blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0e544a35af7083262b759e756838e87d877bbcd8 | cai-yang/python-test | /up1st.py | 220 | 3.984375 | 4 | #This program is for corrcting the user's input by making the fisrt letter upwrote.
def up1(name):
return name[0].upper()+name[1:].lower()
#Test the up1
c=map(up1,['jaSon','dicK','JohNson'])
for x in c:
print x
|
cbb9bfc0c1f060f0322d085864ca56906cb41833 | tejaskale1495/python-Numpy-Panda | /function.py | 2,193 | 3.765625 | 4 | #function
# def add_sub (a,b):
# c = a+b
# d =a-b
# return c,d
#we can also print it
# print(c)
#result1,result2 = add_sub(2,4)
#print(result1,result2)
#passing the value
# def update (lst):
# print(id(lst))
# lst[1] =35
# print(id(lst))
#
# lst = [12,23,45]
# print(id(lst... |
55aa700e317cd81b0eb31448c52ec88a9fe873cc | tejaskale1495/python-Numpy-Panda | /input.py | 1,201 | 3.9375 | 4 | # user input
# x =int (input("enter 1s number"))
# y = int(input("enter 2nd number"))
# z = x + y
# print(z)
# ch = input("eneter a char")[3:]
# print(ch)
# evaluate a expression
# result = eval(input("enter the exp"))
# print(result)
# condition
# x= int(input("enter number"))
# r = x%2
# if r==0:
... |
2e466d4af2b60146a54d4a0dff38baa35d46a969 | caojianfeng/py_fibonacci | /rabbits.py | 626 | 3.765625 | 4 | #!/usr/bin/env python3
LIMIT = 1474 #122.8年后,月数会超出这个数字,计算机也数不清有多少兔子了。
def fibos(month):
fibo_list = []
big = 0
small = 1
for i in range(0, min(month, LIMIT)):
fibo_list.append({'month': i+1, 'small': small, 'big': big})
big, small = small+big, big
return fibo_list
def print_rabb... |
5660d63772242db7572af7a79338f14e923e13c8 | katpawan/PythonPractice | /HSBCEmployee.py | 596 | 3.65625 | 4 | from Employee import Employee
import n
class HSBCEmployee(Employee):
"""docstring for HSBCEmployee"""
def __init__(self, name, salary, team):
super(HSBCEmployee, self).__init__(name, salary)
print('in child\'s constructor')
self.team = team
def __del__(self):
print('paren... |
1a0e1f6296fec7e7cab389ebb708802c1e46c539 | katpawan/PythonPractice | /hello.py | 699 | 3.515625 | 4 | import sys
def Cat(filename):
f = open(filename, 'rU')
# for line in f:
# print(line,end="");
# lines = f.readlines();
lines = f.read()
print(lines)
f.close()
def Hello(name):
if(name == 'Pawan' or name == 'Lucky'):
print('Pawan in if')
name = name + '!!!!!'
print('... |
44b0620147a5d865289ad354c7da7a73407ad299 | AdityaPunetha/UPES-Sem2-Python- | /Lab9.2.py | 266 | 3.84375 | 4 | mylist = [1, 2, 3, '4', 5]
sum = 0
for i in mylist:
try:
sum = sum + i
except TypeError:
print("unsupported operand type(s) for +: 'int' and 'str'")
print(sum)
try:
print(mylist[5])
except IndexError:
print("list index out of range")
|
b09a354292b60be1fe2cdc2b4028bf080c1cc89e | Jnmendza/pythonpractice | /Algorithms/Arrays/anagram.py | 1,277 | 4.28125 | 4 | """
Given two strings, check to see if they are anagrams. An anagram is when the two strings can be
written using the exact same letters(so you can just rearrange the letters to get a different
phrase or word).
For Example:
"public relations" is an anagram of "crap built on lies."
"clint eastwood" is an anagram of "ol... |
de8ce4921957bb63fe790233d4c4403f141078ec | Jnmendza/pythonpractice | /Algorithms/Strings/non_repeat_elem.py | 730 | 3.875 | 4 | """
Non repeat element
Take a string and return character that never repeats
if multiple uniques then return only the first unique
"""
def non_repeating(s):
s = s.replace(' ', '').lower()
char_count = {} # empty dictionary
for c in s:
if c in char_count:
char_count[c] += 1
el... |
4238eda403ffcd600d6c172e2adc91dbd2c3e887 | mike-bskim/coding_test | /section 6/2. 이진트리순회(DFS)/aa.py | 388 | 3.609375 | 4 | import sys
# import heapq as hq
# sys.stdin = open('input.txt', 'rt')
# 전위순회 방식(print, DFS, DFS)
# 중위순회 방식(DFS, print, DFS)
# 후위순회 방식(DFS, DFS, print), 병합정렬인경우
def DFS(x):
if x>7:
return
else:
DFS(x*2)
DFS(x*2+1)
print(x, end=' ')
if __name__ == "__main__":
# n = int(input())
DFS(1)
# print... |
5f18f72cc42bcc22af31887840a521570268a4cb | Mahsum21/exercicespython | /Chapitre 1/Exercices C1C Ennoncés/C1C3.py | 1,484 | 4 | 4 | # Enoncé : Votre programme demande à l'utilisateur d'entrer un chiffre, ce chiffre représentera le sexe la personne (1:femme 2:homme 3:autre)
# En fonction de l'entrée donnée, le programme donnera un résultat différent, le programme saluera la personne en prenant en compte son sexe,
# (Boujour Madame/Boujour Monsieur/... |
6583f0eee28d27673a03d78bcd157b307cc4ce7f | rickythai1996/afs505_u1 | /project/game_of_life_draft_0.py | 2,062 | 4 | 4 | from sys import argv
def print_grid(grid, n_row, n_col):
# Iterate through the rows of the grid.
for i in range(n_row - 1):
# Iterate through the columns of row i.
for j in range(n_col - 1):
# If the cell identified by i,j is a 0 then print
# a -. If it's a 1 then print... |
0d340f052642cb01ec41894cceb9882cbda04613 | osnipezzini/PythonExercicios | /desafio010.py | 264 | 3.921875 | 4 | # Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela pode comprar .
# Considere US$1,00 = R$3,27
n1 = float(input('Quanto você tem de dinheiro ? R$ '))
print('Você pode comprar {:.2f} dólares'.format(n1/3.27)) |
326286587fa50d1f594914eba6be450eef4c4686 | osnipezzini/PythonExercicios | /ex062.py | 640 | 3.96875 | 4 | '''
Melhore o Desafio 061, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerra quando ele disser que quer mostrar 0 termos.
'''
from emoji import emojize
pt = int(input('Digite o primeiro termo: '))
raz = int(input('Digite a razão: '))
sign = emojize(':arrow_right:', use_aliases=True)
... |
b52ff347a412af35097881b0f905667f4edcd545 | osnipezzini/PythonExercicios | /ex071.py | 952 | 4.25 | 4 | '''
Crie um programa que simule o funcionamento de um caixa eletrônico. No inicio, pergunte ao usuário qual será o valor a ser sacado ( numero inteiro ) e o programa vai informar quantas cédulas de cada valor serão entregues.
OBS: Considere que o caixa possui cédulas de R$ 50, R$20, R$10 e R$1
'''
print('=' * 30)
prin... |
5020d728d855309f974ffba64e5a0a34e3368742 | osnipezzini/PythonExercicios | /ex027.py | 384 | 4.03125 | 4 | """Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o ultimo nome separadamente .
Ex: Ana Maria de Souza
primeiro = Ana
ultimo = Souza"""
from format import style
nome = str(input('Digite seu nome completo : ')).strip()
n = nome.split()
style()
print('Seu primeiro nome é {}'.... |
3cd3830e89c955e0025dd219f52fa559b515a3a5 | osnipezzini/PythonExercicios | /ex060.py | 428 | 4.09375 | 4 | '''
Faça um programa que leia um número qualquer e mostre o seu fatorial.
Ex: 5! = 5x4x3x2x1 = 120
'''
from emoji import emojize
user = int(input('Digite um valor e lhe mostrarei o fatorial : '))
mul = user
fat = 1
sign = emojize(':heavy_multiplication_x:', use_aliases=True)
while mul > 0:
print('{}'.format(mul), ... |
3c9b12eccf6fee2ca501319a3c530a101dd3376a | lofues/Data_Science | /02_matplotlib/18_animation.py | 309 | 3.5 | 4 | """
演示matplotlib的动画功能
"""
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.animation as ma
import random
def update(number):
print(number)
mp.text(random.random(),random.random(),number)
mp.figure("a")
a = ma.FuncAnimation(mp.gcf(),update,interval=30)
mp.show() |
25256b29db5f0f6495a521d6539e2d590dc55a40 | lofues/Data_Science | /01_numpy/06_numpy_slice.py | 185 | 3.609375 | 4 | import numpy as np
arr = np.random.randint(0,100,(5,5))
print(arr)
# 多维数组的切片[行,列]
print(arr[0][:-4:-1])
# 以逗号为分割,前两行前两列
print(arr[:2,:2])
|
a17fe2d824565081b038f040a4494f437f89da81 | lofues/Data_Science | /01_numpy/08_stack_stack.py | 1,455 | 3.609375 | 4 | """
多维数组的组合与拆分
"""
import numpy as np
a = np.arange(1,7).reshape(2,3)
b = np.arange(7,13).reshape(2,3)
print('a->',a)
print('b->',b)
# 垂直组合 vertical
# axis 为0 垂直方向
print('*'*50)
c = np.vstack((a,b))
c = np.concatenate((a,b),axis=0)
print('vertical:',c)
# 水平组合 hiro...
# axis 为1 水平方向
print('*'*50)
d = np.hstack((... |
13b076f60cc48afb65a846f12d2975a7b3ef3c69 | arunshankarsam22/Python | /oddorevenswap.py | 226 | 3.984375 | 4 | '''Given a string s swap the even and odd characters.
Input Size : |s| <= 10000000(complexity O(n))
Sample Testcase :
INPUT
abcd
OUTPUT
badc'''
a=input()
b=len(a)
c="".join([a[i:i+2][::-1] for i in range(0,b,2)])
print (c)
|
7b9b9e65aeb5d7a082db9b24cf58df8e9c4343d2 | arunshankarsam22/Python | /swapnumberttogeneratebiggest.py | 95 | 3.546875 | 4 | m1=input()
m2=input()
m3=m2.split()
m4=''.join(m3)
print(''.join((sorted(m4,reverse = True))))
|
eddb3cc5fd3d8cc2e693f4c3c3538943e6780846 | arunshankarsam22/Python | /factorial.py | 199 | 4.0625 | 4 | '''Given a number N, find its factorial.
Input Size : N <= 20
Sample Testcase :
INPUT
5
OUTPUT
120'''
a=int(input())
factorial=1
for i in range (a,0,-1):
factorial=factorial*i
print(factorial)
|
51119c8e22f4fb752eb7910b3d1ce1285a7e25e4 | wtreston/python-labs | /week1/car-salesman.py | 336 | 3.890625 | 4 | base_car_price = float(input("Enter the base car price: "))
tax = base_car_price * 20 / 100
license = base_car_price * 5 / 100
dealer_prep = 200
destination_charge = 50
car_price_with_extras = base_car_price + tax + license + dealer_prep + destination_charge
print("The price of your car with added extras is: ", car_pri... |
cb4298287d4e50cc9917f8f9ba056097c3483cd8 | sksoumik/Algorithm-Design-and-Analysis | /Divide and Conquer/Quick Sort PsudoCodeType.py | 889 | 4.125 | 4 | # Worst case complexity is O (n^2)
# Best and Average case O (n log n) possible if the pivot is selected as median
# partition function
# https://www.geeksforgeeks.org/quick-sort/
def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
... |
d2ec04d8fc3fcca667bd85451cfe78a84a343d16 | void78/matcher | /bin/sequence_generator.py | 6,691 | 3.6875 | 4 | #!/usr/bin/python
import sys
import random
class Level:
def __init__(self):
self.orders = []
def __str__(self):
level = ""
for order in self.orders:
level += ("%d,"%(order['id']))
return level.replace("\n", ",")
class OrderBookSide:
def __init__(self, side, order_book):
self.side = side
self.levels... |
64da80c795b57e3d76579f03972b440183d6f7a0 | JungleTryne/Tupper-s-formula | /Tupper/tupper_decoder.py | 1,926 | 3.875 | 4 | from PIL import Image, ImageDraw
from Tupper.tupper_constants import IMAGE_MODE, WIDTH, HEIGHT, \
AREA, SIZE_TUPLE, DEFAULT_IMAGE_COLOR
class TupperDecoder:
def _height_to_bin(self, height: int) -> str:
"""
This is the first step of reverse Tupper's algo
We take the height (mentioned a... |
446c6195bdd676149f2f6ee724307aa21ab92e5c | Zilleplus/KHBOLessenroosterAPI | /LessonData.py | 712 | 3.53125 | 4 | #!/usr/bin/python3
# contains the data from one square in the roster and is present in
# the list on the roster data
class LessonData:
def __init__(self) :
self.dataList = []
def add(self,parameter):
self.dataList.append(parameter)
def reset(self) :
for data in self.dataList :
... |
8408e7ca4c46e34d73ede2f3683c8b798988740e | hyperspy/hyperspy-doc | /dev/_downloads/27e577ab3ef879ffbd7ffe80e1c1f4d8/two_gaussians.py | 1,577 | 3.65625 | 4 | """
Simple simulation (2 Gaussians)
===============================
Creates a 2D hyperspectrum consisting of two Gaussians and plots it.
This example can serve as starting point to test other functionalities on the
simulated hyperspectrum.
"""
import numpy as np
import hyperspy.api as hs
import matplotlib.pyplot as ... |
eed127943fd6556b5d5c506d60f481600507c621 | xiangx7805/CS664-Final | /MazeSolving.py | 10,022 | 3.890625 | 4 | import numpy as np
import pandas as pd
import pickle
import turtle
## Dec 13
# this code allow the player to read a txt file
# with special characters for different scenarios
# for instance: + for walls, 'S' for start position/Entrance
# white space allow the move
# we will show two samples
# MazeSample1.text & MazeSa... |
3705d9e2e3078f3ddc003a283a2828d576b1e677 | hillnet/CodeFights | /python/matrixElementsSum.py | 349 | 3.5625 | 4 | def matrixElementsSum(matrix):
result = 0
for i in range(len(matrix[2])):
for j in range(len(matrix)):
if matrix[j][i] == 0:
break
result += matrix[j][i]
return result
print(matrixElementsSum([[0, 1, 1, 2],
[0, 5, 0, 0],
... |
43fa3258b401867afb35c25e815423f429185dab | Plantalytics/automation-example | /tests/test_base_functions.py | 3,176 | 4 | 4 | import unittest
from unittest.mock import MagicMock
import application as app
"""
Unit tests
Must start with 'test_'
Must import unittest
Must have (self) in method declaration
Ideally each test will test 1 thing (have one assertion)
"""
class AppTest(unittest.TestCase):
def test_simple_max_num(self):
"... |
ecf4c63e8fac1412ab51dda8536fc2c5423e657b | financieras/pyCoder | /calculadora.py | 782 | 3.890625 | 4 |
import sys
valor1 = int(sys.argv[1])
valor2 = int(sys.argv[2])
operacion = sys.argv[3]
# para ejecutar tecleamos en la terminal:
# python3 calculadora.py 2 3 suma
def suma(numero1, numero2):
resultado = numero1 + numero2
return
def resta(numero1, numero2):
resultado = numero1 - numero2
return result... |
2c1feba47f8b5ea1980e20c727480430c60e0026 | Tavs64/Tkinter-Gui-Andegradsligning | /TkinterGUI.py | 3,120 | 3.796875 | 4 | from tkinter import *
import sys
solve1_text = "Solution 1"
solve2_text = "Solution 2"
equation_text ="Equation"
class Application(Frame): # Application is a Frame (inheritance from Frame)
def __init__(self, master):
Frame.__init__(self, master, bg='#E33B49')
self.grid(sticky=N+S+E+W) # put frame... |
76f62fafb6814f1441168720d2447975de624c62 | chanvi1/hba_coursework | /exercise/skills1/test_skills1.py | 5,375 | 3.828125 | 4 | import unittest
from skills1 import *
class Test_Skills_1(unittest.TestCase):
def setUp(self):
self.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec']
self.days = ['Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']
... |
fc53a306fa1916aea236832b4de82fceaef56584 | chanvi1/hba_coursework | /exercise/skills2/skills2.py | 4,935 | 4.03125 | 4 | string1 = "I do not like green eggs and ham."
list1 = [2, 5, 12, 6, 1, -5, 8, 5, 6, -2, 2, 27]
list2 = [-5, 6, 4, 8, 15, 16, 23, 42, 2, 7]
words = ["I", "do", "not", "like", "green", "eggs", "and", "ham", "I", "do", "not", "like", "them", "San", "I", "am"]
# """
# Write a function that takes a string and produces a di... |
a97c76b2ad9219ae558668209ddda00f51b39107 | jl-wynen/code_stuffs | /python/single_char_input.py | 262 | 3.8125 | 4 | # read a single character without pressing enter
import sys
import getch
print("Yes or no: ", end="")
sys.stdout.flush()
ans = getch.getche()
print("")
if ans.lower() == "y":
print("yes")
elif ans.lower() == "n":
print("no")
else:
print("What??")
|
50bcc53d544df7d7e2ea85093f4a7bdd007b3e30 | Torend/Python-Functional-Programming | /task_1.py | 3,346 | 3.6875 | 4 |
# for every element x in the list x=x*2+1
def p1i1lc(inputlist):
return [x * 2 + 1 for x in inputlist]
# for every element x in the list x=x*2+1
def p1i1fo(inputlist):
return list(map(lambda x: x * 2 + 1, inputlist))
# for every element x in the list if x divided by 3 without earth division write true oth... |
ce7a47c09383db76b4d1bf650a4857c549c36c08 | Peter13st/Python_lessons_basic | /lesson04/home_work/hw04_easy.py | 2,357 | 3.859375 | 4 | # Все задачи текущего блока решите с помощью генераторов списков!
# Задание-1:
# Дан список, заполненный произвольными целыми числами.
# Получить новый список, элементы которого будут
# квадратами элементов исходного списка
# [1, 2, 4, 0] --> [1, 4, 16, 0]
import random
# Заполняем список произвольными целыми числами... |
a7136e8fb6d5e13819f8a3cc10b2b480565d0e06 | vsudhakar99/Python | /Q261.py | 124 | 3.65625 | 4 |
n = 1
if n == 1:
print("*") # *
if n == True:
print("**") # **
if n == False:
print("***")
print(3 == True)
|
9d799bdd60f5168b5cc9c4dfa1bbba1ad2bdcf90 | gersondi/test | /stmt.py | 220 | 4.03125 | 4 | #enter a fruit name
fruit = input("An ______ a day keeps the doctor away\t")
if fruit == ("apple")or("APPLE"):{
print("correct answer")}
else :
print("incorrect answer")
|
42587c200799de22479198ddf0c6d3702ddee5bd | EtanGuir/packetPython | /complexe/complex.py | 3,004 | 3.59375 | 4 | import math
class complex:
def __init__(self,reel=None,imaginaire=None):
self.reel = reel
self.imaginaire = imaginaire
def __add__(self, x):
"""Addition entre deux complexe"""
comp = complex()
comp.reel = self.reel + x.reel
comp.imaginaire = self.imaginaire + x... |
835a4566f267acfa802663e9ac4fc4b682f83029 | bhamrick/ai2 | /constraint/arccons_ac4.py | 5,926 | 3.78125 | 4 | # Brian Hamrick
# 9/22/08
# Backtracking Constraint Solver
# Input: Three hash maps: domains, assignments, and constraints
# passed as arguments
# domains: Key: a variable
# Value: a list of possible values to assign it
# assignments: (Empty when called)
# Key:... |
52a69c937933a2d1364b778c558c25381ccd4a0c | bhamrick/ai2 | /constraint/queens.py | 916 | 3.640625 | 4 | # Brian Hamrick
# 9/11/08
# N-Queens program using the constraint solver
import sys
from backtracking1 import backtracking
def constraint(row1, col1, row2, col2):
# Precondition: col1 != col2
return col1 != col2 and col1+row1 != col2+row2 and col1-row1 != col2-row2
def disp(n, assignments):
str = ""
for row in r... |
27aa78f76015ea638fd354ee593b45be572c0ca7 | Alejandro-08/Practica_02 | /Ejercicio_03_1.py | 1,071 | 4.40625 | 4 | # Ejercicio_3_1
class Car():
"""Clase tipo coche"""
def __init__(self, make, model, year):
"""Inicializacion de los atributos"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
""" Impr... |
75b568fe645eb6fe0c5e84e5c57c457e85e8236f | ivanesia-Gomes-Costa/Maratona_Python_Bruno_fraga | /Anotacoes_Segundo_dia.py | 721 | 4.09375 | 4 | #-----------------funcões-----------------
def welcome(name):
msg = 'Ola ' + name.title()
print(msg)
welcome('ivanesia gomes costa')
welcome('lucas alberto de souza')
#criando uma função de soma
"""
No exemplo da função abaixo, solicita dois valores, porém se o usuário informar somente um valor, a função ira... |
8afa9c4539297bb6ed2374ca4773f37abfd6754d | reesjones/numerical-analysis | /newton.py | 586 | 3.96875 | 4 | import sys
from math import *
sys.setrecursionlimit(5000)
def newton(f,f2,start,error,iterations):
x = start
previous = x
for z in range(iterations):
x = x-(f(x)/f2(x))
print("x = "+str(x)+" , f(x) = "+str(f(x))+" , error = "+str(x-previous))
if abs(x-previous)<=error:
return x
previous = x
return x
... |
729f6edc65686f2498bcae48a2105dc9f11d43c7 | saicumbulam/Python-for-Algorithms--Data-Structures--and-Interviews | /Algorithm/array/missingNumberinArray.py | 334 | 4.15625 | 4 | '''
1. Get the sum of numbers
total = n*(n+1)/2
2 Subtract all the numbers from sum and
you will get the missing number.
'''
def missingNum(num):
n = len(num)
total = (n+1) * (n+2)/2
for i in num:
total -= i
return int(total)
if __name__ == '__main__':
print(missingNum([1,2,3,5,... |
6319741a1c453fe5e518a44bc62bef024220d217 | saicumbulam/Python-for-Algorithms--Data-Structures--and-Interviews | /Algorithm/randomNumber/GenerteRandomNumList.py | 600 | 3.671875 | 4 | from random import seed
from random import randint
# seed random number generator
seed(1)
class Random:
'''
generate some integers
'''
def __init__(self, total ,low, high):
self.total = total
self.low = low
self.high = high
self.genArray = []
def generate(self):
... |
d2c343b3d8acfa0d1165bb7bf82b0a6decbd0b82 | saicumbulam/Python-for-Algorithms--Data-Structures--and-Interviews | /Algorithm/array/recursive_reverse_array.py | 294 | 4.3125 | 4 | '''Recursive python program to reverse an array '''
def reverse(arr,start,end):
if start >= end:
return
arr[start],arr[end] = arr[end],arr[start]
reverse(arr,start+1,end-1)
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6]
print(reverse(arr,0,2))
print(arr)
|
b7d382dd909fcff3e28ad291eaf01914337fd948 | saicumbulam/Python-for-Algorithms--Data-Structures--and-Interviews | /Algorithm/array/smallest-common-number.py | 1,092 | 4.125 | 4 | class SmallestCommon:
def __init__(self, array1, array2, array3):
self.array1 = array1
self.array2 = array2
self.array3 = array3
def run(self):
i, j, k = 0,0,0
while i < len(self.array1) and j < len(self.array2) and k < len(self.array3):
# Finding the small... |
9502a93fd982971a6a032f3be7547eabf4e035f2 | Thisisnowspam/TaxCalculator | /Tax calculator.py | 1,549 | 3.796875 | 4 | # Made by Joshua Hillis
import re
import time
while True:
global tax
global price
print ("Made by Joshua Hillis")
time.sleep(.5)
tax = input("What is the tax rate we must apply to the item?")
price = input("What's the price of the item?")
tax = float(tax)
price = float(price)
pri... |
925e5fe0c5475bb0f2d1f0ac6020ca5774642c09 | Aegarain/advent-of-code | /Python/2020/day_05.py | 1,669 | 3.703125 | 4 | input_file = open("day_05_example.txt")
input_text = input_file.read()
boarding_passes = input_text.split("\n")
boarding_passes.pop()
highest_ID = 0
def read(pass_text):
row = range(0,128)
column = range(0,8)
for x in range(8):
row_len = int(len(row))
mid = int(row_len/2)
char = pas... |
8a7c29d676904a0194d1d6dc2957c7f0053bd751 | Mau5trakt/PCC | /Semana 2/semana 2/defhour.py | 196 | 3.890625 | 4 | def print_seconds(hours, minutes, seconds):
h = hours * 3600
m = minutes * 60
s = seconds
print(h + m + s)
print_seconds(24, 0, 0)
print_seconds(3, 56, 27)
print_seconds(1, 2, 3) |
d0cbb7f5f6081bb14a4deee7129e4204db08bb07 | Mau5trakt/PCC | /Semana 4/defirstandlast.py | 251 | 3.609375 | 4 | def first_and_last(message):
if not message:
return False
a = (message[0])
b = (message[-1])
return a == b
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
print(first_and_last("enrique")) |
e241da3136803feadd9508b27ec4f012df6ad601 | DLHub-Argonne/dlhub_sdk | /dlhub_sdk/utils/types.py | 3,931 | 3.671875 | 4 | """Utilities for generating descriptions of data types"""
from datetime import datetime, timedelta
from six import string_types
PY_TYPENAME_TO_JSON = {
bool: "boolean",
int: "integer",
float: "float",
complex: "complex",
timedelta: "timedelta",
datetime: "datetime",
str: "string"
# use... |
ada94ff26fda11f4d69b501355a9c8379e6b95fe | arbonap/Data_Structures | /Fraction_Class.py | 500 | 3.78125 | 4 | class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
def __add__(self, otherfraction):
#cross multiply:
newnum = self.num * otherfraction.den + self.den * otherfraction.num
... |
5358173ce5bf9e1af0e7297b58f367198e2e7148 | vinci011235/python | /analise.py | 575 | 3.6875 | 4 | def analise(codigo, tokens, estruturas):
for i in range(0, len(estruturas)):
codigo = codigo.replace(estruturas[i], ' ')
c = codigo.split()
for i in range (0, len(c)):
if not c[i].isdigit():
if not c[i] in tokens:
return 'Erro de Sintaxe: ', c[i]
return '... |
4b0390faa2184c7811c731a06f3dc232938477df | andput/web | /math_const.py | 247 | 3.59375 | 4 | import sys
import math
print "Enter what you whant to see in format <name> : <accuracy>:"
name=sys.argv[1]
tochn=sys.argv[3]
tochn = int(tochn)
if name =='pi':
print round(math.pi,tochn)
if name == 'e':
print round(math.e,tochn)
|
0d34ec990a77f833a94b1a3c2eb88cc2f8c7fb00 | LauraKapitza/learning_projects | /scraping.py | 2,546 | 3.640625 | 4 | import requests
import re
import random
# VARIABLES
word_to_look_for = "Kim Kardashian"
first_url = "https://en.wikipedia.org/wiki/Special:Random"
# Filter all the href with this string
wiki_link = "/wiki/"
# base url of wikipedia, used to build a new link
wiki_url = 'https://en.wikipedia.org'
# keep track of the amo... |
617e28e2c80c0d4b3ba118df147d7b833122b10d | magello-group/machine-learning | /k-means/lab1/kmeans.py | 2,620 | 3.78125 | 4 | import numpy
import cv2
# Read the image which should be processed. It will be stored in memory as
# an array of arrays of arrays. In the case of an image of size 32x32 it will contain
# 32 columns -> 32 Rows -> Pixel [R,B,G]
# Thre images are available, you can raplce them with your own if you want
# img-640x640.jpg... |
8966b609d43d117602df4e2dd93a80fab613d9af | mopugh/SheehyBook | /chapter2/shapes.py | 570 | 3.84375 | 4 | class Polygon:
def __init__(self, sides, points):
self._sides = sides
self._points = list(points)
if len(self._points) != self._sides:
raise ValueError("Wrong number of points.")
def sides(self):
return self._sides
class Triangle(Polygon):
def __init__(self, poi... |
7f7d8c3e553a89ebfaee4f8c3fcb9446479922b3 | JonyHM/Fatecodes | /Lista_2/L2_Questao07.py | 305 | 3.890625 | 4 | print("Lista 2 - Questão 7","\n")
m = float(input("Metros quadrados a serem pintados: "))
lit = m / 3
lat = lit / 18
if m % 3 != 0:
lit = lit + 1
if lit % 18 != 0:
lat = int(lat + 1)
p = lat * 80
print(f"Latas a serem utilizadas: {lat}")
print(f"Preço a ser pago: R${p:.2f}")
|
966d09c2ea516b6a677093498f72809bc6b60937 | JonyHM/Fatecodes | /Lista_2/L2_Questao01.py | 422 | 4.21875 | 4 | print("Lista 2 - Questão 1", "\n")
print("Insira três lados de um trângulo")
a = int(input("1: "))
b = int(input("2: "))
c = int(input("3: "))
if (a + b) < c or (a + c) < b or (b + c) < a:
print("Esta forma não é um triângulo")
elif a == b == c:
print("Este triangulo é equilátero")
elif a == b or a == c or b ... |
9f8806c5f3c0c669095f440ac308beddbe629b30 | JonyHM/Fatecodes | /Lista_1/L1_Questao06.py | 299 | 3.59375 | 4 | print ('Questao 6', '\n')
dist = float (input ('Insira a distancia a ser percorrida (em KM): '))
velo = float (input ('Insira a velocidade media em que espera percorrer este trajeto (em km/h): '))
tempo = dist / velo
print ('Sua viagem tera duracao de aproximadamente %.2f horas' %tempo)
|
f9b9a0175c2d0fa6b00eeba6a52329daab99ad03 | portellabea/python-testing | /forca.py | 1,005 | 4 | 4 | def jogar_forca():
print("********************************")
print("Bem vindo ao jogo de advinhação!")
print("********************************")
palavra_secreta = "banana"
letras_acertadas = ["_", "_", "_", "_", "_", "_"]
enforcou = False
acertou = False
#enquanto não enforcou E o jog... |
5906d7d100e129af8be83c53b940ad9bb028f926 | jmccormack200/ARCAM-Net-Public | /WebInterface/frequencytable.py | 1,000 | 3.671875 | 4 |
class FrequencyTable:
freqs = [900000000, 915000000, 920000000, 2200000000, 2400000000, 2500000000, 5725000000]
current_freq = 0
current_index = 0
def __init__(self):
self.current_index = 0
self.current_freq = self.freqs[self.current_index]
def increase_freq(self):
... |
c5a0013b74e80c0af6e4623a767bd3c78ac8a12d | tmdghks0704/python-practice | /02_container.py | 448 | 3.6875 | 4 | '''a= dict()
a={'이름':'김승환','나이':'23'}#중괄호를 써도 dictionary형이 됨
a=['js']=39
print(a)
a = {'서울':'02', '경기':'031', '제주':'064'}
print(a['제주'])
my_account = {'bank': '우리은행', 'balance': 234, 'pay':100}
print(my_account['bank'])
print(my_account.get('lotto'))#.get을사용함으로써 error를 내지않고 코드가 돌게끔사용
set_a={1,2,3}#set에서는 순서가 없음
s... |
9e263fddf5d3170786cb9b95be4a10ba4fe15866 | aman-ku/Machine-Learning-Algorithms | /Classification/6.KNN/K_nearest_neigbour.py | 1,235 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 22:30:34 2020
@author: amankumar
"""
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
ds=pd.read_csv('Iris.csv')
X=ds.iloc[:,1:5].values
Y=ds.iloc[:,5].values
def distance(x,row):
distcol=np.array([])
... |
3c09bb7f695e96c0eb63e9117546cd911075a3be | OCEAN-Senior/Python_Sariqdev | /14_dars Lug'at/Amalyot.py | 2,242 | 3.609375 | 4 | # MyFamily_name = {
# 'Otam' : 'Otaming ismi Ikramov Botir',
# 'Onam' : 'Onamning ismi Daminova Moxidil',
# 'Ukam' : 'Ukamning ismi Abduvaitov Bunyodxon',
# 'Singlim' : 'Singlimning ismi Abduvaitova Yulduzxon'
# }
# MyFamily_year = {
# 'Otam' : '1973 - yilda, Samarqand viloyatida',
# 'Onam... |
9f4398521a476accb63c7a66812316d62a9e5eb4 | nmaneck/ManeckNumGuessv2 | /main.py | 446 | 3.765625 | 4 | import functions as f
print("Welcome to the Number Guessing Game!")
# See getName function in functions.py
name = f.getName()
# Game plays until program is exited.
while True:
# Plays main game and saves number of guesses
totalGuesses = f.mainGame()
# Checks to see if new high score is set and updates t... |
5fe86b458cdf5c9883d01dc6dcf2d96c4170e28e | snjumaheshwari/Program | /Algo/Graph_1.py | 713 | 3.65625 | 4 |
// BFS ALGORITHM
def BFS(i):
for j in range(1,n+1):
visited[j]=0
parent[j]=-1
q=[]
visited[i]=1
q.append(i)
while(q!=[]):
j=q.pop(0)
for (j,k) in Edge_set:
if (visited[k]==0):
visited[k]=1
parent[k]=j
q.append(k)
def BFS_2(i):
for j in range(1,n+1):
level[j]=-1
parent[j]=-1
q=[]
l... |
4d4e054faf374cf2bbae238eac5098877ebb3fe5 | ccsuehara/30254 | /Machine_Learning/hw4/hw4_cluster.py | 6,569 | 3.734375 | 4 | '''
Augmenting the pipeline for Clustering
Author: Carla Solis
'''
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import seaborn as sns
import matplotlib.pyplot as plt
SEED = 1234
#Step 1: Read the data
def read_data(filename):
'''
Read the data and convert it to a dataframe
... |
266cdb8c87760241b6b781dcc4443722454f0e9b | afcarl/en_corpora_predealer | /tokenizer.py | 1,490 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: largelymfs
# @Date: 2014-09-25 13:33:50
# @Last Modified by: largelymfs
# @Last Modified time: 2014-09-26 15:49:40
import string
import nltk
class Tokenizer:
def __init__(self, lower=True, punctuation=True, digits=True):
self.symbols = string.p... |
5d57b75990b50783ca46725d87671637c042b63c | shubhi1998/Beginner-Python-Programming- | /Course 2: Python Data Structures/Week 3/4.py | 358 | 4.0625 | 4 | name = input("Enter the file name")
try:
fhand = open(name)
except:
print("This file can't be opened")
exit()
lst= list()
for line in fhand:
line = line.rstrip()
words= line.split()
for word in words:
if word not in lst:
lst.append(word)
else:
... |
f1e101109eae0aa5643a7f710dff31710fb68521 | shubhi1998/Beginner-Python-Programming- | /Course 1: Introduction to Python Programming/Week 2/5.py | 133 | 3.84375 | 4 | ctemp = float(input("Enter the temperature in Celsius"))
ftemp = (ctemp*1.8) + 32
print("The temperature in Fahrenheit : ",ftemp)
|
109130e98addb76cb25b734926a45d3067e51b19 | shubhi1998/Beginner-Python-Programming- | /Course 1: Introduction to Python Programming/Week 5/2.py | 314 | 4.1875 | 4 | max = None
min = None
while(True):
num = input("Enter the number :")
if num =="Done":
break
num = int(num)
if max is None or num > max:
max = num
if min is None or num < min:
min = num
print("Done printing")
print("Maximum :",max)
print("Minimum :",min)
|
f4bf39e6d9b180de08c825f176367a1a88c39ed3 | chaderdwins/interview_problems | /Python/gen_fxn.py | 158 | 3.703125 | 4 | def count_up_to(x):
count = 1
while count <= x:
yield count
count +=1
k = count_up_to(10)
k = list(k)
for item in k:
print(item)
|
242d9390973f77feaa67a04e300afa022dee9a2e | chaderdwins/interview_problems | /Python/2-6.py | 2,566 | 4.125 | 4 | # Palindrome
# Implement a function that checks if a linked list is a palindrome
from random import randint as r
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length =... |
77ddbb9b39f2a9330017b5147485add7d728a9d1 | chaderdwins/interview_problems | /Python/Linked Lists/singly_linked.py | 2,894 | 3.9375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def append(self, data):
node = Node(data)
if not self.head:
self.head = node
... |
7b9110c859f69d0a009db98f7ad2914b79164d5b | chaderdwins/interview_problems | /Python/2-5.py | 3,256 | 3.921875 | 4 | # Sum Lists
# You have two numbers represented by a linked list, where each node contains a single
# dialt. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a
# function that adds the two numbers and returns the sum as a linked list
# EXAMPLE
# Input: (7-> 1->6) + (5-> 9... |
cc339365c69be3ae48594a3ba59a59ddef974e9e | chaderdwins/interview_problems | /Python/l-3.py | 970 | 3.8125 | 4 | # Given a string, find the length of the longest substring without repeating characters.
# Example 1:
# Input: "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
# Example 2:
# Input: "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
# Example 3:
# Input: "pwwk... |
2cb810fa42e145bc8359b7540a8d0bdc6296ff46 | chaderdwins/interview_problems | /Python/l2.py | 942 | 4.15625 | 4 | # Given a 32-bit signed integer, reverse digits of an integer.
#
# Example 1:
#
# Input: 123
# Output: 321
# Example 2:
#
# Input: -123
# Output: -321
# Example 3:
#
# Input: 120
# Output: 21
# Note:
# Assume we are dealing with an environment which could only store integers within
# the 32-bit signed integer range: [−... |
30cb71e00c863c26b5620fe2a7627f0ae5a4c6b1 | chaderdwins/interview_problems | /Python/2-4.py | 3,079 | 4.03125 | 4 | # Partition
# Write code to partition a linked list around a value x, such that all nodes less than x co
# before all nodes greater than or equal to x If x is contained within the list, the values of x only n
# to be after the elements less than x is below). The partition element x can appear anywhere in the
# right pa... |
23e800a936aeb1645448d18714c1267259837cfa | chaderdwins/interview_problems | /Python/c-25.py | 538 | 4.0625 | 4 | # Write a function called find_greater_numbers which accepts
# a list and returns the number of times a number is followed by a larger
# number across the entire list.
'''
find_greater_numbers([1,2,3]) # 3
find_greater_numbers([6,1,2,7]) # 4
find_greater_numbers([5,4,3,2,1]) # 0
find_greater_numbers([]) # 0
'''
def fi... |
b4a1acc3782b8294886de78ab8af4ab3e1447122 | chaderdwins/interview_problems | /Python/frequency_count.py | 473 | 3.734375 | 4 | # write a fxn called same which accepts two arrays
# the function should return true if every value in
# the array has it's corresponding value squared
# in the second array. frequency must match.
#
def frequency(x,y):
if len(x) != len(y):
return False
for i in range(len(x)):
x[i] = x[i]**2
... |
85e7b1bab0be06e6ea9b889b5c6d79f1f7fb9eb0 | chaderdwins/interview_problems | /Python/csv_file.py | 578 | 3.8125 | 4 | from csv import reader
from csv import DictReader
# with open("data.csv") as file:
# my_csv = reader(file)#yields iterator object
# next(my_csv)#skips the headers
# for item in my_csv:
# print(f"On {item[0]} at {item[1]} the {item[4]} will begin. It is a {item[7]}.")
with open("data.csv") as file:... |
85d97fc07d8603ce76cfc401602ed12a0dba6cf5 | jgooding7346/projects | /PiCam/piCamValidate.py | 511 | 3.71875 | 4 | import time,picamera
picFine = False
while picFine != True:
filename = input("What is your name? ")
with picamera.PiCamera() as camera:
camera.start_preview()
time.sleep(2)
camera.capture(filename+".jpg")
camera.stop_preview()
print('Captured %s' % filename)
picFineIn... |
3c25d8393bf319108b8082853cc89408d9b1ed79 | jenserek/text-adventure-game | /FirstGame/gamelib/Controller.py | 7,571 | 3.75 | 4 | from itertools import chain
class Controller():
def __init__(self, story, player):
story.controller = self
self.story = story
self.player = player
self.actions = {
"show_stats": "show_stats",
"stats": "show_stats",
"stat": "show_stats",
... |
355da1ccec21e986fca16b091bee6ae9ef308967 | jaimemarijke/project-euler-solutions | /project_euler/problem1.py | 967 | 4.1875 | 4 | # Multiples of 3 and 5
# https://projecteuler.net/problem=1
# 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.
# Find the sum of all the multiples of 3 or 5 below 1000.
from functools import partial
import itertools
def _is_multiple_... |
62a8f0283b2d3bba7a7ca0d381f1fd353fbc9145 | alanacca/Algoritmos-de-Ordenacao | /Quicksort.py | 569 | 3.8125 | 4 | def Quicksort(alist,comeco,fim):
posPivo = 0
if(comeco<fim):
posPivo = partir(alist,comeco,fim)
Quicksort(alist,comeco,posPivo-1)
Quicksort(alist,posPivo+1,fim)
def partir(alist,comeco,fim):
pivo = alist[comeco]
c = comeco+1
f = fim
while(c <= f):
if (alist[c] <= pivo):
c += 1
elif (pivo < alist[... |
a7efb87aff30e8ab8521e6e805d347e7f83b1ce3 | exxxar/python | /оценки и лабы других/бурцев/lab1/lab1/14.py | 212 | 3.6875 | 4 | mystr="bla bla lalalal on ku rok"
print mystr
i=0
for el in mystr:
for eltwo in mystr:
if(el==eltwo):
i+=1
if(i==2):
break
if(i==1):
print el
i=0
|
f913d607278d476fd53c244de06ba9eb994e5428 | exxxar/python | /lab1/l1_3.py | 720 | 3.609375 | 4 | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
def format(x):
x = str(x)
if (len(x)<2):
x = str(x+"0")
return x
money = 0
real = 0
coins = 0
while True:
try:
... |
59bad584b7cf2db77ec62cb6883b06b7aa3395a3 | Captain-Seli/Data-Mining-Projects | /Assignment 1/dm.py | 1,710 | 3.9375 | 4 | # """ * Create a Python module with a __main__ , and at least 100 lines of code. You should use
# if __name__ == "__main__":
# * Define at least 1 class, and at least 1 function for each class you have defined. Your __main__ should instantiate objects of the classes you have designed, and use them to invoke the m... |
f7c7e0bd4183a7ae62446886445f8026a4be12e1 | A01748151/Mision-02 | /coordenadas.py | 597 | 4.1875 | 4 | # Autor: Alberto Contreras Torres, A01748151
# Descripcion: Texto que describe en pocas palabras el problema que estás resolviendo.
Escribe un programa que calcula la distancia entre dos puntos.
• El programa le pregunta al usuario las coordenadas (x1, y1) del primer punto y, también, las coordenadas (x2, y2) del segu... |
2662256b17c25f04c3c62d7d76c8d541b6d2e220 | Colorsublime/Colorsublime-Plugin | /colorsublime/asynclib.py | 2,078 | 3.5625 | 4 | """
Decorator to run functions asynchronously.
"""
import traceback
from .lib.concurrent import futures
from . import logger
from . import settings
log = logger.get(__name__)
asyncPool = futures.ThreadPoolExecutor(max_workers=10)
def _is_function(fn):
return hasattr(fn, '__call__')
def runasync(fn):
""" Dec... |
8d27b19e6122db10c1a44cd64b1424058f520b2c | feamon/Nginx-Consul-Api | /nginx_platform_backend/libs/basic_function.py | 483 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
def checkIp(ip):
"""
验证IP是否合法
:param ip:
:return:
"""
rule = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
if rule.match(ip):
return True
else:
return False
def checkPort(port)... |
801dc0c8f2ec3eb5cac4c908b35d670b98e241ac | shio408/AtCoderBeginnerContest-practice | /question02.py | 97 | 3.546875 | 4 | import sys
a, b = list(map(int, input().split()))
x = 'Even' if (a*b)%2==0 else 'Odd'
print(x) |
1351ee01ed0aed78e535c2002bd664ff8409ab80 | shio408/AtCoderBeginnerContest-practice | /question17.py | 76 | 3.625 | 4 | import sys
word = input()
print(word[0] + str(len(word[1:-1])) + word[-1]) |
a1fafed7f30ec880b999ebdc08a264f99506a202 | jncraton/nfa | /nfa/nfa.py | 17,464 | 3.84375 | 4 | from string import ascii_lowercase as lower, digits
from IPython.display import display_html
import graphviz
class NFA:
"""
Implements a nondeterministic finite automaton
This can used for DFAs as well becuase a DFA is just a special case
of an NFA.
"""
def __init__(self, transitions, F=None, q0=None)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.