blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3ce5143411abc13d9562f4ab8d48fd91f52adb69 | rori4/python_homework | /01_lab/04_inch_to_cm.py | 64 | 3.640625 | 4 | inch = float(input())
cm = inch * 2.54
print(format(cm, '.2f'))
|
8aa4a0fff928ba5f5d0d0c89b244a4f2f956fefe | hubbm-bbm101/lab5-exercise-solution-b2200765015 | /exercise3.py | 352 | 4.0625 | 4 | from random import choice
guess1=int(input("Make a guess(Between 100 and 1):"))
number=choice(range(100))
print(number)
while True:
if guess1 == number:
break
elif guess1 < number:
print("increase your number")
else:
print("decrease your number")
guess1=int(input(""))
... |
d0cd90896d1038347cc89ce8db381db3e55e8aaa | PlaviAjvar/Optimization | /quad_interpolation.py | 2,661 | 3.640625 | 4 | import decimal
import numpy
# finds parabola through 3 points
def find_parabola(x_1, x_2, x_3, y_1, y_2, y_3, epsilon):
# numpy inverse doesnt work directly with Decimal :(
den1 = x_1*x_2 + x_1*x_3 - x_2*x_3 - x_1**2
if den1.copy_abs() < epsilon:
return 0, 0, 0, False
a_11 = -1 / den1
a_21... |
1a160195d19a22c0e91333b53a5b669958631c77 | tomas13perez/QueensSolver | /main.py | 12,830 | 3.859375 | 4 | import random
"""
CSC 412
2/26/2021
@author: Tomas Perez
"""
counter = 0
white_chess_queen = '\u2655'
empty_square = '\u25A1'
white_square_obstacle = '\u25a0'
main_board = []
solutions = []
size = 9
env = []
goal = None
goal_index = -1
iteration_count = 0
perform_mutation = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
"""
This... |
18bb78106f9c77b988e79dd7d0ac9b138478af1e | Pnickolas1/Code-Reps | /AlgoExpert/Algorithms/search_for_range.py | 1,259 | 3.921875 | 4 |
"""
Search for range
binary search version:
given array of sorted numbers and target, return the range of indices
where the target resides within the array
if the target is not in the array, return [-1, -1]
"""
def searchForRange(array, target):
finalRange = [-1, -1]
alteredBinarySearch(array, target, 0,... |
a820b399c63b2f759dfc606f422eff5351d0b9b4 | viniciusaccioly/GerenciadorDownload | /computador.py | 1,280 | 4.21875 | 4 | class Computador:
"""esta classe contem um id único para cada objeto instanciado imutável, e as propriedades ip e recurso que podem ser modificadas """
__id = 0
__ip = 0
def __init__(self, descricao = None):
self.__class__.__id += 1
self.__class__.__ip += 1
self.__descricao = de... |
1ebb4c65a2f8d09217b63fbfcd3bd0ecaab243d8 | RomekRJM/Playground | /Python/python-interview/shopping.py | 1,228 | 3.765625 | 4 | # As we work in online grocery we would like you to compute discount for our clients
# Each client is identified by his name and has list of shoppings assigned to him:
#
# shoppings = [
# Shoppings("Victor", [12.2, 21]),
# Shoppings("Jane", [5.5, 5.1, 5.8, 6.3]),
# Shoppings("Adam", [5, 8, 9]),
# Shoppings(... |
ce6105ccc8398cad5664cb14ad8fea9f37335764 | boeschthomas/python | /chaining_methods.py | 1,129 | 3.5625 | 4 | class User():
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_depost(self, amount, other_user):
self.account_balance += amount
return self
def make_withdrawl(self, amount):
self.account_balance -... |
2f04187ef4ea87961d0582750183a209a537f02d | LeonardoBerlatto/URI | /1005.py | 144 | 3.765625 | 4 | # -*- coding: utf-8 -*-
A = float(input());
B = float(input());
A *= 3.5;
B *= 7.5
MEDIA = ((A + B)/11);
print ("MEDIA = %1.5f" % MEDIA);
|
8c375056fe9d74d7a82f94e009e46bc8311dd6f5 | MohamedAmeer/python-T2 | /day16.py | 787 | 4.1875 | 4 | # multiply two arguments
mul = lambda n1, n2: n1 * n2
n1 = 5
n2 = 15
print("the multiplication of n1&n2 is", mul(5, 15))
# fibonacci series
def fib(m):
r = [0, 1]
any(map(lambda _: r.append(r[-1] + r[-2]), range(2, m)))
print("the fibonacci series is", r)
n = int(input("Enter number:"))
p... |
f6f89004ec568c7df940ced6b206277df7bcb9e5 | ledbagholberton/holbertonschool-machine_learning | /supervised_learning/0x06-keras/3-one_hot.py | 399 | 3.59375 | 4 | #!/usr/bin/env python3
""" Function one_hot
Write a function that converts a label
vector into a one-hot matrix:
The last dimension of the one-hot matrix must be the number of classes
Returns: the one-hot matrix
"""
import tensorflow.keras as K
def one_hot(labels, classes=None):
""" Function one-hot"""... |
30e32317108bb2120fb1ee1e4985d28b3649adf1 | DanielCastillo03/senior-project | /model.py | 1,127 | 3.734375 | 4 | # https://www.python-engineer.com/courses/pytorchbeginner/17-saving-and-loading/
import torch
import torch.nn as nn
# Enter the desired model, this is an example model
# def save_model():
class Model(nn.Module):
def __init__(self, n_input_features):
super(Model, self).__init__()
self.linear = nn.L... |
e5d83b472451facb2a6f38a174e0c8c760bc0182 | avir100/ConsultAdd | /task2/task2_2.py | 2,005 | 4 | 4 | '''
Write a program in Python to perform the following operator based task:
Ask user to choose the following option first:
If User Enter 1 - Addition
If User Enter 2 - Subtraction
If User Enter 3 - Division
If USer Enter 4 - Multiplication
If User Enter 5 - Average
Ask user to enter the 2 numbers in a variable for fir... |
134e2e31b83f4d1e145c88c839d6d093e99640d0 | Vijay1126/Interview-Prep | /Algoexpert/interweavingStrings.py | 582 | 3.765625 | 4 | def interweavingStrings(one, two, three):
if len(one) + len(two) != len(three):
return False
return canInterweave(one, two ,three, 0 , 0, {})
def canInterweave (one, two , three, i, j, cache):
if (i,j) in cache:
return cache[(i,j)]
k = i+j
if k == len(three):
return True
if i <len(one) and one[i] ==... |
a62dbd4f3c75220cf74b843341e25c27d8b88bc6 | ghTravis/ThreadvsProcess | /thread-test.py | 1,724 | 3.625 | 4 | #!/usr/bin/env python
from threading import Thread
from random import randint
import itertools
import sys
import timeit
class Worker:
"""
Worker Class
Initialize the Worker class for the multi-threaded computations
"""
def __init__(self):
# number of computations to perform
self... |
d64878b5299dd131bb8d9e7f04ba383cdb6da03b | wan-catherine/Leetcode | /problems/N2513_Minimize_The_Maximum_Of_Two_Arrays.py | 710 | 3.5625 | 4 | import math
import sys
class Solution:
def minimizeSet(self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int) -> int:
l, r = 1, sys.maxsize
def lcm(a, b):
return a * b // math.gcd(a, b)
def check(m):
a, b = m - m // divisor1, m - m // divisor2
... |
17c8b34b8d0f0b175117754d7794cd70e0e53103 | janeon/automatedLabHelper | /testFiles/primes/primes64.py | 715 | 3.828125 | 4 |
def isPrime(i):
for factor in range(2,i):
if i%factor == 0:
return False
return True
def main():
nth = eval(input("Please feed me a number \"nth\" number of prime sequence index: "))
print("The first", nth, "primes are:")
numbercounter = 0
twins = 0
previous... |
09ee2224f9223e89c3686b06ce9cf994e801837e | mcmadmac11/healthinsurance | /health_insuranceVSCOPY.py | 905 | 3.5625 | 4 |
class healthPlan():
def __init__(self):
def get_deductible(self):
get_deductible = (input('Enter Your Annual Deductible:$'))
deduct = get_deductible
return deduct
def get_procedureCost(self):
opCost = input('Enter the expected cost of your procedure:$')
return opCost
class payor(opCost):
... |
b10b85b264d89422469531c94b4f9156a9acb3a8 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#050 Multiply the number.py | 378 | 3.828125 | 4 | # Jack really likes his number five: the trick here is that you have to multiply
# each number by 5 raised to the number of digits of each numbers, so, for
# example:
#
# multiply(3)==15 # 3 * 5¹
# multiply(10)==250 # 10 * 5²
# multiply(200)==25000 # 200 * 5³
# multiply(0)==0 # 0 * 5¹
# multiply(-3)==-15 # -3 * 5¹
def... |
b4f5f5fc96b0d4b5a8635526e64f52e10d41355c | Jinhyy/python-study | /python-study.py | 2,097 | 4.09375 | 4 | print('hello python')
# 1. 변수
x = 1
y = '안녕'
print(y)
print(x == y) # 결과 False, 값이 틀리므로.
# 2. 타입
x = 1
y = 2
z = 3.0
print(z % y) # 결과 1
print(y ** z) # 제곱근, 결과 8
# 3. 문자열
y = "bye"
z="""안녕하세요 여러 줄의 문자열 따옴표 3개로 할수 있습니다.
하지만 주의해주세요~ ㅎㅎ 엔터도 들어갑니다.
ㅎㅎ
"""
print(y + z)
# 결과
#bye안녕하세요 여러 줄의 문자열 따옴표 3개로 할수 있습니다.
#하지만... |
01299cd31c1724dde6cf8fc0d7b8bb0083c5784b | IVyazmin/MADE_algoritms | /HW_3/Task_D.py | 558 | 3.640625 | 4 | from sys import stdin, stdout
def get_count(array, x):
counter = 0
for value in array:
counter += value // x
return counter
def bin_search(array, k):
left = 0
right = array[-1] + 1
while right - left > 1:
middle = (right + left) // 2
count = get_count(array, middle)
if count >= k:
left = middle
e... |
f0c1e29f2bdd7d261f82f2f5e482a143243d4ca7 | j4p3/fundamentals | /python/interviewcake/highest_product_of_three.py | 3,478 | 4.40625 | 4 | import unittest
from functools import reduce
def highest_product_of_3(list_of_ints):
"""Give the highest possible product of three ints from a list of ints.
Args:
list_of_ints (list[int])
Returns:
int: highest possible product of three elementsi n list
Naive/brute force solution:
... |
2d6219e4ca7d1d5500244b32db5d9effbd1f3d84 | rohitvishal7/flask | /PythonTraining/074KeywordArgumentsDemo.py | 243 | 3.59375 | 4 | def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(12, 24)
# a is 12 and b is 24 and c is 10
func(12, c = 24)
# a is 12 and b is 5 and c is 24
func(b=12, c = 24, a = -1)
# a is -1 and b is 12 and c is 24 |
52957e7ccb600179c07d073a4b2884326e95bb23 | wKenpachw/MorozovAP | /ferstLab/atribute_skill.pyw | 1,215 | 3.75 | 4 | class Atribute_skill(object):
_name = str()
_val = int()
_atr_val = int()
_mastered = bool()
_mastered_val = int()
def __init__(self, name: str, atr_mod_value: int, mastered: bool, mastered_val:int ):
self._name = name
self._mastered = master... |
2ed2c3bfb48c9ce94aa7be7bbcdcd30c7a648e5f | bomminisivaprasad/python-for-everybody-coursera- | /Course 3 - Using Python to access web data/ex13/extracting_data_from_xml.py | 945 | 4.09375 | 4 | # This programme reads an online XML file from which it extracts the values of the <count> tags and sums those values
# Importing libraries
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
# Initialising
total_count = 0
# Asking user to input the source URL of the XML data file
ur... |
d1f43dccb7ccff5394224eaa7edbb19ec1916a98 | Kairo93/is12-programmeerimise_algkursus | /funktsioonid_kodus.py | 654 | 3.75 | 4 | import sys
from random import randint
def display(x, y, text):
sys.stdout.write("\033[" + str(y) + ";" + str(x) + "H" + str(text))
def box(x, y, laius, korgus):
display(x, y, '#' * laius)
height = 0
while height <= korgus:
display(x, y + height, '#')
display(x + laius, y + height, '#')
height +=... |
9e1a72fb417f5dbde8613a95a53a80b77fb44909 | sachazur/AzureAutomation | /3rdDay/Functionalprog.py | 224 | 3.65625 | 4 | #lambda Function:
square = lambda a:a*a
print (type(square))
print (square(4))
def abc(myfun,x):
return myfun(x)
def cube(x):
return x**3
print (abc(cube,5))
print (abc(square,6))
print (abc(lambda d:d*d*d,60))
|
ed477f68d6921178a645a839f13813b5f94e69e3 | StefanMojsic/sqlite3Python | /sqlite3Python.py | 1,384 | 3.65625 | 4 | import sqlite3
import sys
def stampajBazu():
try:
podaci = kursor.execute("SELECT ID, Fname, Lname, Age, Address, Salary, HireDate FROM Employees")
for i in podaci:
print("ID: ", i[0])
print("Ime: ", i[1])
print("Prezime: ", i[2])
print(... |
3efa2ad19e612214f1ea0bb30254d91b2a3782b2 | WonDoY/PSNote | /BOJ/10000-10999/10808b/10808.py | 944 | 3.734375 | 4 | #Alphabet number
#String
def atoi(s):
if(s=='a'): return 0
elif(s=='b'): return 1
elif(s=='c'): return 2
elif(s=='d'): return 3
elif(s=='e'): return 4
elif(s=='f'): return 5
elif(s=='g'): return 6
elif(s=='h'): return 7
elif(s=='i'): return 8
elif(s=='j'): return 9
elif(s=='k... |
c1c1716f1ac19e3d3a68ae0da61e27a02eb88371 | vaughany/advent_of_code | /2019/01.py | 854 | 3.65625 | 4 | #!/usr/bin/python3
# Advent of Code 2019. Day One. http://adventofcode.com/2019/day/1
import sys, time
print ("Advent of Code 2019, Day One.")
timestart = time.time()
out1 = out2 = 0
with open('01.txt') as instructions_file:
# instructions = instructions_file.readlines()
instructions = instructions_file.r... |
743b11a4a552d96900927d58adaf8c866645346c | chkche1/Slicr | /slicr/sourcer.py | 2,440 | 3.765625 | 4 | #!/usr/bin/env python
import urllib2
class Sourcer(object):
"""A general class that is responsible for retrieving data
Args:
data_source: URL that's used to retrieve data
custom_properties: A map that's used to help the Sourcer object retrieve data
Raises:
NotImplementedError: Raised if load_data... |
160874929742ccf41d9e1d5be9f9a85e86b4b314 | LiaoYuxuan/MCM-ICM | /Binary_Search.py | 1,101 | 3.828125 | 4 | data = [2, 4, 5, 7, 8, 9, 12, 14, 17, 19, 22, 25, 27, 28, 33, 37]
target = 28
# Linear Search
def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i
return 'not found'
# Iterative Binary Search
def binary_search_iterative(data, target):
low = 0
... |
d6861da1aa90a3451739a07d6da53699aea2a116 | StanikLukasz/compilator | /AST.py | 4,165 | 3.671875 | 4 | ## Table of contents
#
# 0. Base Node class
# 1. Initial rules
# 2. Statement types
# 2.1 Condition statements
# 2.2 Values range
# 3. Instruction types
# 3.1 Assignment operators
# 4. Expressions
# 4.1 Array definition (and array line used in other structures)
# 4.2 Array special functions
# 4.3 Array tran... |
1542cf76a498c99b318fce7e669ed55f01c267f9 | ericanaglik/Tweet-Generator | /probability.py | 932 | 3.84375 | 4 | import random
words = [1,2,3,4,5,6,7,8]
new_words = ["one", "two", "red", "blue", "fish"]
frequency = [1, 1, 1, 1, 4]
denominator = int(len(words))
frequency_percent = []
for i in frequency:
frequency_percent.append((i/denominator))
print(random.choices(new_words,frequency_percent,k = 8))
def frequency_tester():... |
5d9fd7227f038139bf722e41fb23004e75e78302 | kumaya/python-programs | /graph/transitive_closure.py | 857 | 3.734375 | 4 | # Transitive Closure of a Graph using DFS
from collections import defaultdict
class Graph(object):
def __init__(self, v):
self.vertices = v
self.graph = defaultdict(list)
# to store transitive closure
self.tc = [[0 for j in range(self.vertices)] for i in range(self.vertices)]
... |
e236fc6315db88bf4a3ed2cb47d14b3c34b9936c | roque-brito/ICC-USP-Coursera | /icc_pt1/exe_extras/ex03_roque.py | 375 | 3.90625 | 4 | # Escreva a função vogal que recebe um único caractere como parâmetro e
# devolve True se ele for uma vogal e False se for uma consoante.
# ---------------------------------------------------------------------
def vogal(x):
letras = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
if x in letras:
... |
7209d712f98dc1f06da372564bd1ac8b8648adad | EmmanuelTovurawa/Python-Projects | /Class_Work/Chapter 9/chapter9_pg_234.py | 891 | 3.625 | 4 | class Users:
def __init__(self, first_name, last_name, age, race):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.race = race
self.login_attempts = 0
def describe_user(self):
print(f"{self.first_name} {self.last_name} is {self.age} year old person of race {self.race} has {se... |
0dd8e5741f17a5a46c8c158dd9ecd35e65a6bc64 | threeHardWorker/charts | /graph/lines.py | 629 | 3.5 | 4 | # -*- coding: UTF-8 -*-
# author: star
# created_at: 18-2-1 20:35
class GraphLine(object):
def __init__(self, ax, data_x, data_y, color='b', sz='8', sp='o', zo=1, ap=1):
self.ax = ax
self.color = color
self.size = sz
self.shape = sp
self.data_x = data_x
self.data_y ... |
cec711fe7003ebfe6abea8024d89a6e54d73850d | sureshkandula/python-suresh-git | /Dictionaries/Dictionaries.py | 1,149 | 3.9375 | 4 | '''
string={'a':"this is a dictionary file",'b':"i know that",'c':"ok boss"}
print(string['a'],string['b'],string['c'])
print(dict(string))
print(dict(enumerate(string)))
del string['c']
print(string)
'''
"""
suresh={'lastname':'kandula', 'middlename':'venkat'}
print('name of last name::{0} and his middle name::{1}... |
5a9493c01d96feca69a2e85d4c9db3f3316eb546 | GhostDovahkiin/Introducao-a-Programacao | /08-Exercício-Aula-8/Lista-Laboratório/10.py | 712 | 3.609375 | 4 | import bibliotecacorreios
tipoitem = str.lower(input("Digite o tipo de item: "))
peso = float(input("Digite o peso do item(Kg): "))
tamanho = str.lower(input("Digite o tamanho da embalagem: "))
tipoentrega = str.lower(input("Digite o tipo de entrega: "))
bibliotecacorreios.validaEntrega(tipoentrega)
entrega = bibliot... |
bd94f63ae7cc2e8c3d71e32b342595c7cfd17e43 | matteo-conti-97/Cycle_Detection | /Final/creaGrafiRand.py | 4,421 | 3.546875 | 4 | import random
import graph.Graph_AdjacencyList as grafo
# In questo file vengono generati grafi random con e senza cicli per la fase di testing
# Viene creato un grafo con ciclo in cui ogni vertuce ha un arco col successivo e l'ultimo vertice ne ha uno con il primo
#Il grafo creato e' il caso peggiore di grafo con ci... |
9e41d9a8a5e0aa90efaa141dba0018e22859628d | brunozupp/TreinamentoPython | /exercicios/exercicio036.py | 433 | 3.875 | 4 | if __name__ == '__main__':
valorCasa = float(input("Qual o valor da casa = "))
salarioComprador = float(input("Salário do comprador = "))
quantosAnos = int(input("Quantos anos deseja pagar = "))
prestacaoPorMes = valorCasa / (12 * quantosAnos)
if prestacaoPorMes > (salarioComprador * 0.3):
... |
501f51e25d57ce9d8e0408e077fa98e5fa898bdf | ESMValGroup/ESMValTool | /esmvaltool/diag_scripts/cmug_h2o/convert_h2o.py | 1,125 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions to convert water vapour variables.
###############################################################################
convert_h2o.py
Author: Katja Weigel
EVal4CMIP + ESA-CMUG project
##############################################################################... |
31dcf8cd3db6f20524311379e2338342cd10413b | satrini/python-study | /exercises/exercise-2.py | 152 | 3.9375 | 4 | # Calculate grade
n1 = float(input("Student's grade 1: "))
n2 = float(input("Student's grade 2: "))
print("Grade average: {:.2f}".format((n1 + n2) / 2)) |
f9b3ff9ad074625e4eb7ad9315bcf4ab9ff93d3a | eamonyates/pp2_Odd_Or_Even | /pp2_OddEven.py | 736 | 4.25 | 4 | #! usr/bin/env python3
def odd_even():
user_number = int(input("Please enter a number: "))
if (user_number % 4) ==0:
print ("\nYou have chosen a number divisible by 4")
elif (user_number % 2) == 0:
print ("\nYou have chosen an even number")
else:
print ("\nYou have chosen an odd number")
print ("\nNow lets... |
91ab0f4d1178892af5f7f0d4f0065b7d0615020a | 317702550/THC | /OK/Python/FigurasGeométricas.py | 3,096 | 3.96875 | 4 | #!/usr/bin/python3
# Maximiliano Proaño Bernal, Antonino Equihua
# Triángulo equilátero de lado 2
# con un vértice en el origen en
# el cuadrante I y un lado sobre el eje x
# Coordenadas del triángulo:
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
x1 = 0
y1 = 0
x2 = x1+2
y2 = y1
x3 = x2/2
y3... |
b8baa06d18d6c6c25485cceaa0ff32f5ab7debe0 | pomacb/CursorPython | /YoungDevelopers/Homework8/while1.py | 194 | 3.59375 | 4 | total = 100
while total > 0:
n = int(input())
if total >= n:
total = total - n
else:
print ("Not permitted")
break
print("Ресурс вичерпано")
|
ce98fd7e1eefa95ee7e5a0d2b5aa0887517f36fc | itshui3/cs-module-project-recursive-sorting | /src/sorting/quickSort.py | 615 | 3.796875 | 4 | # pivot always first element implementation
def quick_sort(arr):
# catch-case logic
if not len(arr):
return []
# initialization logic
pivot = arr[0]
less_than = []
greater_than = []
for i in arr[1:]:
if i >= pivot:
greater_than += [i]
else:
l... |
8064a9ec1edac0442efd95ee206a59fd49bbc85a | gcgc100/leetcodeSolution | /solutions/9-palindrome-number/solution.py | 460 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
"""
Determine whether an integer is a palindrome. Do this without extra space.
"""
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0 or (x!=0 and x%10 == 0):
re... |
cadf226c949967d2d604a30b514dd9b5ff3251d7 | VincentHuto/Python | /Tessst.py | 1,963 | 3.875 | 4 | from turtle import Turtle, Screen
import random
import math
def draw_square(some_turtle):
for _ in range(4):
some_turtle.forward(200)
some_turtle.right(90)
def draw_art():
# Turtle Angie
dick = Turtle(shape="turtle")
dick.color("blue")
dick.pensize(3)
dick.speed(0) # slightly slow... |
98d74ccf1da09780130cd04ce41c9b7458e51ae0 | lzafmn/PythonExercises | /Maclaurin.py | 616 | 3.65625 | 4 | from math import pi
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-pi, pi, 200)
def mtpow(x):
return x*mtpow(x-1) if x>0 else 1
def SIN(x0, N):
n = 0
y = 0
while (2*n + 1) <= N:
y += (-1)**n*(x-x0)**(2*n+1)/mtpow(2*n +1)
plt.plot(x, y, label=str(2*n+1))
n +... |
59a8967faf9bef71474ef699049835aa3580cbbe | alan-turing-institute/defoe | /defoe/nzpp/article.py | 2,602 | 3.734375 | 4 | """
Object model representation of an article in a New Zealand Papers Past
newspaper represented as an XML document.
"""
from datetime import datetime
class Article(object):
"""
Object model representation of an article in a New Zealand Papers
Past newspaper represented as an XML document.
"""
d... |
742463c29b8bd15f3f6a8d5ddb6ecf97b9e83b28 | gokseltokur/Turkish-NLP | /word.py | 708 | 3.9375 | 4 | class Word:
def __init__(self, name, _type):
self.letterValue = {'a': 1, 'b': 2, 'c': 3, 'ç': 4, 'd': 5, 'e': 6, 'f': 7, 'g': 8, 'ğ': 9, 'h': 10, 'ı': 11,
'i': 12, 'j': 13, 'k': 14, 'l': 15, 'm': 16, 'n': 17, 'o': 18, 'ö': 19, 'p': 20, 'r': 21,
's': 22... |
aca446740c006a474bc9caa76c67f9c667f02c32 | 9842911312/medd | /pr1.py | 117 | 3.703125 | 4 | s=input("enter the string 1")
s1=input("enter string 2")
for i in range(0,len(s)):
if s[i]==s1[i]:
print(s[i])
|
0ed2562916daeaf8ed19b53b9e0d9da74c8d6e28 | BabaninGA/CP9 | /9.py | 639 | 3.765625 | 4 | def hl():
if X%2==1:
b="нижнее"
else:
b="верхнее"
return b
def cb():
if X<=36:
c="купе"
else:
c="боковое"
return c
try:
print("Введите номер места в плацкартном вагоне")
X=int(input())
except ValueError:
print("Номер места может быть только целым числом")
exit()
if 1<=X<=54:
print("место:"+hl()+"_"... |
fa7eb98d12de70fc9178da5278a7f4305ecf4c90 | Siddharthcmd/Python_Codes | /generate_ticket.py | 1,663 | 4.3125 | 4 | '''
Write a python program to generate the ticket numbers for specified number of passengers
traveling in a flight as per the details mentioned below:
The ticket number should be generated as airline: src: dest: number
where
Consider AI as the value for airline
src and dest should be the first three characters of the... |
201d05d937080e5de11547703e8b6399cf2d63ec | mcriech/ME701 | /HW3/HW3_Prob1/Fourier_Transform.py | 843 | 3.515625 | 4 | '''
Created on Oct 13, 2014
@author: michael
'''
from Continuous_Orthogonal_Basis import Cont_Orth_Basis
from fourier import Fourier
class Fourier_Trans(Cont_Orth_Basis):
'''
classdocs
'''
def __init__(self, n):
'''
Build the continuous orthoganal basis from the fourier polynomials.
... |
7960e8fd2b185b925a74e66dcb090d4978c53787 | DragonWarrior15/Coursera | /University_of_California/Advanced_Algorithms_And_Complexity/Week01/io.py | 1,366 | 4.375 | 4 | try:ing is cheap, ifing is expensive
If you have code like this:
if somethingcrazy_happened:
uhOhBetterDoSomething()
else:
doWhatWeNormallyDo()
And doWhatWeNormallyDo() would throw an exception if something crazy had happened, then it would be faster to arrange your code like this:
try:
doWhatWeNormall... |
3e1da25558eba23d156eddcd031ca261a16dbddd | danilodelucio/Exercicios_Curso_em_Video | /ex031.py | 343 | 3.8125 | 4 | dist = float(input('Digite a distância de uma viagem em Km: '))
print('Você está prestes à começar a sua viagem de {}Km.'.format(dist))
preço = dist * 0.50 if dist <= 200 else dist * 0.45
'''if dist <= 200:
preço = dist * 0.50
else:
preço = dist * 0.45'''
print('E o preço da sua passagem será de R$ {:.2f}.'.for... |
4aee2b37ff2693dba3e4eadb8622cf73d69729f9 | codingscode/curso_python | /Work001/file026_default-dict.py | 1,091 | 4.40625 | 4 | """
Modulo Collections - Default Dict
Default Dict - Ao criar um dicionario utilizando-o, nós informamos um valor default(padrão), podendo
utilizar um lambda para isso. Este valor será utilizado sempre que não houver um valor definido.
Caso tentemos acessar uma chave que não existe, essa chave será criada e o v... |
7cf07c497d649ff1aff589269eae417435780484 | tomr-stargazer/euler | /problem2.py | 1,363 | 4.125 | 4 | """
Even Fibonacci numbers
Problem 2
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 exceed four million, find the ... |
160ca7e43c9976e96fb1888152b867714f0f0931 | Zeronimo-commits/FirstRepo | /python issues/issue_one_coins.py | 294 | 3.5625 | 4 | ls1 = ["steal", "steal", "share"]
ls2 = ["steal", "share", "steal"]
def get_coin_balances(lst1, lst2):
a, b = 3, 3
for i, j in zip(lst1, lst2):
if i == 'share': a, b = a-1, b-3
if j == 'share': a, b = a+3, b-1
return [a, b]
a= get_coin_balances(ls1, ls2)
print(a)
|
cd0bde8c72fa9221d136bfe55aad249902dc8855 | fadhiladiahap/Fadhila-Diah-Ayu-P._I0320038_Andhika_Tugas5 | /I0320038_Soal2_Tugas5.py | 483 | 3.8125 | 4 | # input data
nama = input ("Nama: ")
nilai = int (input ("Nilai: "))
output = "Halo, " + nama + "!" + " Nilai Anda setelah dikonversi adalah "
if 85 <= nilai <= 100:
print(output, 'A')
elif 80 <= nilai <= 84:
print(output, 'A-')
elif 75 <= nilai <= 79:
print(output, 'B+')
elif 70 <= nilai <= 74:
print(... |
e469cfadbb3068acf0ef1fca3b2d2bdfdf78d47e | FishRedLeaf/my_code | /leetcode/分组刷题/1数组/1找规律/48旋转图像.py | 715 | 4.09375 | 4 | class Solution:
def rotate(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
# 1 将矩阵进行上下翻转
# 2 将矩阵沿着轴对角线轴对称的元素交换
rows, cols = len(matrix), len(matrix[0])
for i in range(rows//2):
matrix[i], matrix[rows-i-1]... |
0593fdc19fe577743fb5bfa79261e3382b06e3eb | praneethinturi/testrepo | /test.py | 192 | 4.03125 | 4 | x=5
y=10
z=x+y
if(z==15):
print("Correct")
else:
print("Wrong")
if(x==5):
print(10*"Correct\n")
print("The value of x is 5")
else:
print("The value of x is not 5")
|
912be4ea85e623c881be504004f637f205d97610 | shuowenwei/LeetCodePython | /Medium/LC1891TODO.py | 1,896 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/cutting-ribbons/
https://walkccc.me/LeetCode/problems/1891/
LC875, LC1011, lC1891
go read https://www.geeksforgeeks.org/maximum-length-possible-by-cutting-n-given-woods-into-at-least-k-pieces/
"""
class Solution(object):
def maxLeng... |
796ee5764a1abd982317453edab24c6c0d28c717 | Nepgy/Desafio_Nubimetrics | /Desafio 08/desafio_8.py | 1,093 | 3.65625 | 4 | #Definimos nuestra funcion
#Los parametros los tomamos como INT para poder operar con ellos
def generarPathUltimosDias(fecha, dias):
#Creamos lista Vacia para realizar el .append
lista_paths = []
#Tomamos el string Fecha y extraemos por separado dia, mes, año para armar el path
dia = str(fecha)[-2:]
... |
fbf1f445e45e174cc971321ab3f92adaa3de702b | DevRyu/Daliy_Code | /DataStructure/graph(DFS).py | 1,896 | 3.765625 | 4 | # 23-18 깊이우선 탐색
# BFS(Breadth First Search) : 노드들과 같은 레벨에 있은 노드들 큐방식으로
# DFS(Depth First Search) : 노드들의 자식들을 먼저 탐색하는 스택방식으로
# 스택 방식으로 visited, need_visited 방식으로 사용한다.
# 방법 : visited 노드를 체우는 작업
# 1) 처음에 visited에 비어있으니 시작 노드의 키를 넣고
# 2) 시작 노드의 값에 하나의 값(처음또는마지막 인접노드들)을 need_visit에 넣는다,
# 2-1) 인접노드가 2개 이상이면 둘 중 원하는 방향... |
bc834cf0859a76bafd2e2755f6714614d18408b4 | chenzm918/czm001 | /zhengli2.py | 1,039 | 3.546875 | 4 | #计算这个矩阵的对角线[[3,8,9], [6,11,2], [7,18,5]]
#编写输入任意一张银行卡号,输出银行卡号的前6位和后4位,剩下的所有数字用星号(*)表示
#如:card("5189301239921331") -> 518930******1331
# card=input("请输入银行银行卡卡号:")
# a=card[7:-4].replace(card[7:-4],"*")
# b=card[0:6]
# c=card[-4:]
# def yinhangka(card):
# if isinstance(card,str) and
# a = card[0:6]
# ... |
b8b4cb71a31689f6a733c4215b175b704ac88125 | vkoprivica/100_Days_of_Python | /days_13-15_games/r_p_s_game.py | 1,420 | 3.90625 | 4 | from r_p_s_classes import Player, Roll
import random
def main():
print_header()
rolls = build_the_three_rolls()
name = get_players_name()
player1 = Player(name)
player2 = Player("Computer")
game_loop(player1, player2, rolls)
def game_loop(player1, player2, rolls):
count = 1
p1_co... |
1e2f71599d19c936c84a744d9df89e462460dc9e | hasibul442/uri-online-judge-in-python3 | /1065 - Even Between five Numbers.py | 182 | 3.734375 | 4 | list1 = []
count= 0
for i in range(0,5):
x = int(input())
list1.append(x)
for i in range(0,5):
if(list1[i]%2==0):
count = count+1
print(count,"valores pares")
|
819795205e82e3b5d217f37acbabcc1b1c6968f4 | DanielBMeeker/module_7 | /fun_with_collections/sort_and_search_array.py | 1,708 | 4.21875 | 4 | """
Program: sort_and_search_array.py
Author: Daniel Meeker
Date: 6/21/2020
This program defines two functions to search or sort an array.
"""
import array as arr
def sort_array(a_array):
"""
This function will take an array and sort it. It explicitly converts to an array
in case the user tries to pass i... |
fb7516e0d817b563a13c65b751a5039428ce6f28 | matheus0214/application_flask_learn | /aulas/aula1/comprehension.py | 142 | 3.625 | 4 | colors = ["Green", "Red", "Blue"]
list = [c for c in colors]
list_filter = [c for c in colors if c != "Red"]
print(list)
print(list_filter)
|
417e8111feb77d389fa801770c56eff20e0cb989 | hp15071hp/Parallelization | /parallelization/Parallelization.py | 4,528 | 3.5 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2014/4/18
@author: Ivy Liu
'''
import threading
import time
from robot.libraries.BuiltIn import BuiltIn
from robot.errors import ExecutionFailed, ExecutionPassed, ExecutionFailures
_errors = []
_condition = threading.Condition()
class Parallelization:
global _errors ... |
35989dbb2f8f16a1c3c23d8fd10edd5e4a9af9f4 | ashu20031994/HackerRank-Python | /Day-3-Comprehensions, intro to files & directories/1.Zipped.py | 1,236 | 4.34375 | 4 | """
zip([iterable, ...])
This function returns a list of tuples. The th tuple contains the th element from each of the argument sequences or iterables.
If the argument sequences are of unequal lengths, then the returned list is truncated to the length of the shortest argument sequence.
Task
The National University ... |
1b22851822a7b3bc83b26fb4c73cb1483b54cf59 | webturing/ACM | /oj.ahstu.cc/1182.py | 145 | 3.65625 | 4 | import sys
for line in sys.stdin.readlines()[1:]:
print ''.join([char.upper() if char.islower() else char.lower() for char in line.strip()]) |
2ef807c0fcb6d13ed4bfc3fbb66f4806beb3d145 | onsare/oop | /oop.py | 1,791 | 4.40625 | 4 |
#methods
class Book(object):
"""Methods are basically functions within
a class. The first definition of a method
has to be a reference "self" to the instance
of the class
"""
def __init__(self, name):
self.name = name
#constructor
"""
The __init__ keyword acts as a constructor in python
Though strictly sp... |
aca5d1186d646b937866324d77246eb9e0f8a6e1 | janeenyamak/reciepeGenerator | /recipe.py | 4,805 | 3.796875 | 4 | ### This Program will generate the GUI of our application
### INPUT: List of ingredients
### OUTPUT: A single image
#Libraries necessary in order to run our application
from io import BytesIO
from PIL import Image, ImageTk
import requests
import tkinter as tk
import webbrowser
import random
#this will set up the win... |
71a609c08cbf64faee0deb7794e15067e2f3a1a1 | Ruslan-Dziov/GB_Python | /lesson8_hw1.py | 1,544 | 3.90625 | 4 | """
1. Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год».
В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать число, месяц,
год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, должен ... |
0bb78d1a374cca70b158c31e42e1c2f71e1d7bc9 | Ganesh-sunkara-1998/Python | /Important codes/factorial problem.py | 196 | 4.125 | 4 | ''' factorial program....'''
def factorial (num):
if num==0:
return 1
else:
return num*factorial(num-1)
def main():
res=factorial (3)
print(res)
main()
|
ce0904381d9fcfbfda9553841828fa977af4bfba | victorcarnaval/uri-online-judge-exercises | /iniciante/uri_1061.py | 587 | 3.609375 | 4 | start_date = input()
[start_hour, start_min, start_sec] = [int(x) for x in input().split(' : ')]
end_date = input()
[end_hour, end_min, end_sec] = [int(x) for x in input().split(' : ')]
seconds = end_sec - start_sec
minutes = end_min - start_min
hours = end_hour - start_hour
days = int(end_date[4:]) - int(start_date[4... |
4bb591aedb0cd872ff3d2f823b82800c9e276843 | kannix68/advent_of_code_2017 | /day03/day03b_ext.py | 907 | 3.53125 | 4 | # code !stolen!
# see: [-- 2017 Day 3 Solutions -- : adventofcode](https://www.reddit.com/r/adventofcode/comments/7h7ufl/2017_day_3_solutions/)
# see: https://www.reddit.com/r/adventofcode/comments/7h7ufl/2017_day_3_solutions/dqox0fv/
from itertools import count
from collections import defaultdict
def sum_spiral():
... |
97111e2a67b26c7b305f086bff9a223dd010b726 | probcomp/iventure | /external/seaborn/dist/examples/heatmap_annotation.py | 354 | 3.515625 | 4 | """
Annotated heatmaps
==================
"""
import seaborn as sns
sns.set()
# Load the example flights dataset and conver to long-form
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")
# Draw a heatmap with the numeric values in each cell
sns.heatmap(flights, an... |
4fca697050a603d0225895eca47b5da5560db84f | tahir24434/py-ds-algo | /CodingInterviewProblems/DynamicProgramming/bt4_sublists.py | 1,275 | 4.03125 | 4 | """
In earlier examples, jane, bob != bob, jane. In this example, jane, bob == bob, jane.
where they went into solution VS whether they went into solution ???
https://www.youtube.com/watch?v=J_odcqzHGqw&list=PLnfg8b9vdpLn9exZweTJx44CII1bYczuk&index=18
"""
def sublists(S):
chosen = []
_sublists(S, chosen)
d... |
f67d5625ce55f174e8e961c828dd4d58d934aa5e | alexioso/Neural-Network | /neural_network.py | 5,192 | 3.703125 | 4 | class NeuralNetwork:
def __init__(self, units_per_layer_array, learning_rate):
""" Args:
- units_per_layer_array: an array containing the number of neurons in each layer
its length is equal to the number of layers, including the
... |
bf021d12ca2b443a722e3029f6cf11b4090dd253 | Yara7L/python_algorithm | /leetcode2/58_oddEvenList.py | 1,435 | 3.828125 | 4 | # 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。
# 请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。
#
# 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。
class ListNode(object):
def __init__(self, num):
self.value = num
self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
... |
82998864cd0cfe43cd461ee8695015fa698624f9 | EduVencovsky/Ven-Task-Manager | /validator.py | 497 | 3.546875 | 4 | func = {
"init": [
"--y"
]
}
def init(params):
print(params)
def call(argv):
method = ""
options = []
arguments = []
if func[argv[1]]:
print("method found is " + argv[1])
method = argv[1]
else:
raise KeyError(argv[1])
for arg in argv[2:]:
... |
13c7a7abf9d68720214e493e7f6806fb96114fd4 | snirmagram/pythonProject2 | /games/cards/Class_card.py | 1,143 | 3.8125 | 4 | class Card:
def __init__(self,value,suit):
self.value=value
self.suit=suit
self.suits={1:"Diamond",2:"Spade",3:"Heart",4:"Club"}
self.values={11:"Jack",12:"Queen",13:"King",14:"ace"}
def __str__(self):
if self.value > 10:
return f"{self.values[self.value]}:... |
6c7355d58377938bdc4153e9b4d6b6e9782040c4 | ybalenko/practice_exercises | /02_alphabet/alphabet.py | 594 | 4.09375 | 4 | """
There is an alphabet which has the following characteristics:
- language
- letters
Print all the letters
Count letters.
"""
class Alphabet():
def __init__(self, language: str, letters: str):
if type(letters) != str:
raise Exception('Unexpected input for letters')
if type(langu... |
d79158566242dfb4feff02088ffb940633e39c8f | thaddeuspearson/Intro_Comp_Sci | /Problem_Set_1/ps1b.py | 1,385 | 4.4375 | 4 | #!/usr/bin/env python3
# Problem Set Directions:
# https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/assignments/MIT6_0001F16_ps1.pdf
# Helper Functions
def interest(savings):
return (savings * .04) / 12
def semi_... |
ef4d636e4cb07d51ac648c063bf42e065c13e71e | RUCS24/ProgrammingExamples | /python/triangle_checker.py | 980 | 4.59375 | 5 | # Checks what type of triangle the 3 sides form
def triangle(a, b, c):
# Put the sides into a sorted array, so the shorter 2 sides come first
sides = [a, b, c]
sides.sort()
# If the sides don't fulfill the triangle inequality (a + b > c),
# these side lengths can't form a triangle
if sides[0] + ... |
6d976d62cbdd750aab4e36f5b22fe703aa80ee3a | shaharam/practice-python | /exercises/seven_boom.py | 444 | 3.859375 | 4 | # The function gets an int and print all the numbers from 1 to int
# if the num divisible by 7 or 11 using modulo print "boom"/"trach"
# Declare constants for later change
BOOM = 7
TRACH = 11
def seven_boom(x):
for i in range(1, x+1): # Run from 1 to x (inclusive)
if i % BOOM == 0:
print ... |
ea291219b52292647b4aa1b8f94eaed1abe8ec20 | StefanCondorache/Probleme_Fisier | /Problema_4.py | 211 | 3.578125 | 4 | with open("input.txt","r") as i:
x=int(i.readline())
list1=list((str(x-2)+' ',str(x-1)+' ',str(x)+' ',str(x+1)+' ',str(x+2)))
with open("output.txt","w") as o:
for y in list1:
o.write(y) |
961058d762b890ac9cce2f695ad4f8dffae48924 | SubhoBasak/Algorithm | /PostfixExpEvaluator/PostfixExpEvaluator.py | 728 | 3.640625 | 4 | class Stack:
def __init__(self):
self.__items = []
def push(self, value):
self.__items.append(value)
def pop(self):
return self.__items.pop()
def isEmpty(self):
if len(self.__items) == 0:
return True
return False
def evaluator(st):
lst = list(s... |
c722803b6471d46275666f8da009601d9ecf894d | devendraingale2/PythonPrograms | /complexaddition.py | 469 | 3.765625 | 4 | try:
def add(r1,r2,i1,i2):
real=r1+r2
imag=i1+i2
print("After Addition..")
print("Complex Number is:",real,"+",imag,"i")
print("Number 1.")
real1=float(input("Real part1:"))
imag1=float(input("Imaginary Part1:"))
print("Number 2.")
real2=float(input("Real part2:"... |
602fc2470ef3241e2b0e118e0ba7a78c0f69c10a | mcewenar/PYTHON_INFO_I_BASIC | /anidadoClases.py | 1,479 | 4.25 | 4 | #Herencia: issubclass()
#Python ofrece una función que es capaz de identificar una relación entre dos clases, y aunque su diagnóstico no es complejo,
#puede verificar si una clase particular es una subclase de cualquier otra clase.
#Así es como se ve:
#issubclass(ClaseUno, ClaseDos) True si ClaseUno es subclase de ... |
6ff6a85badd48b60723db790b942118509645771 | arypb1cbka/stepik-auto_test_course | /3.2.8_lesson_assert.py | 695 | 3.53125 | 4 | ###Вам дана функция test_input_text, которая принимает два значения: expected_result — ожидаемый результат, и actual_result — фактический результат. Обратите внимание, input использовать не нужно!
###Функция должна проверить совпадение значений с помощью оператора assert и, в случае несовпадения, предоставить исчерпыв... |
941dc57a441d3b5dd61ef44fdee9ddcffd393262 | WangRongsheng/Python-functions | /functions/ord函数详解.py | 679 | 4.125 | 4 | '''
描述
ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。
语法
以下是 ord() 方法的语法:
ord(c)
参数
c -- 字符。
返回值
返回值是对应的十进制整数。
'''
print(ord('a')) #输出97
print(ord('b')) #输出98
print(ord('c')) #输出99
prin... |
ebb0264c1bbd610d48bbd74a7f83045e413f049e | python-cookbook/PythonStudy | /p02_personal_summary/p08_lee_yong_eun/p01_week/p02_thursday/Ch2-13.py | 1,344 | 4.09375 | 4 | ####################################################################################################
# 2.13] 텍스트 정렬
# * 텍스트를 특정 형식에 맞추어 정렬하고 싶다.
#
# 1] ljust(), rjust(), center()
# : 좌정렬, 우정렬, 가운데
# 2] format()
# : 인자로 <. >, ^ 사용
####################################################################################... |
c943845df042e4c7af0899153342737e30677556 | Ankur-v-2004/Class-12-ch-1-python-basics | /prog_multretclass12.py | 251 | 3.90625 | 4 | #Program to iilustrate return statement returning multiple values
def add_diff(x,y):
add = x+y
diff = x-y
return add,diff
a,b = add_diff(200,180)
print("The sum of two numbers is :",a)
print("The difference of two numbers is :",b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.