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
377103a2ecb05c04b129d7fee3702e294101048b
juanjosua/codewars
/string_repeat.py
364
3.625
4
""" Instructions: Write a function called repeat_str which repeats the given string src exactly count times. Example: repeatStr(6, "I") // "IIIIII" repeatStr(5, "Hello") // "HelloHelloHelloHelloHello" Link: https://www.codewars.com/kata/57a0e5c372292dd76d000d7e/train/python """ def repeat_str(repeat, string): ...
9b13b81591ac46bd67f1f646ccd9c707534766c5
juanjosua/codewars
/duplicate_encoder.py
1,332
4.09375
4
""" Instructions : The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is...
24ac308b1f86080be86ad0f125da974a0b9a0ecb
juanjosua/codewars
/test_autocomplete.py
696
3.9375
4
""" This file is to learn how to use pytest. """ # https://www.codewars.com/kata/5389864ec72ce03383000484/train/python import pytest import os def autocomplete(input_, dictionary): #your code here result = [] for d in dictionary: if d.find(input_) == 0: result.append(d) ...
baf421c8b8c4cf0b61ee33128be04746a73ed06d
gerbriel/backend-dev
/day2.py
1,091
4.09375
4
def first_vowel(x): for index, char in enumerate(x): if char in 'aeiou': return index def convert(x): index=first_vowel(x) return x[index:]+x[:index]+'ay' print(convert('dog')) # englishWords = ['dog','zebra','tiger'] # vowels = 'aeiou' # wordAmount = 3 # bitwiseClasses = [...
de8a2a7262a1e0ede3cc86aa6fd82a0caeb8dff7
idanjos/University_classes
/AA/fibo.py
263
3.671875
4
add = 0 def fibo(n): global add if n<2: return n add+=1 return fibo(n-1) + fibo(n-2) def fiboL(n): global add if n<2: return n add+=1 return fibo(n-1) + fibo(n-2) for i in range(1,11): print(str(i)+"-"+str(fibo(i))+"-"+str(add))
b694ae4d15c7480aa440207d9b008b43bd5050fe
idanjos/University_classes
/AA/f1.py
342
3.71875
4
counter = 0 adds_counter = 0 def f1(n): global counter r = 0 for i in range (1,n+1): r+=i counter +=1 return r def r1(n): assert(type(n)==int) and (n>=0), "Wrong arg" global adds_counter if n == 0: return 0 adds_counter +=1 return 1+ r1(n-1) print(f1(...
cf4c17b1917124cb4f63ccf478d798fc92470ff7
rahulvenugopal/ePRIME_txt_csv_batch
/example/eprime_txt_csv.py
755
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 5 23:18:10 2021 @author: Rahul Venugopal Just a wrapper to automate bulk converting .txt files to .csv files """ # Loading library from convert_eprime.convert import text_to_csv from tkinter.filedialog import askopenfilenames from tkinter import Tk ...
9555bd3ece66087b254256195488cdb03fe87f8d
kyletgithub/notes-or-something
/twod_lists.py
701
4.15625
4
a = [[1,2,3], [4,5,6]] ## one way to traverse a 2d list #for i in range(len(a)): # for j in range(len(a[i])): # print(a[i][j],end=' ') # print() ##another way #def print_2dlist(lst): #for row in a: # for element in lst: # print(element,end=' ') # print() #add all elements #sum = 0 #for ...
6115fe58abcf4cedf25d90d87613590919ec494a
lisamryl/oo-melons
/melons.py
2,057
4.15625
4
"""Classes for melon orders.""" import random import datetime class AbstractMelonOrder(object): """Abstract for both domestic and international melon orders.""" def __init__(self, species, qty): """Initialize melon order attributes.""" self.species = species self.qty = qty se...
52ebc75576602d16893646ac5085cb69717f225b
DanielHadley/dailyprogrammer
/DrSuess.py
4,664
3.796875
4
# # http://www.reddit.com/r/dailyprogrammer/comments/25clki/5122014_challenge_162_easy_novel_compression_pt_1/ # Welcome to this week's Theme Week. We're going to be creating our very own basic compression format for short novels or writing. This format will probably not be practical for actual use, but may serve as a...
96a58d71f67b01d07897d83fca08c3beb5c718cd
loudsoda/CalebDemos
/Multiples_3_5/Multiples_3_5.py
1,228
4.125
4
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Note: If the number is a multiple of both 3 and 5, only count it once. Courte...
8d64526c36feb282be5b48be89e8d832e998fe60
cshweeti77/Backup
/hangman.py
778
3.9375
4
from random import * from collections import Counter list = ['mango', 'orange', 'apple', 'pear', 'papaya', 'banana'] word = random.choice(list) letterguessed = '' print("HANGMAN") print("HINT::THIS IS THE NAME OF FRUIT") for i in range(len(word)): print('-', end='') print() count = len(word) + 2 if __name__ ==...
f1b6723564181b6d1cadde4314e8d6a6048759b0
VasiliyTrutnev/Homework-01
/hw04_easy.py
3,019
4.15625
4
# Задание-1: # Напишите функцию, переводящую км в мили и выводящую информацию на консоль # т.е функция ничего не возвращает, а выводит на консоль ответ самостоятельно # Предполагается, что 1км = 1,609 мили def convert(km): miles = km * 1.609 print(miles) # Задание-2: # Напишите функцию, округляющую полученное ...
3aa43958f2887660ca5c73d850b370e996961d00
VasiliyTrutnev/Homework-01
/hw10.py
3,266
3.828125
4
"""Предметная область - предприятие. Разработать класс Enterprise, описывающий работу с предприятием. Разработать класс People, описывающий человека, человек характеризуется параметрами: фамилия, имя, отчество, дата рождения, телефон. Разработать класс Employees на базе класса People, сотрудник характеризуется следу...
0c9c4ef95cd77be56ae0d19f1cd54028401cd3fd
5l1v3r1/Accident-Risk-Prediction-Travelify-
/app.py
3,879
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 20 20:27:40 2020 @author: Rahul """ # xnn import numpy as np import pickle import pandas as pd import streamlit as st from PIL import Image pickle_in = open("accident.pkl","rb") classifier=pickle.load(pickle_in) def welcome(): return "Welc...
75f94c5be6a41b96a33d4595bf0d6eb2839cd351
domoramas/code_guild_projects
/python labs/lab25_v3.py
2,193
4.09375
4
#ATM class ATM: def __init__(self, balance = 0, int_rate = .01, trans = []): #initializer with balance and interest rate defaults self.balance = balance self.int_rate = int_rate self.trans = [] def check_balance(self): return f'{self.balance}' def deposit(self,amount...
8b1158eeaecd935bfecfd8c2512b004faa3c11fa
domoramas/code_guild_projects
/python labs/lab02.py
800
3.765625
4
#Madlib print ("Welcome to Madlibs") adj1 = input("Give me an adjective: ") adj2 = input('Give me another adjective: ') adj3 = input('Give me one last adjective: ') noun1 = input('How about a noun: ') noun2 = input('Lets get another noun: ') noun3 = input('Lets get one more noun: ') noun4 = input('Last noun, I promise:...
7b22293bb6218ea013111594f809a22260b0e320
domoramas/code_guild_projects
/python labs/lab24_v2.py
2,086
3.65625
4
#rain data # need to load the file import datetime def load_text(path): with open(path) as text_file: data_table = text_file.read().strip('\n') return data_table data_table = load_text("skyline_school.rain.txt") data_lines = data_table.split("\n") data_lines = list(data_lines) date_rain = [] for i in...
d3321a42c854ebfbf08f41ca68abcff04b684653
taandreo/python
/livro/lista.py
381
3.734375
4
l = [0,0,0,0,0] x = 0 soma = 0 while x < 5: nota = float(input('Digite a nota %d: ' %(x +1))) l[x] = nota x += 1 print('0 para sair do programa') while True: e = int(input('Escolha um número para mostrar: ')) if e == 0: break elif e > 5 or e < 0: print('Opção inválida') ...
c04a4abd0e91be56a4ced982a2b75cef7d90706a
petepall/Treehouse_Course_files
/tuples/tuples.py
538
3.6875
4
# def multiply(*args): # product = 0 # for nums in args: # if product == 0: # product = nums # else: # product *= nums # return product # print(multiply(5, 4, 3)) # def stringcases(data): # return (data.upper(), data.lower(), data.title(), data[::-1]) # pri...
aa8c88c89885946f9641d5177997a4514f481c4b
petepall/Treehouse_Course_files
/classes/book.py
565
3.71875
4
class Book: def __init__(self, title, author): self.title = title self.author = author def __str__(self): return f"{self.title} by {self.author}" class Bookcase: def __init__(self, books=None): self.books = books @classmethod def crete_bookcase(cls, book_list): ...
ee7195c77b6de0b24df33b938058b4a2f45ec48e
sunnysunita/BinaryTree
/take_levelwise_input.py
1,353
4.25
4
from queue import Queue class BinaryTree: def __init__(self, data): self.data = data self.left = None self.right = None def print_binary_tree(root): if root is None: return else: print(root.data, end=":") if root.left != None: print("L", root.lef...
26b1e46a4279147c4489c437903bc49e469a2ae0
Aluriak/readings
/readings/database.py
1,679
3.609375
4
"""Implementation of a database. """ import json from readings import Story, logger DEFAULT_DB_FILE = 'data/database' class Database: """Remember seen stories. Expose mark_as_read, already_read and commit methods, that allow client or readings to manipulate data. """ def __init__(self, dbf...
9751551b763a74c5cad40fcddd00a13c99b3a842
nofuture-git/31g
/trunk/Code/NoFuture/Util/Core/Math/Matrix/matrixEtc.py
5,210
3.5625
4
import random import numpy as np import numpy.linalg import math def convFromNumpyArray(numpyNdArray): """Converts a, typically a numpy array, into a simple python list""" if numpyNdArray is None: return [[]] isvector = False if type(numpyNdArray) is np.ndarray: if len(numpyNdArray.shap...
e32fa617568c69e52b69c961afd676fa94b2e586
benreynwar/plogram
/tutorial.py
4,036
3.6875
4
''' A tutorial to teach the system. ''' import random import os import json # Test 1) Test of the basic ?? letters on left. # Test 2) Test of the basic ?? letters followed by enter/space/underscore # Test 3) Test vowels # Test 4) Test letters on right. # Test 5) Test of common words that just use those basic letters....
ed9b730715aceab3e60c3550529a713489b19c03
weinbrek8115/CTI110
/P2HW1_DistanceTraveled_WeinbrennerKarla.py
377
4.03125
4
# CTI-110 # P2HW1 Distance Traveled # Karla Weinbrenner # 15 Feb 18 speed = 70 time=6 distance = speed * time print ("Distance after",time,"hours is", distance, "miles") time=10 distance = speed * time print ("Distance after",time,"hours is", distance, "miles") time=15 distance = speed * t...
c368badfeda0bd1f7079c807eb072dbbb6938641
weinbrek8115/CTI110
/P4HW2_RunningTotal_WeinbrennerKarla.py
628
4.15625
4
#CTI-110 #P4HW2 #Karla Weinbrenner #22 March 2018 #Write a program that asks the user to enter a series of numbers #It should loop, adding these numbers to a running total #Until a negative number is entered, the program should exit the loop #Print the total before exiting #accumulator variable runningTota...
64e6dcc3759a7a16042377dc6ca856bbfd9ebdac
M-de-Mateus/Python
/ex044 - condições pagamento.py
1,607
3.703125
4
c = -1 while c < 10.000: print(f'{" Pagamento e condições ":=^40}') preco = float(input('Digite o preço do produto: ')) condicao = int(input('Escolha a condição de pagamento: \n' '1 - À vista dinheiro ou cheque (10% de desconto) \n' '2 - À vista no car...
492e6be59e3283bfb1b411cf972b2806105a30a0
M-de-Mateus/Python
/ex081 - Extraindo dados de uma lista.py
450
3.953125
4
lista = [] while True: valores = int(input('Digite um valor: ')) lista.append(valores) continuar = str(input('Deseja continuar? [S/N] ')).upper().strip()[0] if continuar in 'N': break print(f'Foram digitados {len(lista)} números!') print(f'Lista ordenada de forma decrescente: {sorted(l...
1682599cccdf436eb7778af462162ebe81468e7f
M-de-Mateus/Python
/ex085 - Lista de pares e impares.py
696
3.65625
4
''' pares = [] impares = [] principal = [] for c in range(0, 7): valor = int(input('Digite um valor: ')) if valor % 2 == 0: pares.append(valor) else: impares.append(valor) principal.append(sorted(pares[:])) principal.append(sorted(impares[:])) pares.clear() impares.clear() pr...
65d3d7cca641f40bea611ac31c2c65cced5f8734
M-de-Mateus/Python
/ex031 - calculos de passagem.py
287
3.84375
4
distancia = int(input('Digite a distancia da viagem em km: ')) if distancia <= 200: valor = float(distancia * 0.50) print('Sua viagem custará R$ {:.2f}.'.format(valor)) else: valor = float(distancia * 0.45) print('Sua viagem custará R$ {:.2f}.'.format(valor))
e7ab46cf3f59673b3137bd8da17c5fd05ab41ce0
M-de-Mateus/Python
/ex061 - Progressão aritimetica v2.0.py
213
3.859375
4
primeiro = int(input('Digite o primeiro termo: ')) razao = int(input('Razão da PA: ')) termo = primeiro c = 1 while c <= 10: print(f'{termo} - ', end='') termo += razao c += 1 print('Fim')
b9369d89e11e99fd7b14cd4a283676189e6e77ba
M-de-Mateus/Python
/ex067 - Tabuadas.py
279
3.875
4
n = c = 0 while True: n = int(input('Digite o número do qual deseja ver a tabuada: ')) if n < 0: print('O programa foi encerrado!') break else: while c < 11: print(f'{n} x {c:2} = {n * c}') c += 1 c = 0
9015300f9d5fb18a251e9979260105fc09b28b23
M-de-Mateus/Python
/ex010.py
158
3.765625
4
num = float(input('Digite quanto você tem na carteira: R$ ')) dol = num/3.27 print('Você consegue comprar US${:.2f} com R${:.2f}!'.format(dol, num))
ff7db0296430316145a59a1d8c9581b6f2152566
kongp3/sorter_demo
/bubble_sort.py
801
3.96875
4
# -*- coding: utf-8 -*- def bubble_sort(array): for i in range(1, len(array)): for j in range(0, len(array)-i): if array[j] > array[j+1]: temp = array[j+1] array[j+1] = array[j] array[j] = temp return array def bb2(array): for i in range(...
f34ace8f794dba90324f2f96cd5673e347608e8a
Pandinosaurus/Deep-Reinforcement-Learning-Algorithms-with-PyTorch
/environments/Ant_Navigation_Environments.py
2,608
3.53125
4
from .ant_environments.create_maze_env import create_maze_env import numpy as np """Environments taken from HIRO paper github repo: https://github.com/tensorflow/models/tree/master/research/efficient-hrl There are three environments that can be represented by this class depending on what environment_name you provide. ...
3db3b5ca43e22dda42fc6b20a6fcb084cbdfd32b
prem2597/Python-socket
/Guessing Game/guessing_client.py
1,248
3.5625
4
''' Write a python client program that 0. connects to localhost and port 10000 1. send a "Hi <name>" message 2. waits for the server to send the "READY" message 3. guess a number and send to the server 4. wait for the server to send the message 5. Read the message and...
1b0b96fe65b2d3582357197aa9670bd23eb05f76
ortizjd-jmu/interactive-maps
/interactive-maps-2.py
1,036
3.53125
4
import pandas as pd import plotly.express as px # Opens mapbox public token .txt file and reads it with open('D:\Documents\Python_Programs\interactive-maps\mapbox_tkn.txt', 'r') as f: mapbox_key = f.read().strip() # reads the scraped data for popular Areas, Food/Drinks, Transportation, Lodging, and NAN loc_df =...
458c71876e43e72f5c0215b1873bad58422f815b
notalentgeek/pyautomation
/pth.py
4,884
3.734375
4
from sys import platform import os import exc import var """ `chk` refers to "check". `ap` refers to absolute path. `sp` refers to system separator. "/" in Unix or "\" in Windows. """ """ This is a function to check if a provided path is an absolute path or a relative path. """ def chk_ap(_s:str) -> bool: return os.p...
7487a6e2960a136792e30eeb5712f50512fd4eee
WesStutzman/Matrix-Multiplication-Python
/main.py
1,922
3.625
4
#!/usr/bin/env python3 import time import myModule from random import randint def get_random_array(input_x = 0, input_y = 0): return_list = [] for i in range(0, input_x): return_list.append([]) for m in range(0, input_y): return_list[i].append(randint(0, 1000)) return return_list def matrix_mult...
9a261d56857e3e80fbe58f0315f16185d44017b5
kdha123/Django
/django/class1.py
1,573
3.984375
4
# class 클래스명: # 함수 # 함수 # class User: # def __init__(self, name, age): # print('생성자 호출') # self.name = name # self.age = age # # def __init__(self, name): # print('생성자 호출') # self.name = name # # def getinfo(self): # print(self.name+','+str(self.age)) # # # ...
8fca031ae67eb5fcf6b7b7c41584d4d6455c77e3
kuperchal/python-course-2018
/B4162/Kalimullin/2018-12-01/ryb.py
102
3.53125
4
kto=[1,5,3,4,2] max=kto[0] for i in range(len(kto)): if kto[i]>=max: max=kto[i] print(max)
6ece19f0cdb723ad6f46f1f6c7fc039fe711a285
kuperchal/python-course-2018
/B4162/Logushkova/2018-09-22/homework1.py
326
3.796875
4
a = float (input("vvedite a:")) b = float (input("vvedite b:")) c = float (input("vvedite c:")) d = b**2 - 4 *a*c if d > 0: x1 = (-b + d**0.5) / (2* a) x2 = (-b - d**0.5) / (2* a) print ("Answer: x1=", x1, "x2=", x2 ) elif d == 0: x1 = -b / (2*a) print("Answer: x1=" , x1) else: print("korney...
7274b0bf2f47f17454e1facfc041ed1be591e226
kuperchal/python-course-2018
/B4162/Kozlov/Control_1.py
156
3.65625
4
#Дан численный массив, преобразовать в строковый array = [1,5,3,4,2] array = [str(i) for i in array] print (array)
d6262839b3c34a08d902805c5b55f987833b35d8
kuperchal/python-course-2018
/B4162/Kalimullin/2018-09-22/2018-09-22 - kvadratnoe yp.py
356
3.875
4
a=int(input('Введите 1 коэффициент = ')) b=int(input('Введите 2 коэффициент = ')) c=int(input('Введите 3 коэффициент = ')) D=b**2-4*a*c if D>0: print('x1 =',(-b-((D)**(1/2)))/(2*a)) print('x2 =',(-b+((D)**(1/2)))/(2*a)) elif D==0: print('x =',(-b/(2*a))) else: print('Корней нет')
f58500778ee9bc75d74e358bad997ae772bd678b
kuperchal/python-course-2018
/B4162/Kolotaev/2018-10-20/homework3.py
1,994
3.53125
4
class sp: def __init__(self, a): self.a = a #заполняет матрицу выбранным значением def fill(self, ch): self.ch = ch for i in range(len(self.a)): for j in range(len(self.a[i])): self.a[i][j] = self.ch #выводит матрицу def show(self): print(self.a) #выводит размерность матрицы def sh...
63f97c25f680ac1a7393a00b389756659a559def
iamuhammadkhan/SSUET-Python-Practice
/Chapter 5/Exercise 5-4.py
292
3.875
4
alien_life = 10 alien_color = str(input('Please enter a color to improve alien life ')) if alien_color == 'green': alien_life += 5 print('You just scored 5 points') elif alien_color == 'yellow': alien_life += 10 print('You just scored 10 points') else: print('You lost')
368e7c29f57ab23714cd4f93f739ca0044866850
iamuhammadkhan/SSUET-Python-Practice
/Chapter 4/Exercise 4-2.py
171
3.78125
4
fav_animals = ['Cat', 'Dog', 'Rabbit'] for a in fav_animals: print(a) for b in fav_animals: print('A ' + b, 'would be a great pet') print('These could be pets')
4244d0fff49a2df25cf5d50a95ad0771159b6327
iamuhammadkhan/SSUET-Python-Practice
/Chapter 4/Exercise 4-1.py
397
3.6875
4
fav_dish = ['Pizza', 'Zinger', 'Chinese'] for i in fav_dish: print(i) for a in fav_dish: print('My favourite dish is ' + a) print('I really love Pizza, I really love Pizza, I really love Pizza, I really love Pizza, I really love Pizza, I really love Pizza, \nI really love Pizza, I really love Pizza, I really...
11e6c0fd830349e595f31eb5c72fb8ce7762d7bf
iamuhammadkhan/SSUET-Python-Practice
/Chapter 4/Exercise 4-12.py
261
4.03125
4
pizzas = ["Pepperoni","Chicken Tikka","Hawaiian pizza","Italiano Crust","Crunchy Thin Crust"] foods = ["Cake","Ice Cream","Halwa Puri","Fries","Burger"] print("Pizzas are:") for pizza in pizzas: print(pizza) print("Foods are") for food in foods: print(food)
7d7ad17a019a6423f4b18476277b4a1e3b23ebe6
boojack/formal-methods-assignments-ustc
/assignment6/queen.py
5,966
3.921875
4
"""N-queens puzzle The N-queens problem is about placing N chess queens on an N*N chessboard so that no two queens threaten each other. A solution requires that no two queens share the same row, column diagonal or anti-diagonal.The problem's target is try to find how many solutions exist. """ import time from z3 im...
239391710467264da58b2ef118be8b0581550ccf
boojack/formal-methods-assignments-ustc
/assignment6/linear_regression.py
6,519
4.0625
4
import matplotlib.pyplot as plt from z3 import * from linear_regression_ml import sklearn_lr class Todo(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg def __repr__(self): return self.__str__() ############################################...
959e8ee0cb16ff96fae87e92226fa286295eca71
Cybernetic1/symmetric-polynomial-NN
/poly-algebra-1.py
7,667
3.515625
4
# Polynomial algebra (1) -- programmatically compute invariant weight colors # ========================================================================== # This version succeeds in performing one LINEAR matrix multiplication # The program (this version) computes the output for 1 layer: # 1. Each output component is a ...
0f0f4e53d19ef3e24953f32e42f34ea5ca631d31
Sephoro/elen4020-lab3
/code/WordIndex.py
1,503
3.53125
4
import mrs import string class WordIndex(mrs.MapReduce): def map(self,line_num,line_text): stopWords = open('stopWords.txt','r').read().split() #Extra punctuation morePunct = ['--', '...', '\''] for word in line_text.split(): # Check for ...
01b01a7b660b3afa7391bf61a3c3e990b8051c5e
kazhiryu187/myProgramming
/c2f.py
178
4.1875
4
# Celsius to Fahrenheit converter cel = float(input('Temperature in Celsius: ')) #cel = int(cel) fah = (cel * 9/5) + 32 print("{} Celsius = {} Fahrenheit ".format(cel, fah))
0f2ce0d0219274578f21b0e9ef8a5ddf99809d83
GuidoTorres/codigo8
/Seman4/Dia4-python/03-funcion-new.py
1,011
4.28125
4
#Metodos magicos class Empleado: def __new__(cls): print("El metodo magico_new_ ha sido invocado") instancia = object.__new__(cls) print(instancia) return instancia def __init__(self): print("El metodo magico __init__ ha sido invocado") def __str__(sel...
d84cadab27615c30f1d12d7e9dff4237c97b5780
GuidoTorres/codigo8
/Seman4/Dia2-Python/ejer.py
1,437
4.1875
4
class Coordenadas(): def __init__(self, coordenadaX , coordenadaY): self.coordenadaX = coordenadaX self.coordenadaY = coordenadaY def valores(self): print("Los valores ingresados fueron:","(" , self.coordenadaX,",", self.coordenadaY ,")") def cuadrante(self): if...
8b89727db39b09e46e6378ea6718001951cc9f78
GuidoTorres/codigo8
/Seman4/Dia1/06-esxcepciones.py
969
4.15625
4
# excepciones => try ... except ... else ... finally # try: # #Todo lo que va a suceder dentro del try y si hay un error # #no va incidir con el funcionamiento de nuestro programa # n1 = int(input("Ingrese numero 1: ")) # n2 = int(input("Ingrese numero 2: ")) # division = n1 / n2 # print(di...
e6d182e54dcdc39d3cd2652d98583a1d0030ecb0
Ali-Omrani/DNS-Hierarchy
/DNS Hierarchy/TOPO.py
1,175
3.90625
4
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo class My...
9af3ae57b8654e1d3ab98bbbb4df26e0b8aa4dd5
zubun/DZ_3
/hw3_3.py
636
4.125
4
def my_func (arg_1, arg_2, arg_3): '''adding two maximum numbers - сложение двух максимальных чисел''' list_1 = [arg_1, arg_2, arg_3] number_1 = max(list_1) list_1.pop(list_1.index(max(list_1))) number_2 = max(list_1) summ = number_1 + number_2 return summ arg_1 = float(input("Введите перво...
a21568f61edffe5b17c412734aa38ce9918956f8
JoseCordobaEAN/ProgramacionG320182
/Semana_9/saludar.py
195
3.75
4
# Saludar hasta que diga chao mensaje = 'dime algo y lo repetiré hasta que me digas "chao"' ingresado = "" while ingresado.lower() != 'chao': ingresado = input(mensaje) print(ingresado)
656dc2837419bdae8ced84fd8ccc1f2df9581ada
JoseCordobaEAN/ProgramacionG320182
/Semana 4/Ejercicios semana1.py
907
3.890625
4
def de_kelvin_a_centigrados(kelvin): """ (float) -> float Convierte una cantidad dada en grados kelvin a grados centigrados >>> de_kelvin_a_centigrados(273.0) 0.0 >>> de_kelvin_a_centigrados(73.0) -200.0 :param kelvin: (float) la cantidad de grados kelvin :return: (float) la can...
965f6ee7983db7fa1b5d10b9f220ad5d56894edc
JoseCordobaEAN/ProgramacionG320182
/Semana_11/ejercicios_while.py
2,143
4.21875
4
def de_la_z_a_la_a(): """ () -> list of str >>> de_la_z_a_la_a() ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] :return: list con las letras de la z a la a """ resultado = [] contador = 122 while co...
72905d05794fb7305ed436ba41193689dcc803ab
JoseCordobaEAN/ProgramacionG320182
/Semana_12/funciones_diccionarios.py
1,465
3.875
4
def union_diccionarios(dic1, dic2): """ (dict, dict) -> dict Hace la union entre los dos diccionarios >>> union_diccionarios({'hola':'mundo'}, {'mundo': 'hola'} ) {'hola': 'mundo', 'mundo': 'hola'} >>> union_diccionarios({'hola':'mundo', 'mundo': 'hola'}, {'jose':'cordoba'} ) {'hola': 'mun...
94330ced7a14e30c9471635029b5aab87a0053dc
juliopovedacs/datascience
/1. Python/Intro to Python course/bmi_program.py
221
4.1875
4
#Body Mass Index Python Program print("BMI PYTHON PROGRAM") height = input("What is your height? \n") weight = input("What is your weight? \n") bmi = height / weight ** 2 print("Your Body Mass Index is " + str(bmi))
3a89024106e4d253736123414b0dd7f2e3281b4e
ananduri/insight_h1b_statistics
/insight_testsuite/temp/src/FreqMax.py
6,337
4.25
4
from collections import namedtuple KeyValue = namedtuple('KeyValue', ('key', 'value')) class DblNode: '''Node for doubly linked list''' def __init__(self, datum): self.datum = datum self.next = None self.prev = None class FreqMax: ''' Data structure used to track most frequent...
d11670f69011653abb1c767e0709ab39bbe89613
amigoavena/Shutdown-Restart-Logout-Windows-Python
/Shutdown, Logoff, Restart - Tkinter.py
2,463
3.8125
4
from tkinter import * from tkinter import ttk import os window = Tk() window.title("Logout Manager") def shutdown_window(): shutdown_win = Toplevel(window) shutdown_win.title("Shutdown") Label(shutdown_win, text = "Are you sure you want to shutdown your computer now?").grid(row = 0, columnspan = 2, ...
ff314553704b0bf5a11c84c45083231043362fd4
janpara/Parrillas
/escribir_tabla.py
2,217
3.625
4
import sqlite3 def leer_catalogo(): kdc = {} #leemos el fichero con todos los capitulos y creamos un diccionario con ellos lineas = len(open('KDC.txt').readlines()) fichero = open("KDC.txt", "r") for iteracion in range(lineas): dato = fichero.readline() if "/" in dato: pa...
f6d2ffeff53816d3667c8a46646cfe50d236fed7
yutamago/GameAI2018
/resources/shortest_path.py
779
3.78125
4
''' Created on Sep 15, 2013 @author: pglauner ''' def shortest_path_search(start, successors, is_goal): """Find the shortest path from start state to a state such that is_goal(state) is true.""" if is_goal(start): return [start] explored = set() # set of states we have visited frontier =...
1aeecab1f13099d486850dcd8b785e7df12f08d0
katyja/python-observer
/utils/states.py
234
3.546875
4
import abc from enum import Enum class Stateable(abc.ABC): """ Abstract class for states """ class States(Enum): pass @property @abc.abstractproperty def states(self): return self.States
24dab539541f5eb32e4f161bf5e4c2c8084c5baa
tanyaphung/Genetic_Architecture
/ABC_method/get_slim_outputs.py
1,254
3.6875
4
import random def get_slim_outputs(directory, m): """ This function obtains SLiM outputs. Each SLiM simulation is 100kb. The number of SLiM outputs to be obtained is dependent on the value of M. For example, if M is 200kb, 2 SLiM output files are obtained for analyses. :param directory: This is the di...
7b47343944b63e77be8d295bf8de16039ad836ed
elliptic1/Hello-Repo
/hi.py
451
3.9375
4
#!/usr/bin/python msg = "This is the Paid version" n = 20 print msg print n # Comment: This is my list myList = ['Milk', 'eggs', 13, 21, 8] print "There are ", len(myList), " things on my list." print "The Second Item on the list is" , myList[1] i=0 # This loop only runs in the paid version while i<10: print i ...
9f7ab2ec4f7747b7c72e3815310403bcaf53bac8
ShushantLakhyani/200-Python-Exercises
/exercise_7.py
570
4.28125
4
# Q7) Write a Python program to construct the following pattern, using a nested for loop. # * # * * # * * * # * * * * # * * * * * # * * * * # * * * # * * # * #step 1: let a variable have the value 5, because of the final number of asterisks is 5 x = 5 # step 2: first 'for loop' to output the asterisks for the ...
f4753e41101f6702cad27b5c62848e3afc1662a3
ShushantLakhyani/200-Python-Exercises
/exercise_5.py
538
4.4375
4
#Write a python program to check if a triangle is valid or not def triangle_validity_check(a,b,c): if (a>b+c) or (b>a+c) or (c>a+b): print("This is not a valid triangle.") elif (a==b+c) or (b==c+a) or (c==a+b): print("This can form a degenerated triangle.") else: print("These values ...
340d779fbcb7a75975d1da98170879b9c2448954
ShushantLakhyani/200-Python-Exercises
/exercise_29.py
363
3.796875
4
# Write a Python function to create the HTML string with tags around the word(s). # Sample function and result : # add_tags('i', 'Python') -> '<i>Python</i>' # add_tags('b', 'Python Tutorial') -> '<b>Python Tutorial </b>' def add_tags(tag,word): return "<%s>%s<%s>" % (tag,word,tag) print(add_tags('i', 'Python'))...
2de6e4f4e6b61f97dc19627994d5d7fe04c0bcfd
ShushantLakhyani/200-Python-Exercises
/square_root__positive_number.py
247
4.21875
4
# Q3) Find the square root of a positive number #Declare a number in a variable a = 8 #to find thhe square root we raise the number to the power of 0.5, so raise a to the power of 0.5 a = a ** 0.5 # Now, print a to get the square root print(a)
c4ed80db929a1218c2bee51a9f6691b5a3677bcb
AtnuamInar/python_assignment_dec15
/q3.py
287
4.34375
4
#!/usr/bin/python3 num_list = [1, 2, 3, 4, 6, 7, 8, 9] def power(num_list): cube = list(); for num in num_list: cubed = num ** 3 cube += [cubed] return cube cube = power(num_list) print('Original list\t = {}\nCubed list\t = {}'.format(num_list, cube))
65f62d5cdcd3f29aa7b10147caf7afa5bbe5facb
hptruong93/TXT
/hw_set_map.py
3,171
4.65625
5
# In python a set is initialized with the_set = set() # Usage of set is simple the_set.add(1) the_set.add(2) for num in the_set: print("We have number %s in the set." % num) if 2 in the_set: print("2 is in the set") the_set.remove(2) if 2 not in the_set: print("2 is not in the set") # Map in python is c...
874543d68442f09ebe5b0b1a85091c3e64d04632
philipdexter/build-a-lang
/fib.py
153
3.703125
4
def fib(n): a = 0 b = 1 i = 1 while i < n: a, b = a + b, a i += 1 return a for i in range(0, 10): print(fib(i))
f9bc94b090998966bf94e9609686836a61381614
AcidicNic/SPD2.3
/refactoring-composing-methods/extract_method3.py
545
3.625
4
# Written by Kamran Bigdely # Example for Compose Methods: Extract Method. import math def get_circle_distance(xc1, yc1, xc2, yc2): """Returns the distance between the two circles.""" return math.sqrt((xc1-xc2)**2 + (yc1 - yc2)**2) print(f'distance: {get_circle_distance(4, 4.25, 53, -5.35)}') def get_vector_...
ebca23a55f335180898261bef4f90c514594e344
AcidicNic/SPD2.3
/unit-testing/exercise_2.py
1,096
3.703125
4
from math import log T_HALF = 5730 DECAY_CONSTANT = -0.693 class InvalidCarbon14Ratio(Exception): pass def get_age_carbon_14_dating(carbon_14_ratio): """Returns the estimated age of the sample in year. carbon_14_ratio: the percent (0 < percent < 1) of carbon-14 in the sample conpared to the amount in...
582e00fca36bad3bc8dce9f4ceabc100eb4e8614
blackpanther409/foldersyncing
/client_chat.py
1,794
3.65625
4
#client socket import socket #functions for sending and receiving messages def sending(): msg = input('client:') global a if 'bye' in msg.lower().strip(): a=0 if len(msg)>0: s.send(bytes(msg,"utf-8")) print('message sent') def receiving(): msg = s.recv(1024) msg = msg.decode("utf-8") global...
dc7e2704b42e58cbb4ca38a7f2cb5c466f815945
tidhardavid/DevOps-Pycarm
/DevOps1/20181022/assignment3.py
1,732
4.09375
4
#Tidhar Ben David #Assignment 3 print('Assignment 3:') #A class Dog: def __init__(self, name = None, age = None): self.name = name self.age = age def mainA(): print('A.') rexi = Dog('rexi', 3) print(rexi.name, ' is ', rexi.age, ' years old') #B the code will print the instance age - ...
e52a6f27f5629274acf3e14b3ff10ce3c23e9ce0
Abassade1/switch_adebayo
/GuessGame_UPDATED.py
1,839
3.984375
4
print ("=====WORD GUESS GAME SOLUTION=====") WORD_LIST =["game", "car", "plane", "laptop", "switch", "civichive"] import random def pick_word(list_word): word = random.choice(list_word) return word def get_guess(): #print("running the get_guess function") guess = input("Guess a word: ") if not gue...
9feda80b847322e53438513ab2cdd225e69c779e
Abassade1/switch_adebayo
/Guess_Game_2017.py
1,231
4
4
import random g_word_list = ["game", "car","plane","laptop","switch","civichive"] g_game_count = 1 def pick_word(): word = random.choice(g_word_list) return word def get_guess(): while True: guess = input("Guess a word: ") if guess != "": return guess print ("Word ca...
ac4f05c23813f49b866204fe0fd4bc3bbd1a1c7c
JohnGeenty/NetworkSim
/client_TCP.py
1,093
3.71875
4
from socket import * #Set up the TCP stream socket client_s = socket(AF_INET,SOCK_STREAM) #Declare both the server IP and the port number SERVER = '127.0.0.1' PORT = 40404 #Connect the client to the server on port 'PORT' client_s.connect((SERVER,PORT)) #Begin the while loop while True: # output = client_s.recv(10...
b04244b7a80bad4f16ccb51c43f9eb4d410476d3
kaweepong39/oop-python
/getterSetter/exGetterSetter.py
1,377
3.9375
4
# Java style class Person: def __init__(self, fname, lname, position): self.fname = fname self.lname = lname self.setPosition(position) def __str__(self): return "Name:{} {} position:{}".format(self.fname, self.lname, self.__position) def getPosition(self): return self.__position def ...
a7d9ec33bb704a750182163cc6761b5fda1412fc
jonmarkprice/explorations
/hackerrank/12/2017-03-07.py
1,829
3.8125
4
def merge(a, b): # This is the problem step. DOn't do it! c = a + b #list i = 0 j = len(a) # first item of b inv = 0 while i < j: if j >= len(c): break if c[i] > c[j]: # successively swap k = j # wh...
f61513fc92dbefffa28ffc1128f745db341894db
ibyt32/pynet_test
/w1e8_ciscoconfparse.py
939
3.78125
4
#!/usr/bin/env python # Python and Ansible for Network Engineers # Week 1, Exercise 8 # # Write a Python program using ciscoconfparse that parses cisco_ipsec.txt. # Note, this config file is not fully valid (i.e. parts of the configuration # are missing). The script should find all of the crypto map entries in the # f...
8640d4907b25214905d4c98cfd716a91bf38ea55
factoredai/sokrates
/app/app_core/data_processing/text_extract/base.py
354
3.5625
4
import pandas as pd from abc import ABC, abstractmethod class Extractor(ABC): """ Interface to represent feature extractors. """ @abstractmethod def process_df(self, df: pd.DataFrame) -> pd.DataFrame: """ Process the given dataframe to extract features. :param df: ...
2a10d7aa154938c75dc57289b058f41873ca5b93
fredmorcos/attic
/Coding/Project Euler/p1.py
259
3.8125
4
def f(x,count=False): if count==False: return f(x-1,True) if x==0: return 0 elif x%3==0 or x%5==0: return x+f(x-1,True) else: return f(x-1,True) if __name__ == '__main__': print(f(10)) print(f(20)) print(f(30)) print(f(1000))
91dc62ac370d40be3f2a6fa98ad6f3dd88da80d6
fredmorcos/attic
/Projects/PyFuzz-2/variable.py
1,695
3.6875
4
class Variable: """ an input/output variable, a set of functions """ def __init__(self, label = ""): """ constructor """ self.functions = [] self.label = label self.mh = 0.0 def add_function(self, function): """ append a function to the list of functions """ self.functions.append(functi...
f270fdbfd92a0a104ddb16542699baa1280da0f7
fredmorcos/attic
/Projects/PyFuzz-2/rulebase.py
1,995
3.578125
4
from rule import Rule class RuleBase: """ a set of rules """ def __init__(self, inputs = [], outputs = []): """ constructor """ self.inputs = inputs self.outputs = outputs self.rules = [] def generate(self): """ generates the rules base from all possible combinations of input vari...
2f6ccd47de4add0f934f2db0721969b2da452ff4
BraydenCleary/SF_DAT_15_WORK
/hw/hw1.py
4,550
3.8125
4
import pandas as pd # pd.set_option('max_colwidth', 50) # set this if you need to import sys,os path = os.path.realpath('../hw/data/police-killings.csv') killings = pd.read_csv(path) killings.head() # 1. Make the following changed to column names: # lawenforcementagency -> agency # raceethnicity -> race ki...
e4397104cd4f075cbeeeaed74d1c7fb7bdd4d23f
acompagnon/elbow_point_detection
/elbow_point_detector.py
836
3.765625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Author: Aloyse Compagnon def detect_elbow(x: list, y: list): """Find elbow point in a curve. Args: x (list): x axis values. y (list): y axis values. Returns: elbow_x: elbow point x axis value. elbow_y: elbow point y axis value....
b5dfcda8e0f15e7547513d51c52c5ecfe19a6d44
roocell/garage-pi
/switchrelay.py
1,142
3.5625
4
#!/usr/bin/python3 import RPi.GPIO as GPIO import time door1 = 7 # GPIO4 door2 = 37 # GPIO26 relay1 = 12 # GPIO18 relay2 = 16 # GPIO23 relay3 = 18 # GPIO24 relay4 = 22 # GPIO25 def setup(): GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering GPIO.setup(door1, GPIO.IN, pull_up_down=GPI...
6afac551ac43aae0ef7eb22041eeec9a1af88704
Perilynn/HackerRank-Coding-Challenges
/Greedy/Grid Challenge/andrew.py
853
3.640625
4
class Grid(object): def __init__(self, rows): self.rows = rows def canBeSorted(self): temp = [] for row in self.rows: temp.append("".join(sorted(row))) # check columns for j in xrange(len(temp[0])): col = [temp[i][j] for i in xrange(len(self.rows))...
bd8910fbc246c9cefdfb682ab69bfe863d17c8eb
Perilynn/HackerRank-Coding-Challenges
/Greedy/Grid Challenge/Modi.py
1,664
3.859375
4
## Solution for HackerRank Algorithms/Greedy/Grid Challenge ## https://www.hackerrank.com/challenges/grid-challenge __author__ = 'modi95' __date__ = 'Thursday 4 June 2015' # It seems one can rephrase this question as follows: # # Can each row be sorted such that: # - Each row is in lexicographically sorted # - E...
338486b9f2a5cef2b3d9b90aa1d5e6492a72a44d
voygha/RedGraySearchservice
/ejer13_for_range.py
240
3.921875
4
productos= ["Monitor", "Smart TV","Tablet", "Audifonos","Smart Watch"] for producto in productos: print(producto) numeros= [1,2,3,4,5,6,7,8,9,10] for numero in numeros: print(numero*2) for indice in range(5,15,2): print(indice)
61133e6fa91e503cd0aa8370debc3140534d03a5
voygha/RedGraySearchservice
/ejer3_instrucciones_con_texto.py
968
4.28125
4
mi_cadena= "Hola mundo!" mi_cadena2= 'Hola mundo!' print(mi_cadena) #Si se va a mostrar comillas en una cadena, se debe poner una comilla contraria a las que se va a utilizar cadena_con_comillas= 'Javier dijo: "Hola Mundo"' print(cadena_con_comillas) comillas_simples= "Hello it's me!" print(comillas_simples) #EL ...