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
0b1121f1e838150882e447b93131d8129c55c576
cIvanrc/problems
/ruby_and_python/python_oop/multilevel_inheritance.py
427
3.765625
4
class MusicalInstruments: number_of_major_keys = 12 class StringInstruments(MusicalInstruments): type_of_wood = "Tonewood" class Guitar(StringInstruments): def __init__(self): self.number_of_string = 6 print("This guitar consits of {} string. It is made of {} and it can play {} keys"...
68456f7fa3638ae327fc6874c22b74099b28f351
cIvanrc/problems
/ruby_and_python/3_list/find_max.py
648
4.28125
4
# Write a Python program to get the smallest number from a list. # max_num_in_list([1, 2, -8, 0]) # return 2 def find_max(): n = int(input("How many elements you will set?: ")) num_list = get_list(n) print(get_max_on_list(num_list)) def get_list(n): numbers = [] for i in range(1, n+1): ...
f1691f8fc22ef23cf27ee1926c49722d6a421b31
Eldalote/CDP-Component-Database-Program
/Component-Database/Subs/db_handler.py
10,037
3.71875
4
from tkinter import * from tkinter import messagebox import sqlite3 from sqlite3 import Error from icecream import ic class component_database: def __init__(self, db_path): self.db_path = db_path self.conn = self.open_connection() def open_connection(self): """Create a databas...
9600319f92cf09f3eef5ec5e5cdfbe80c2c8e81a
asingleservingfriend/PracticeFiles
/regExpressions.py
1,796
4.125
4
import re l = "Beautiful is better than ugly" matches = re.findall("beautiful", l, re.IGNORECASE) #print(matches) #MATCH MULTIPLE CHARACTERS string = "Two too" m = re.findall("t[wo]o", string, re.IGNORECASE) #print(m) #MATCH DIGITS line = "123?34 hello?" d = re.findall("\d", line, re.IGNORECAS...
5092dc06fae99dc25a6ca94b70075ba52798dce6
tonchik-tm/yandex-checkout-payout-sdk-python
/src/yandex_checkout_payout/domain/common/xml_helper.py
6,191
3.5
4
import re import var_dump from lxml import etree class XMLHelper: @staticmethod def object_to_xml(obj): serializer = Object2XML() return serializer.parse(obj) @staticmethod def xml_to_object(xml): deserializer = XML2Object() return deserializer.parse(xml) """ Object...
e5236755c068102517c568d13afd071c32a6cb26
cesaroll/pythonPath
/pythonFundamentals/08-Iterables/iteration.py
397
3.71875
4
import math from itertools import islice, count def is_prime(x): if x < 2: return False for i in range(2, int(math.sqrt(x)) + 1): if x % i == 0: return False return True def sumPrimes(maxNu return sum(islice((x for x in count() if is_prime(x)), maxNum) ) def run_sumPrimes(...
ec9efd8a576d35a0b91afccacc0fa07000d8bbfa
Omnifarious/GaloisField
/polyops.py
6,949
3.734375
4
"""This module implements a set of functions that allow an iterable over a set of elements to be treated as a list of coefficients to a polynomial. It tries to be as agnostic about the types of the coefficients as possible. It uses the standard +, -, * and / operators to operate on the coefficients. It assumes the ad...
61ab0fbfc3e3a00048a56f005b93b5e7a42ecd1b
alexlamgit/cs50
/pset6/readability/readability.py
1,534
3.671875
4
# Computes the approximate grade level needed to comprehend some text import cs50 def main(): # Calculate with the results of stuff... text = cs50.get_string("Text: ") # Again... words = numwords(text) # Again... letters_per100 = (numletters(text) * 100) / words sentences_per100 = (nums...
4f25342b2b01e741366cf006ffb63d2324e8e2f1
Zanarh/stuff
/filter-0911.py
3,025
3.640625
4
# Build 11.09.2012 # This program splits each line of a given text file according to # a given list of characters, i.e. the text is split at each # character, if present within the text. # This program has only been tested with the following files: # testing.tbl, testing.ext # and with the following inputs: # >> 2 ...
10a1d131ff6eb33d0f12d8aa67b3e9fd93e05153
christianmconroy/Georgetown-Coursework
/ProgrammingStats/Week 8 - Introduction to Python/myfunctions.py
2,006
4.375
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 07 18:33:25 2018 @author: chris """ # -*- coding: utf-8 -*- """ Created on Wed Mar 07 18:29:10 2018 @author: chris """ # refer slide 41 # Program with functions # Name this program withfunctions.py # the entire program; there is one small change # that small change is ...
551b27fa10a71889c51d39c5a41cfd877eb5a3c2
1220x/game_play
/game_play.py
1,991
3.671875
4
import random import time while True: player_value = 0 enemy_value = 0 for i in range(3): player_life = random.randint(100,150) player_attack = random.randint(30,50) enemy_life = random.randint(100,150) enemy_attack = random.randint(30,50) print('-----现在是第...
0c91ea1ca105fa8eb3c3e6dedf00771c09777e9a
dakshdiwan/Python_Hadoop_MapReduce_MarketBasketAnalysis
/dataset_generator/generate_items.py
981
3.5625
4
import json def initialize_json(): try: with open("items/item_list.json", "r") as itemjson: items = json.load(itemjson) except: jsondata = {"items": []} jsonwrite = open("items/item_list.json", "w") json.dump(jsondata, jsonwrite, indent=4) jsonwrite.close() ...
ef62123d5a01c52b45e4ac7187e33ca69a631670
fireconey/liangshuchen
/pandas1.py
568
3.921875
4
# 行索引可以打印出来但是不能修改,为了多个 # 数据中数据对应 import numpy as np import pandas as pd data=pd.Series([1,2,4])#一维向量,是一列,左边有index data1=pd.Series([1,2,3],index=["a","b","c"]) print(data1["a"]) # 使用字典进行一维向量 data3=pd.Series({"a":2, "b":3}) print(data3.index.values[1],"****") # loc 通过索引。可以第二个参数没有 data2=pd.DataFrame({ "a":[1,2,3,4] ...
138cde568743fba2b152b3b653977df0d2a0fa6d
Leo-Liu-us/Python
/133_clone_graph/clone_graph.py
1,469
3.8125
4
# Definition for a undirected graph node #class UndirectedGraphNode(object): # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution(object): def cloneGraph(self, node): """ :type node: UndirectedGraphNode :rtype: UndirectedGraphNode """ ...
116e36d240d83bcca2a460c4c6c84e99841072b9
Jorgro/TDT4171-Methods-in-AI
/Exercise1/Exercise-1.py
13,502
3.75
4
from collections import defaultdict import numpy as np class Variable: def __init__(self, name, no_states, table, parents=[], no_parent_states=[]): """ name (string): Name of the variable no_states (int): Number of states this variable can take table (list or Array of reals): Cond...
3608552cce91138d629a3ad9cb2208b2b8f15b2f
Latoslo/day-3-3-exercise
/main.py
617
4.1875
4
# 🚨 Don't change the code below 👇 year = int(input("Which year do you want to check? ")) # 🚨 Don't change the code above 👆 # > `on every year that is evenly divisible by 4 # > **except** every year that is evenly divisible by 100 # > **unless** the year is also evenly divisible by 400` #Write your code below...
d281443f38b542469ae78363e3fc4cb8987c2f08
samarthjj/Competitive-Coding-7
/K-SmallestElementSortedMatrix.py
1,821
3.78125
4
import heapq # APPROACH 1, MIN HEAP # Time Complexity : O[(n^2)*log(n^2)], where n is the length and width of the given matrix # Space Complexity : O(n^2) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : None # Your code here along with comments explaining your approach #...
6e4713fcfa5d26984af29dd0d8002048c2ed6d82
KikoBelchi/2D_to_3D_Hausdorff
/distance_matrix_4_tensors.py
5,117
3.640625
4
import torch """ Code adapted to tensors from: https://github.com/scipy/scipy/blob/v1.2.0/scipy/spatial/kdtree.py#L936-L987 """ def minkowski_distance_p(x, y, p=2): """ Compute the p-th power of the L**p distance between two arrays. For efficiency, this function computes the L**p distance but does ...
592719c6b9845c0734e54ddc89b13fede37a296b
gobboph/trials
/portfolio_tracker.py
4,724
3.546875
4
#!/usr/bin/env python import string from prettytable import PrettyTable # !!!DEFINING RELEVANT FUNCTIONS!!! def dict_from_file(file): #This function reads from a file and writes a dictionary from it. #The file needs to have on each line the structure: title, name of the company, number of shares, purchase price, la...
8db806afe155ec75241a03b49a5b8ac55c0b21f0
shubhamkanade/all_language_programs
/decorators.py
248
3.640625
4
def sub(num1,num2): return num1-num2 def decorator(orignalfunc): def updator(a,b): if(a < b): a,b = b,a return orignalfunc(a,b) return updator result = decorator(sub) print(result(10,7)) print(result(7,10))
d7257111830a2e3e5ff7abe2c097d279943087e4
shubhamkanade/all_language_programs
/prime.py
162
4.09375
4
n = int(input("Enter a number")) for i in range(2,int((n+1)/2)): if(n % i == 0): print("not prime") break else: print("it is prime")
847d713e93f3813b840d0a5b098eb821c1bf86cd
shubhamkanade/all_language_programs
/pattern.py
141
3.921875
4
print("Enter any number") n = int(input()) for i in range(1,n+1,1): for j in range(1,(n+2)-i,1): print(j, end = " ") print()
80b2020aeabd82d5390c8ef044523e6d3fb616c4
shubhamkanade/all_language_programs
/Evenfactorial.py
363
4.28125
4
def Evenfactorial(number): fact = 1 while(number != 0): if(number % 2 == 0): fact = fact * number number -= 2 else: number = number-1 return fact number = int(input("Enter a number")) result = Evenfactorial(...
e137b863f5a780c6c0c06f74051f628dfdde44c0
shubhamkanade/all_language_programs
/operator_overloading1.py
381
3.5625
4
class vector: def __init__(self,no1,no2): self.no1 = no1 self.no2 = no2 def __str__(self): return "vector (%d %d)" % (self.no1 ,self.no2) def __add__(self,other): return vector(self.no1 + other.no1 , self.no2 + other.no2) def main(): vobj = vector(3,4) vob...
e0461c90da83c9b948352e729a91c80b24ed2817
shubhamkanade/all_language_programs
/checkpalindrome.py
460
4.21875
4
import reverse def checkpalindrome(number): result = reverse.Reverse_number(number) if(result == number): return True else: return False def main(): number = int(input("Enter a number\n")) if(checkpalindrome(number)== True): print(...
a1a1c971e1fa7008b457aa67d8d784b054f0b671
workwithfattyfingers/testPython
/first_project/exercise3.py
553
4.40625
4
# Take 2 inputs from the user # 1) user name # 2) any letter from user which we can count in SyntaxWarning # OUTPUT # 1) user's name in length # 2) count the number of character that user inputed user_name=input(print("Please enter any name")) char_count=input(print("Please enter any character which you want to coun...
50469676eb395932f957a03cfdf2abe2a3fbc809
Derioss/prog
/python/fonction/diffdate_time.py
298
3.84375
4
import datetime ##formatdate = "%m/%d/%Y" ##you can get more information on class date here : #https://docs.python.org/3/library/datetime.html def diffDate(date1,date2): firstday = datetime.date(date1) seconday = datetime.date(date2) diff = firstday - seconday diff.days return
e00abe0ba7cf332c771f59d95db4ab6ba73abf82
shashankarao/reinforcement-learning
/rl.py
4,486
3.890625
4
#!/usr/bin/env python import pylab import numpy, random import animate ''' This is the transition matrix delta. At state s and action a, trans(s,a) = s' = next state ''' trans = ( (1 , 3 , 4 , 12) , (0 , 2 , 5 , 13) , (3 , 1 , 6 , 14) , (2 , 0 , 7 , 15) , (5 , 7 , 0 , 8) , (4 , 6 , 1 , 9) , (7 , 5 , 2 , 10) , ...
64546537644e82d976613567eb3fdd621d16cc07
MarcoRamirezGT/Lab06Cifrado
/lab06P2.py
1,318
3.65625
4
import hashlib import hmac import codecs # PARTE 2 # Lee el archivo deseado original_file = open("data.txt", "r") mensaje = original_file.read() # Recibe el mensaje del txt oiriginal # Modifica el mensaje new_message = mensaje.replace("a", "d") # Guarda el mensaje en el nuevo txt copy_file = open("copy_data.txt", "w+"...
8ca6c553c9d2fcf7d142b730e5b455a781cf22da
Phone5mm/MDP-NTU
/Y2/SS/MDP/NanoCar (Final Code)/hamiltonianPath.py
2,928
4.125
4
# stores the vertices in the graph vertices = [] # stores the number of vertices in the graph vertices_no = 0 graph = [] #Calculate Distance def distance(p1, p2): return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5 #Add vertex to graph def add_vertex(v): global graph global vertices_no global vertices ...
863817a9ec431234468b53402deaccd657227c15
brianabaker/girlswhocode-SIP2018-facebookHQ
/data/tweet-visualize/data_vis_project_part4.py
2,586
4.25
4
''' In this program, we will generate a three word clouds from tweet data. One for positive tweets, one for negative, and one for neutral tweets. For students who finish this part of the program quickly, they might try it on the larger JSON file to see how much longer that takes. They might also want to try subjective...
659c1b57ad892ce6174fd7c7f951e47634151f21
brianabaker/girlswhocode-SIP2018-facebookHQ
/data/surveyproject/solution-folder/survey-project.py
836
3.75
4
import json survey = [ "What is your name?", #0 "How old are you?" #1 ] keys = ["name", "age"] dictionaries = [] done = "YES" while done == "YES": answers = {} for x in range(len(survey)): response = input(survey[x]+": ") answers[keys[x]] = response dictionaries.append(answers)...
5f72c44db92217c663f7d8a6442e6e1b347660ed
brianabaker/girlswhocode-SIP2018-facebookHQ
/python/python-solutions/AllTheFilters/part4/filters.py
4,727
3.625
4
from PIL import Image import math # Return an Image loaded from the specified file. # * filename: string, name of file to load def load_img(filename): im = Image.open(filename) return im # Display Image to the user (for debugging purposes). # * im: Image to display def show_img(im): im.show() # Save t...
f32d66dd7363abd120642d92a621be81fa53607b
sandrahelen/pythonkurs
/turtle.py
379
3.671875
4
from turtle import * #importerer turtlebiblioteket import math #importerer pylab for å bruke sqrt() shape("turtle") forward(30) #tegner en strek left(90) #snur 90 grader mot høyre forward(40) left(143.13) dist = math.sqrt(40**2 + 30**2) #pytagoras for å regne ut avstand til start forward(dist) ...
87b2528a0b01e95c3665bf4a8615d3d6ce6fdab6
sammald/Arcade-Party
/game_room.py
5,549
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sqlite3 import datetime import random import requests import json questions_db = '/var/jail/home/team67/game_files/trivia/questions.db' players_db = '/var/jail/home/team67/players.db' games_db = '/var/jail/home/team67/games.db' game_starting_html ...
94198c6efec26e4809eca316ac96135f105f89d1
Tomek-RTU/RTR-105
/Python/Python learning/Strings.py
460
4.03125
4
print('Today is good day to lear Python') print("Python is fun") print("Python's strings are easy to use") greeting = 'Hello' name = "Tomek" #name = input('Lūdzu, ievadiet savu vārdu ') print(greeting+' '+name) age = 24 print(age) print(type(greeting)) print(type(age)) age_in_words = "2 years" print(n...
52233155c8a16cf11bc54b83c1c6004b567f18f8
Tomek-RTU/RTR-105
/Python/Python learning/aa.py
365
3.90625
4
x = 23 x += 1 print(x) x -= 4 print(x) x *= 5 print(x) x //= 4 print(x) x /= 5 print(x) x **= 2 print(x) x %= 5 print(x) greeting = "Good " greeting += "morning" print(greeting) greeting *= 5 print(greeting) print() number = 5 multiplier = 8 answer = 0 for i in range(mult...
d9ea7607b09666ccf70da18063d98cd82008fb7a
Tomek-RTU/RTR-105
/Python/Python learning/writting_io.py
813
3.625
4
# cities = ["Riga", "Liepaja", "Valmiera", "Bauska", "Jurmala"] # # with open("cities.txt", 'w') as city_file: # for city in cities: # print(city, file=city_file) # cities = [] # # with open("cities.txt", 'r') as city_file: # for city in city_file: # cities.append(city.strip('\n')) #...
072979239198fafa96b147fa4e42a65a953da62b
Tomek-RTU/RTR-105
/Python/Python learning/notin.py
431
3.625
4
# activity = input("Ko tu gribētu šodien darīt? ") # # if "kino" not in activity.casefold(): #.casefold priekš upper un lowercase burtiem! # print("Bet es gribu iet uz kino!") name = input("Kā Tevi sauc? ") age = int(input("Cik Tev gadi, {0}? ".format(name))) #if age > 18 and age < 31: if 18 <= age < 31:...
aec9f612ed99128ea228bbf8931b6f84929a7b8a
wuli133144/design_pattern_python
/lib/test_list.py
1,268
4.03125
4
# -*- coding: UTF-8 -*- # def login(username="jackwu" ,passwd="123"): # if(username is "admin" and passwd is "123"): # print "success" # else: # print "login fail" def login(username="jakcwu",passwd="123"): if (username is "jackwu" and passwd is "123" ): print ...
b4c2ca7c1c6e71fd0f0e965ac95e4c78b10552be
HLUNA8/DataCademy
/Pycardio/conversor.py
691
3.640625
4
def millas_kilometros (millas): return round ((millas * 1609344),2) def kilometros_millas (kilometros): return round((kilometros/1609344),2) def run(): print("Hola!, que deseas hacer?") print ("1. millas -> kilometros") print ("2. kilometros -> millas") eleccion = int(input()) if eleccion == 1 : millas = i...
92e49524a242d298790572bba5d4bb6da3270be8
axellbrendow/python3-basic-to-advanced
/aula033-sistemas-de-pergunta-resposta/aula33.py
1,020
3.78125
4
perguntas = { 'Pergunta 1': { 'pergunta': 'Quanto é 2 + 2 ?', 'respostas': { 'a': '1', 'b': '4', 'c': '5', }, 'resposta-certa': 'b', }, 'Pergunta 2': { 'pergunta': 'Quanto é 3 * 2 ?', 'respostas': { 'a': '4', ...
7229b5d4b491d7e80492b88497c80e140eb131fb
axellbrendow/python3-basic-to-advanced
/aula076-os-arquivos-e-pastas/aula76.py
1,859
3.609375
4
import os # ../../__file__ # caminho = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # termo = 'desafio' caminho = input('Digite um caminho: ') termo = input('Digite um termo: ') contagem = 0 print() def formata_tamanho(tamanho): base = 1024 kilo = base ** 1 mega = base ** 2 giga = base...
b76bf04f4abe660f36fb8e5210905629a379b30e
axellbrendow/python3-basic-to-advanced
/aula004-tipos-primitivos/aula4.py
691
3.96875
4
""" Tipos de dados str - string - textos 'Assim' "Assim" int - inteiro - 123456 0 -10 -20 -50 -60 -15000 1500 float - real/ponto flutuante - 10.50 1.5 -10.10 -50.93 0.0 bool - booleano/lógico - True/False - 10 == 10 """ print('Luiz' , type('Luiz') ) print(10 , type(10) ...
536f88a92c2a136622f635286bc6f71d3369f9a5
axellbrendow/python3-basic-to-advanced
/aula070-metodos-magicos/aula70.py
911
3.53125
4
# https://rszalski.github.io/magicmethods/ class A: def __new__(cls, *args, **kwargs): # Padrão de projeto singleton, onde só é permitido criar uma instância da classe if not hasattr(cls, '_jaexiste'): cls._jaexiste = object.__new__(cls) return cls._jaexiste def __init__...
759023e85d1eb810d44ddcc35083813ded05de3a
axellbrendow/python3-basic-to-advanced
/aula035-list-comprehension/aula35.py
714
4
4
""" List Comprehension [expression for variable in list] <expression> pode ou não usar <variable> dentro dela. <expression> """ # l -> lista, ex -> exemplo l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] ex1 = [v for v in l1] # Copia todos os elementos de l1 para ex1 ex2 = [v * 2 for v in l1] # Copia os elementos multiplicando-o...
52f64667aa49e6f89be4db5aca8c485b0eba2fd1
axellbrendow/python3-basic-to-advanced
/aula069-sobrecarga-de-operadores/aula69.py
790
3.84375
4
class Retangulo: def __init__(self, x, y): self.x = x self.y = y def area(self): return self.x * self.y def __repr__(self): return f"<class 'Retangulo({self.x}, {self.y})'>" def __add__(self, other): novo_x = self.x + other.x novo_y = self.y + other.y ...
c74849204786d127be5283adfc6996494911277a
axellbrendow/python3-basic-to-advanced
/aula007-formatar-strings/aula7.py
389
3.8125
4
""" Breve introdução à formatação de strings """ nome = 'Luiz' idade = 32 altura = 1.80 maior_de_idade = idade > 18 peso = 80 imc = peso / (altura ** 2) print(f'{nome} tem {idade} anos de idade e seu imc é: {imc:.2f}') print('{2} {0} {0} tem {1} anos e seu imc é: {2:.2f}'.format(nome, idade, imc)) print('{n} tem {i} ...
e204319d3fe2d8d7dec0736659e3f076a14cb45c
axellbrendow/python3-basic-to-advanced
/desafios-ate-a-aula073/banco/Conta.py
1,742
3.875
4
# abc = Abstract Base Class from abc import ABC, abstractmethod from banco.Agencia import Agencia from banco.Cliente import Cliente class Conta(ABC): def __init__(self, agencia: Agencia, conta: int, cliente: Cliente, saldo: float): self._agencia = agencia self._conta = conta self._saldo = ...
fafba52c190eb20239fd2eee2b428bcf0789a867
axellbrendow/python3-basic-to-advanced
/aula013-indices-e-fatiamento-de-strings/aula13.py
638
3.96875
4
""" Manipulando strings * String índices * Fatiamento de strings [início:fim:passo] * Funções built-in len, abs, type, print, etc... Essas funções podem ser usadas diretamente em cada tipo. """ # positivos [012345678] texto = 'Python s2' # positivos -[987654321] print(texto[2:6]) print(texto[:6]) # Eq...
cfa6610b49428b6f4131d929c0b98761d9c976dd
cortesi/scurve
/scurve/natural.py
1,475
3.875
4
import math class Natural: """ A natural order traversal of the points in a cube. Each point is simply considered a digit in a number. """ def __init__(self, dimension, size): """ dimension: Number of dimensions size: The size in each dimension """ ...
e4861d1525427bf80a5fbbe5005860a31583e79e
ViniciusBrag/Exercicios-POO
/oo/conta.py
2,204
3.609375
4
from oo import teste_conta from datetime import datetime class Conta: def __init__(self, numero, titular, saldo, limite= 2000): self.limite = limite self.saldo = saldo self.titular = titular self.numero = numero self.historico = Historico() def deposita(self, valor): ...
96d92451d0fd53dd98dff62e651877de55efddce
jacobkreider/msds458
/Follet Chapter Notes and Code/Python for Deep Learning Chapter 6 Notes and Code.py
24,685
4.1875
4
# coding: utf-8 # #### *Deep Learning with Python* Chapter 6: Deep Learning for Texts and Sequences # ##### *Notebook by Jacob Kreider* # # *The below code is pulled directly from Deep Learning with Python by Francois Chollet (Manning Publications, 2018). Code comments, notes, and commentary are a mix of mine and th...
a7b73913e743bab492b9fc61bce1afce0070feee
kuztar97p/pythonDZ
/dz7.py
2,628
3.671875
4
import random as rnd my_list = [rnd.randint(1, 100) for value in range(20)] print(my_list) ########################################################### my_key = ["A", "B", "C"] my_list = [rnd.randint(-10, 10) for value in range(2)] triangel = {key: tuple(my_list) for key in my_key} print(triangel) #################...
47e4a3105a316edba229a87d3994764ff73037fa
cedolic/C-python
/exerc 013.py
185
3.71875
4
salário = float(input('Digite o salário: R$')) aumento = salário + (salário*15/100) print('O salário de R${:.2f} com acréscimo de 15% vai para R${:.2f}'.format(salário, aumento))
0b011cf170dbfa1f8e3316f21536d7aff4b1fceb
mohammadneisi/-random-password-geneartor-
/random password geneartor.py
4,060
3.5625
4
# mohammad neisi # email : muhammadneisi20@gmail.com import random import string import os settings = { 'lower': True , 'upper': True , 'symbol': True , 'number': True , 'space' : False , 'length': 8 } PASSWORD_MAX_LEN = 10 PASSWORD_MIN_LEN = 4 def clear_screen (): os.system('cls') d...
d0db0a41e2b6e806980a96d7cb809faf2521941b
catestettler/finalproject-stettlerCatherine
/introduction.py
1,156
3.828125
4
from player_characteristics import Player from witch_characteristics import Witch class Introduction(object): def __init__(self): pass @staticmethod def player_details(player: Player, witch: Witch): player_name = input("Please enter your name:") player.set_name(player_name) ...
622ffddee02073c8af92d2fd490d4ab943ef4388
catestettler/finalproject-stettlerCatherine
/player_unittest.py
440
3.5
4
import unittest from player_characteristics import Player class PlayerTest(unittest.TestCase): def test_name(self): player = Player() player.set_name("Bob") self.assertEqual(player.get_name(), "Bob") def test_reason(self): player = Player() player.set_reason("berry pi...
43daea1fecde59fac91266032e3c9689d3642808
canstri/enigmath
/Enigmath/lemmas/isequal.py
883
3.546875
4
from sympy import * from mpmath import * def isequal(input_exp): status = False RHS = "" LHS = "" znak1 = "" znak2 = "" bool1 = False dannoe = input_exp if dannoe == '': return ('') for i in range(0, len(dannoe)): if (dannoe[i] == ">" and dannoe[i+1] == "=") or (...
7c2f3eba77f5546e144be7372f25d25ba6ffa1f6
bowling8/projects
/hackerrank/alphabet_rangoli.py
486
3.765625
4
#!/usr/bin/env python3 import string def rangoli_line(alphabet): returns = alphabet[0] if len(alphabet) == 1: return returns print(alphabet.reverse()) returns = "{}{}".format("-".join(alphabet[1:].reverse()), returns) return returns def print_rangoli(size): alphabet = list(s...
4442c21ed6b77b983435dcaaf66e969b2701ee4d
bowling8/projects
/practice/crackingCodingInterview/1_1.py
372
3.578125
4
#!/usr/bin/env python3 test = "Th is a e" letters = [] for i in range(0,26): letters.append(0) #for i in range(0, len(test.lower().replace(' ', ''))): for i in test.replace(' ', '').lower(): test[0] = 'r' index = ord(i) - ord('a') if letters[index] == 0: letters[index] = 1 else: ...
89deae7a350f263d7cb1f7ad1385dbbbc3d54ae9
bowling8/projects
/hackerrank/string_formatting.py
307
4.0625
4
#!/usr/bin/env python3 def print_formatted(number): space = number.bit_length() for num in range (1,number+1): print("{0:>{align}} {1:>{align}} {2:>{align}} {3:>{align}}".format(str(num), str(oct(num))[2:], str(hex(num)).upper()[2:], str(bin(num))[2:], align = space)) print_formatted(99)
0df4477307f7f878ee59965a6870dd19a351a897
akalenuk/html_bitmap
/use_case_1.py
2,538
3.9375
4
#!/usr/bin/python """ This code is a demonstration of maping technique for non-linear programming with constrains forming an edged manifolds inner space. The idea is to map n-manifold inner space on R^n, solve an optimization task there, where it would be unconstrained, then map the results back on the manifold spac...
7a6a5546361d63b62d95c557e62ce37980d76fe3
KateLiliy/python
/football.py
2,771
3.765625
4
import math import random class Playoff(object): def __init__(self, teams): self.teams = teams[:] self.MIN = 0 self.MAX = 31 self.tours = round(math.log(len(teams), 2)) self.history = {tour: [] for tour in range(self.tours)} def _group(self, teams, by): """С...
c147ee2f082b70b7decbee4c396035241031e5f2
KishinTwitch/Chess
/Square.py
718
3.546875
4
import pygame BLACK = (209, 139, 71) WHITE = (255, 206, 158) RED = (255, 0, 0) class Square(pygame.Rect): def __init__(self, x, y, w, h, color): super().__init__(50 + 60*x, 50 + y*60, w, h) self.index_x = x self.index_y = y self.piece = None self.color = col...
214265fae08a785f0ddea21140b8f39c633becb3
codeburr/pyraffle
/raffle.py
1,726
3.5
4
from sys import exit import os import random def clear(): os.system("cls" if os.name=="nt" else "clear") return def raffle(wins,shuffles=3): names=[] winners=[] with open("./names.txt","r") as f: lines=f.readlines() if wins<0: wins=abs(wins) if wins>len(lines): wins=len(line...
f0e1863b39362db65c98698eff2b6c7150984475
G-Radhika/PythonInterviewCodingQuiestions
/q5.py
1,469
4.21875
4
""" Find the element in a singly linked list that's m elements from the end. For example, if a linked list has 5 elements, the 3rd element from the end is the 3rd element. The function definition should look like question5(ll, m), where ll is the first node of a linked list and m is the "mth number from the end". You s...
04af683cc328b43112314b3d52e7ac24935a6954
TheAwiteb/Challenges
/password_generator.py
10,365
3.578125
4
import string from random import choice import curses from curses import textpad from time import sleep import os password_menu = ['UpperCase','LowerCase','Numbers','Symbolic','Save file','Next'] password_values = {'UpperCase':True, 'LowerCase':True,'Numbers': True, 'Symbolic':True, 'Save file':Fal...
449cccca9c8eb50c14c1bb65b946546fa964fb10
TheAwiteb/Challenges
/Challenges19.py
2,266
4.09375
4
#The Primiera #Primiera (from the french word prime, "prize") is a combination of cards of Scopa, a popular Italian card game. #For establishing the value of the Primiera, a separate point scale is used for selecting the best cards in the player's deck, in each of the four suits and totaling those four cards point va...
fe5a16cc871589a167deb2ab6819112da1e19c2d
TheAwiteb/Challenges
/Challenges03.py
1,273
3.859375
4
#Create a function that takes a string (IPv4 address in standard dot-decimal format) and returns True if the IP is valid or False #if it's not. For information on IPv4 formatting, please refer to the resources in the Resources tab. #Examples '''is_valid("1.2.3.4") ➞ True is_valid("1.2.3") ➞ False is_valid("1.2.3.4.5...
2804f3b1b144033f2223577760d22565944ee3b6
taozhanggit/stanfordML
/ex1_linear_regression/linear_regression.py
3,334
3.859375
4
import numpy as np import matplotlib.pyplot as plt def compute_cost(X, y, theta): ''' J = sum((X * theta - y).^2) / (2*m); :param X: 数据 :param y: 结果 :param theta: 梯度向量 :return: cost value ''' inner = np.power(np.dot(X, theta.T) - y, 2) # print(np.sum(inner) / (2 * len(X))) retu...
b6a69cda8b3d19a3c7916d921d23d463b7788d64
Tanavya/ProjectEuler
/#2.py
689
4.03125
4
""" 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 sum of the even-valued terms. """...
f3d84980653b47d9e11f0a9028902d66658d7dd8
Tanavya/ProjectEuler
/EulerP37.py
660
3.90625
4
def isPrime(n): if n == 2: return True if n > 1 and n % 2 != 0: for curr in range(3, int(n**0.5) + 1, 2): if n % curr == 0: return False return True return False def isTruncatablePrime(n): n = str(n) n_copy = n while n: if not i...
dde22b8cb1d2779c18f3636032edfbfdb10d73a2
Tanavya/ProjectEuler
/EulerP33.py
1,115
3.53125
4
product = 1 for denum in range(10,100): for num in range(10, denum): d = "" n = "" str_denum = str(denum) str_num = str(num) for digit in str_denum: if digit not in str_num and "0" not in str_num and "0" not in str_denum: d += digit fo...
f6c22e09b8bd4b7830d510ef72b92de143a7f5a8
Tanavya/ProjectEuler
/EulerP15Attempt2.py
1,786
3.59375
4
import time gridSize = [20,20] def find_paths(gridSize): #bad rec method lool n = 0 if gridSize[0,0]: #print "found" return 1 #if gridSize[0] >= 1: #print "Right", [gridSize[0]-1, gridSize[1]] n += find_paths([gridSize[0]-1, gridSize[1]]) #if gridSize[1] >= 1: ...
998bf8f4e52c37d6c22bbddc4bfff3a80acc6a4e
Tanavya/ProjectEuler
/EulerP27.py
1,222
3.78125
4
#CANT BELIEVE I WROTE THIS ONE, IT LOOKS SO NEAT! <3 import math def isPrime(n): if n < 2: return False if n < 4: return True if n % 2 == 0: return False if n < 9: return True if n % 3 == 0: return False for current in range(3, int(math.sqrt(n)) + 1, 2): if n % current == 0: ...
fc20302463c15655db85cfb5be3da1c3b02885ac
TeamCohen/ProPPR
/src/scripts/symtab.py
1,051
3.640625
4
import logging #symbol table - map strings to/from the range 1..N inclusive. class SymbolTable(object): """A symbol table mapping strings to/from integers in the range 1..N inclusive.""" def __init__(self,initSymbols=[]): self._symbolList = [None] self._nextId = 0 self._idDict = {}...
256df2c76bc6c7546eb2cb4e73e31462c0ebac95
codinglikeagirl42/arcade_book
/source/chapters/07_drawing_with_functions/drawing_with_functions_3.py
1,607
3.953125
4
""" This is a sample program to show how to draw using functions """ import arcade def draw_grass(): """ This function draws the grass. """ arcade.draw_lrtb_rectangle_filled(0, 800, 200, 0, arcade.color.BITTER_LIME) def draw_pine_tree(position_x, position_y): """ This function draws a pine ...
2937aa86a3100e65d6bb5aaa1351fbd970d6cab7
MichaelAuditore/holbertonschool-higher_level_programming
/0x0B-python-input_output/12-student.py
565
3.921875
4
#!/usr/bin/python3 class Student: """ Class to define a student """ def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): d = {} if type(attrs) is not list: ...
e34e189c2cad4576c13d2f740f8715304845cca9
MichaelAuditore/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/tests/6-max_integer_test.py
1,592
3.734375
4
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): def test_positive(self): self.assertEqual(max_integer([1, 3, 5, 7]), 7) def test_negatives(self): self.assertEqual(max_integ...
c260b20f0750cebda13e93067e88b23d156772e1
MichaelAuditore/holbertonschool-higher_level_programming
/0x0A-python-inheritance/101-add_attribute.py
264
3.90625
4
#!/usr/bin/python3 def add_attribute(obj, attr, value): """ This function adds a new attribute to an object if it’s possible """ if (not hasattr(obj, "__dict__")): raise TypeError('can\'t add new attribute') setattr(obj, attr, value)
305683a278a6787fee79820635ba4993f3f6fb7f
MichaelAuditore/holbertonschool-higher_level_programming
/0x11-python-network_1/100-github_commits.py
640
3.5625
4
#!/usr/bin/python3 """Script to do a POST request to github api to get an specific info about a repo in this case print the latest 10 commits """ if __name__ == "__main__": import sys import requests repo = sys.argv[1] user = sys.argv[2] url = "https://api.github.com/repos/{}/{}/commits".format(use...
7aac82a4ee186b9ce025a48c874673bac5f13af4
MichaelAuditore/holbertonschool-higher_level_programming
/0x0F-python-object_relational_mapping/4-cities_by_state.py
580
3.515625
4
#!/usr/bin/python3 """ Script to list all cities by state from hbtn_0e_0_usa """ if __name__ == "__main__": import MySQLdb as sql import sys db = sql.connect(host="localhost", port=3306, user=sys.argv[1], passwd=sys.argv[2], ...
977d238dbe6b74090d35b8966980275114ecefd2
MichaelAuditore/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
738
4.09375
4
#!/usr/bin/python3 """ find the peak """ def rec_peak(lbegin, last, l): """ search peak into list of integers """ mid = (lbegin + last) if (mid % 2 == 0): m = int(mid / 2) else: m = int((mid - 1) / 2) if (m == 0 or l[m] >= l[m - 1]) and (m == last - 1 or l[m] >= l[m + 1]): ...
6ed2cd27f06b2bb4f00f0b14afd94e42e7173164
MichaelAuditore/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
706
4.40625
4
#!/usr/bin/python3 def add_integer(a, b=98): """ Add_integer functions return the sum of two numbers Parameters: a: first argument can be integer or float b: Second argument initialized with value 98, can be integer or float Raises: TypeError: a must be an integer or float ...
51e305ae2cf632e91cbe31fbea925f40860d91e5
AntonioReyesE/ProyectoMetodosFinal
/Termino.py
620
3.5625
4
# -*- decoding: utf-8 -*- class Termino(object): """docstring for Termino""" def __init__(self, grado, constante, variable, numero): super(Termino, self).__init__() self.grado = grado self.constante = constante self.variable = variable self.total = self.constante * (pow(self.variable, self.grado)) self.n...
d914780cd27f3ed97c8c498830d7904651c876bc
emapco/Python-Code-Challenges
/test_find_prime_factors.py
563
3.59375
4
from unittest import TestCase def get_product(factors): product = 1 for factor in factors: product *= factor return product # Test will pass if the product of the factors returned # is equal to the number that was factorized class Test(TestCase): def test_prime_factorize(self): from ...
3e00f6a812c84858d600e33b8211f08320774521
msoares-prog/42AI-BootcampPython
/day00/ex02/whois.py
418
3.578125
4
import sys argc = len(sys.argv) if argc > 2: print("Error") else: try: nbr = sys.argv[1] nbr = int(nbr) if nbr == 0: print("I'm a zero") else: result = nbr % 2 if result: print("I'm odd") else: print...
88487849aef25a6d84cedac5e4da696807e8c447
bebetaro/studyPython
/taityo/sample.py
141
3.5
4
c = [] for i in range(5): if i%2 == 0: c.append(i) print(c) for j in range(5): chinko=input() c.append(chinko) print(c)
d7bbffb47cc293d33cd2d430436949b18d6f2317
bebetaro/studyPython
/taityo/test.py
402
3.734375
4
chinko='chinko' manko=[] for i in reversed(chinko): manko.append(i) print(''.join(manko)) put_line = input() print(input_line.replace('1','January').replace('2','Feburary').replace('3','March').replace('4','April').replace('5','May').replace('6','June').replace('7','July').replace('8','August').replace('9','Septem...
53d59c2b23f7fed52ac36867a4adb6dd4e177187
EMinsight/phylanx
/python/Phylanx.py
2,203
4.03125
4
# A simple way to turn a python3 expression into a data structure (AST) # First overload some basic operators. # All the other classes will inherit from this. class Ops: def __add__(self,a): return Plus(self,a) def __mul__(self,a): return Mul(self,a) def __sub__(self,a): return Sub(...
f923533c900effe650ccfd265aa87f274c6fa878
JMine97/Algorithm
/BFS.py
914
3.65625
4
from collections import deque #양방향 데이터 처리 가능 자료구조 def bfs(graph, start, visited): # 시작 값으로 큐 초기화 queue = deque([start]) # 시작 노드 방문 처리 visited[start] = True # 큐가 빌 때까지 반복 while queue: # 큐에서 하나의 원소를 뽑아 출력 v = queue.popleft() print(v, end=' ') # 방문하지 ...
f55fe0a80a40e01df67e5ce9c8462b2ac4c341ff
Vengalrao-eppa/shopping_basket
/cart.py
3,316
4.1875
4
class Cart(object): """ Shopping Cart Class to handle the products Returns the total amount based on offers ... Methods ------- __init__(store=None) Initialises the object for Cart Class store - an instance of the ProductStore Class get_total(offers=None) Ret...
325fdb3345381669b668b11e89e250dfce794302
david3de/CruzHacks-x-SWE-Pre-Hackathon-Python-Workshop
/set.py
99
4.03125
4
# Basic Python set example myset = set() myset.add('foo') if 'foo' in myset: print('foo in set')
51cd753d54fb8a0e5cb9dfb03e503730f86c1dda
tentone/max-clique
/graph.py
2,774
3.5
4
import json import uuid # Stores a vertex in a position of the graph. # # Vertices have (x, y) integer position associated. class Vertex: def __init__(self, x, y): # UUID of the vertex, used for serialization. self.id = uuid.uuid4() self.x = x self.y = y # Stores an edge that connects two vertices togheter ...
007c745dd9f2ef0be9e3d38971d1e3ec8fd83b10
popyue/Codility
/Rectengle/Rectengle_Function.py
2,577
3.5625
4
# -*- coding: utf-8 -*- # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") #First Rectengle length, width def RectAinfo(K,L,M,N): infoA=[] lengthA=abs(K-M) infoA.append(lengthA) widthA=abs(L-N) infoA.append(widthA) return infoA #Second Rectengle length, wi...
976ace4df65a36bd1f8f717024dce2e932824211
macchid/euler-python
/p01_sum_of_prime_numbers.py
652
3.65625
4
#!/bin/python3 import math import itertools def sumMultiplesOf(numbers, n): sum = 0 for r in range(1, len(numbers) + 1): for g in itertools.combinations(numbers, r): m = math.prod(g) limit = (n-1) // m sign = int(math.pow(-1, len(g)-1)) #print(f"{sign}*...
f3053c703bf285fc0a760777ef5ec27a9dbd5b37
till-h/ICAHHorizons_Y2PhysComp
/session 2/extra_material/icrs_motor_test.py
936
3.75
4
from gpiozero import Robot, DistanceSensor, LED from time import sleep #Import the library with all the functions needed led = LED(pin=18) #Use the LED object, calling it 'led' led.blink(0.5, 0.5, None, True) #on for 0.5 seconds, off for 0.5 seconds, run continuously, run in the background leftPins = (12, 16) rightPi...
012b105ba3aba800d07a01cbfc1eb6797005cf6e
Gitrocha/BR-MarineTraffic
/Main/log.py
977
3.59375
4
import logging import os def start(file_name=None): """ Starts the logging process If file_name is not provided, the name will be the current date Error messages will be automatically logged """ # Sets format as: [12-12-2017 12:43:25,123] - Message message_format = '[%(asctime)-15s] - %(m...
842996c567a336466839c5c3bc7ee41659d1b64e
Zippycz3ch/Python
/rpsAI.py
1,132
4.03125
4
import random games = int(input("Set number of wins: ")) games_won_player = 0 games_won_pc = 0 while games_won_pc < games and games_won_player < games: print(f"PC:{games_won_pc}\nPlayer:{games_won_player}") player_1 = input("Rock, Paper or Scissors?: ") player_2 = random.randint(1,3) if player_2 == 1: ...