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 |
|---|---|---|---|---|---|---|
bca165cc099088514f3e5e213db997d140c5b02d | nandoow/Trabalho-1 | /telasistema.py | 441 | 3.59375 | 4 |
class TelaSistema():
def __init__(self):
pass
def tela_opcoes(self):
print('-----POSTO DE VACINAÇÃO-----')
print('ESCOLHA O NÚMERO DA OPERAÇÃO QUE DESEJA REALIZAR')
print('1 - Cadastrar posto de vacinação')
print('2 - Gerenciar posto de vacinação')
print('3 ... |
79e1bb80416c14cc90604d7d644d762c20bc4195 | ProfessorRex/Safari-Zone-Research | /venoseasect verifier.py | 33,408 | 3.625 | 4 | import math
import concurrent.futures
import time
'''
PLEASE DON'T JUDGE LAZY CODE
this is just for fun <3
'''
def calculate_catch_rate(rate, rock=False, bait=False):
'''Can only accept EITHER balls OR Rocks
The FRLG games use a fairly odd catch formula
the catch rate of a pokemon is modif... |
19d288a50626dff442678f9c1bf5d5df85b29e7d | alanzhchou/python_spider_learning | /basic_learning/python_basic_and_socket/python_more_details/GUI/file4.py | 899 | 4.09375 | 4 | #/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
这个文件用来测试python的多线程功能
'''
import threading
from time import ctime,sleep
def eating(food):
for i in range(2):
print("我在吃%s...好好吃%s"%(food,ctime()))
sleep(1)
def playing(game):
for i in range(2):
print("我在玩%s...没代码好玩!%s"%(ga... |
c7e1aca5b81f3fa640725649c1b3adf041b011c7 | apoorva-19/Advent-of-code | /day6.py | 740 | 3.5 | 4 | # base_set = set(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'])
def count_combi(customs_form):
total = 0
for form in customs_form:
# print(len(form))
total += len(form)-1
return total
inputs=[]
new_set = set()
b_set = set()
with op... |
da66526dcd76a1e2f31cfb9b6271d07ce99ba531 | gengfo/Python | /e-PythonBianChengKuaiSuShangShou/ch7/P7001.py | 382 | 3.921875 | 4 |
def isPhoneNumber(text):
if len(text) != 12:
return False
text = "abc"
print "length is", len(text)
"""
for i in range(0,3):
print str.isdigit(text[i])
if not str.isdigit(text[i]):
return False
for i in range(4,7):
print str.isdigit(text[i])
if not str.isdig... |
cf377f2962bd65b16947b3bed89aa939afec77f8 | Gutjak/PDG_Project | /main.py | 10,459 | 3.640625 | 4 | import pygame
import sys
import constants
import random
import math
import time
# Add Title and Icon to window
pygame.display.set_caption("PDG Project")
icon = pygame.image.load('data/maze.png')
pygame.display.set_icon(icon)
#Define parameters for tiles
class Tile:
def __init__(self, block_path, visited):
... |
2daaf603cec27d4151c88ed56e74501905a66285 | zhangwuxin/my_project | /pandas/shujuzhen.py | 631 | 3.515625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:张印
# datetime:2019/6/10 22:53
# software: PyCharm
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print (df)
data = [['Alex',10],['Bob',22],['Ajax',22]]
df = pd.DataFrame(data,columns=['name','age'],dtype=float)
print (df)
data = {'name':['Tom','Jac... |
c0fdef37d40a0266ca0c111ea771051a175554d6 | zhangwuxin/my_project | /project/xiecheng/xiecheng.py | 1,006 | 3.796875 | 4 | from collections import deque
def sayhello(n):
while n>0:
print('hello~',n)
yield n
n-=1
print('say hello')
def sayhi(n):
x=0
while x<n:
print('hi~',x)
yield
x+=1
print('say hi')
class TaskScheduler(object):
def __init__(self):
self._tas... |
c71cfa4b71b41280b03f0af63aab9afeabef0ccb | Kshitiz14/Rock-Paper-Scissor-Game | /code.py | 746 | 3.859375 | 4 | import sys
player1 = str(input("Plyaer 1: Choose Rock/Paper/Scissor.").lower())
player2 = str(input("Player 2: Choose Rock/Paper/Scissor.").lower())
def compare(p1, p2):
if p1==p2:
return("The game is tie.")
elif p1=='rock':
if p2=='paper':
return("Player 2 wins.")
else:
... |
d7ecd3891a41475d2035c0bc21850d9248746d5d | jfearnow/gold_challenges | /challenge_3/outing.py | 774 | 3.78125 | 4 | '''
Here are the parts of an outing:
Event Type:
Golf, Bowling, Amusement Park, Concert
Number of people that attended,
Date,
Total cost per person for the event,
Total cost for the event
'''
class Outing:
def __init__(self, event_type, people_attending, date, cost_per_person):
self.event_type = ... |
e02be49d885d049f820771a4cd6ee1b3c045453d | lsrichert/LearnPython | /ex3.py | 2,909 | 4.65625 | 5 | # + plus does addition
# - minus does subtraction
# / slash does division
# * asterisk does multiplication
# % percent is the modulus; this is the remainder after dividing one number
# into another i.e. 3 % 2 is 1 because 2 goes into 3 once with 1 left over
# < less-than
# > greater-than
# <= less-than-equal
# >= great... |
aee68143c97d6270a84fd0ed6f1607338594294a | adamrossnelson/crossreg | /corrhandPy.py | 2,197 | 3.71875 | 4 | # Fall 2017 - Adam Ross Nelson - Modified for python draft.
# Fall 2015 - Adam Ross Nelson - Originally exectued in Stata.
# - See: https:github.com/adamrossnelson/crossreg/blob/master/corrhandStata.do
# Maintained at: https:github.com/adamrossnelson/crossreg
# Use this py file to calculate the correlation w... |
d2f009723da32d1593ae09fb8bd529f59dac34bd | Jamin2018/Python_improve_training | /第3章:迭代器与生成器/3-3如何使用生成器函数实现可迭代对象.py | 772 | 4.09375 | 4 | # -*- coding:utf-8 -*-
'''
实现一个可迭代对象的类,它能迭代出给定范围内所有素数:
pn = PrimeNumbers(1,30)
for k in pn:
print k
输出结果:
2 3 5 7 11 13 17 19 23 29
'''
'''
解决方案:将该类的 __iter__ 方法实现成生成器函数,每次yield返回一个素数.
'''
class PrimeNumbers:
def __init__(self,start,end):
self.start = start
self.end = end
def isPrimeNum... |
c1d23b401a7b69e9f816791f45e32542da78af60 | Jamin2018/Python_improve_training | /第4章:字符串处理/4-6如何去掉字符串中不需要的字符.py | 982 | 3.734375 | 4 | # -*- coding:utf-8 -*-
'''
1.过滤掉用户输入中前后多余的空白字符:
' nick2018@qq.com '
2.过滤某windows下编辑文本中的'\r':
'hello world\r\n'
'''
'''
方法一:字符串strip(),lstrip(),rstrip()方法去掉字符串两端字符
方法二:删除行单个固定位置的字符,可以使用切片 + 拼接的方法
方法三:字符串的replace()方法或正则表达式re.sub()删除任意位置字符
方法四:字符串translate()方法,可以同时删除多种不用的字符
'''
# 方法一
s = ' nick2018 @qq.com ... |
91a1d63c30889fa76552173c6cdc1d89f8bdc907 | paulormart/hands-on-python | /performance/lists_optimization.py | 2,718 | 3.625 | 4 | '''****************************************************
File: lists_optimization.py
Author: (c) Paulo Martins
Date: 20130828
Desc: best method to return first value from a list of tuples
version: 1.0
Change Log:
****************************************************'''
import random
import s... |
a0aff6ea7d696b27594019f2bc9207ef5f875291 | jaindinkar/PoC-1-RiceUniversity-Sols | /Homework1/Q10-sol.py | 2,161 | 4.25 | 4 | class BankAccount:
""" Class definition modeling the behavior of a simple bank account """
def __init__(self, initial_balance):
"""Creates an account with the given balance."""
self.balance = initial_balance
self.fees = 0
def deposit(self, amount):
"""Deposits the amount in... |
36c7857bf6cb4087456e70307643515040ae8352 | phoenix14113/TheaterProject2 | /main.py | 2,029 | 4.3125 | 4 |
import functions
theater = functions.createTheater(False)
NumberOfColumns = len(theater)
NumberOfRows = len(theater[0])
while True:
# print the menu
print("\n\n\n\n")
print("This is the menus.\nEnter the number for the option you would like.\n")
print("1. Print theater layout.")
print("2. Purch... |
321119619bc2f755b2d1355fee2e799c8002c7a4 | alexandresampaio/_Exercicios_OO_ | /quadrado.py | 648 | 3.515625 | 4 | #-*-coding:utf-8-*-s
#2) Crie uma classe que modele um quadrado e permita definir,
#alterar e consultar o tamanho dos lados e obter a área.
class Quadrado(object):
def __init__(self, lado):
self._validar_lado(lado)
self._lado = lado
def alterar_lado(self, novo_lado):
self._valida... |
8bb6905d87394ff654ca4669064f85c91592ea95 | gewl/Exercisms | /python/clock/clock.py | 1,245 | 3.875 | 4 | class Clock(object):
def __init__(self, raw_hours, raw_minutes):
hours = str((raw_hours + raw_minutes/60) % 24)
if len( hours ) == 1:
hours = "0" + hours
self.hours = hours
minutes = str(raw_minutes % 60)
if len( minutes ) == 1:
minutes = "0" + minute... |
ca821a61195a739c50d3d2f4d49f93dff6c40b4f | gewl/Exercisms | /python/difference-of-squares/difference_of_squares.py | 265 | 3.859375 | 4 | import math
def difference(n):
return square_of_sum(n) - sum_of_squares(n)
def square_of_sum(n):
sum = (n * (n+1))/2
return math.pow(sum, 2)
def sum_of_squares(n):
sum = 0
for x in range (0, n+1):
sum += math.pow(x, 2)
return sum
|
0c7ed98332f0f07c55174b0937306a2548e976e4 | paulamib123/PP-lab | /pp-lab-3/pp-lab-3-part1.py | 216 | 4.09375 | 4 | ch = input("Enter data: ")
if ch[0].isdigit():
print("Entered data is a digit")
elif ch[0].isupper():
print("Entered data is alphabet in uppercase")
else:
print("Entered data is alphabet in lowercase")
|
62afdcab985a112efa6cc65401bdd209138263e9 | manjulive89/Kitscan | /PROJECT/Server/Utilities.py | 339 | 3.6875 | 4 | ### ###
# Useful methods #
### ###
###############################
# Convert a tuple into a list #
###############################
def convertTupleToList(p_tuple) :
string = str(p_tuple)
string = string.replace("L,", "")
string = string.replace("(", "")
string = string.replace(")", "")
return... |
35d10f22db12794d8e733ea8a66e8bfafa85e605 | AbhiniveshP/Hashing-1 | /WordPattern.py | 1,628 | 3.796875 | 4 | class WordPattern(object):
'''
Solution:
1. Map each character in pattern to each string in list of strings in the same order and vice versa using
another hashMap.
2. While updating each HashMap, if a false mapping exists in any hashMap at any point of iteration, return False.
... |
9f9dbbe4f9ce14485c8e2e0adc9ee5b9399e5c12 | brandon438/even.odd | /even.odd.py | 107 | 4.25 | 4 | num = int(input("Enter Number: "))
if num%2 == 0:
print(f'{num} is even')
else:
print(f'{num} is odd')
|
484d812b212e9e25880140a859dba82e73713911 | yngtodd/eleven | /eleven/vis/confusion.py | 1,167 | 3.515625 | 4 | import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
def plot_confusion_matrix(confusion, classes, normalize=False, cmap=plt.cm.Reds):
"""Plot a confusion matrix
Args:
confusion: confusion matrix computed by sklearn
class: array of class names
normalize: whether ... |
93fde9817e0a27a819de625a85115b1b2d8a0590 | Mech22/ATM_SYSTEM_Controller | /main.py | 2,003 | 3.703125 | 4 | # ATM Controller
import ATM_HW
import ATM_Bank
pin_no = 0
pin_try = 3
ser_try = 1
ser_no = 0
print("\tWelcome to PYTHON ATM\nInsert Your Debit Card\n")
if(ATM_HW.deb_cd_valid() == True):
while (pin_try != 0):
print("Enter your pin number: ")
pin_no = int(input())
if(ATM_Bank.pin_no_va... |
516d0656dc657d042ea1deddc24439531bca95ef | AlexDimitro0v/Gaussian-Distributions-Package | /distributions/example_code.py | 2,751 | 4.15625 | 4 | from distributions.gaussian_distribution import Gaussian
from distributions.binomial_distribution import Binomial
def main_gaussian():
# initialize two gaussian distributions
gaussian_one = Gaussian(25, 3)
gaussian_two = Gaussian(30, 4)
# initialize a third gaussian distribution reading in a data fil... |
310e922c281c21e619e35a085331d89d4bf010ec | HernanGuzman/TP3-Juzgados | /Juzgados/Colas.py | 661 | 3.65625 | 4 | class Cola:
def __init__(self):
self.cola = []
def vaciar(self):
self.cola.clear()
def encolar(self, elemento):
self.cola.insert(0,elemento)
def __repr__(self):
return str(self.cola)
def desencolar(self):
dato = None
if not self.estaVacia():
dato = self.cola.pop()
return ... |
7abdd7a126efa61b09a83d9007fdb35724844e0c | giladbi/learning-python | /pythgor2.py | 665 | 4 | 4 | """
Pythagorean theorem, which states that in a right-angled triangle,
the sum of squares of the legs of the triangles is equal to the square of the hypotenuse.
Pythagorean triples are any three positive integers a, b and c that such that a² + b² = c².
Here is a program that finds all the Pythagorean triples whose... |
5933eed84205771f8efacb325bdb6cb64e719d9b | Dual-Exhaust/expressiontree | /expressiontree/__init__.py | 18,875 | 3.875 | 4 | import math
# Prints the data for the tree
def printdata(expression):
# Initialize the variable we append output to
output = ''
# Removes any spaces from the input expression
exp = ''.join(expression.split(' '))
# Add infix expression to output (it is just the input we took and removed spaces from)... |
1e3194bfe0fdea87b8baa637ab81541dde4b0d83 | Docusland/python-sort | /src/sort.py | 4,411 | 4.34375 | 4 | """
Coding exercise for IT students.
The target of this script is to store different algorithms that sort an array.
"""
def selection_sort(to_sort: list) -> list:
"""
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order)
from unsorted part and ... |
7e829e6b2d8fa9c1a18c9cc2fe45f229b09b9ab9 | splendie/heroku-telegram-bot | /bot.py | 3,017 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""
This Bot uses the Updater class to handle the bot.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and re... |
802ee9c141832d227bf5da0161cf530f31924786 | allyssnerd/Python-520 | /aula_3/revisao.py | 1,238 | 3.984375 | 4 |
class ContaBancaria:
def __init__(self):
self.saldo = 0
self.rendimento = 0.05
def depositar(self, quantidade):
self.saldo = self.saldo + quantidade
def sacar(self, quantidade):
if self.saldo >= quantidade:
self.saldo = self.saldo - quantidade
retu... |
429b4627202ef18b85b7d088f8972f984d4f872a | NelsonJyostna/Array | /Array_12.py | 1,250 | 4.15625 | 4 | #python array Documentation
#https://docs.python.org/3.1/library/array.html
#See these videos
#https://www.youtube.com/watch?v=6a39OjkCN5I
#https://www.youtube.com/watch?v=phRshQSU-xAar
#import array as ar
#from array import *
#h=ar.array('i',[1,6,5,8,9])
#print(h)
from array import *
h=array('i',[1,6... |
39a043117d0b23a076b249a5a74fb388d80a1f94 | tan60man/Google-IT-Automation-with-Python_CapstoneProject | /changeImage.py | 1,093 | 4.0625 | 4 | #!/usr/bin/env python3
from PIL import Image
import os
import file
'''To change the image file in directory "DIR" from a tiff format to a jpeg format and resize it to 600x400'''
DIR = "supplier-data/images/"
'''Convert the image to jpeg format and resize it to 600x400'''
def convert(img):
im = img.convert("RGB")... |
fc72921d25c4cd864459c6044698ea5f77804654 | Amla63/dictionary | /dict.py | 143 | 4.21875 | 4 | dict={'one':1,'two':2,'three':3}
print(dict)
print(dict['one'])
a=dict.get("one")
for x in dict.keys():
if x==3:
print("three")
|
264a27d7a3a905532f0b866308adfcecd39fdd73 | kinjalpatel27/python_code | /chap10_search_sorting/q10_4.py | 881 | 3.59375 | 4 | import random
import numpy as np
def elementAt(array, idx):
if idx is None:
return None
if idx >= len(array):
return -1
else:
return array[idx]
def sortedSearch(array, elem):
idx = 1
while elementAt(array, idx) != -1 and elementAt(array, idx) < elem:
idx *= 2
... |
9552120097e00f52e09c254e3563367bc7d87d6a | kinjalpatel27/python_code | /chap10_search_sorting/q10_2.py | 1,137 | 3.640625 | 4 | import collections
import numpy as np
def if_anagram(st1, st2):
if len(st1) != len(st2):
return False
if sorted(st1) != sorted(st2):
return False
return True
def sort_arry(arry):
idx1 = 0
arry = sorted(arry)
anag_dict = collections.defaultdict(list)
while idx1 < len(arry... |
2997b8260f6876a99fc0153691ef8ea1feacc631 | kinjalpatel27/python_code | /chap2_linked_list/linked_list.py | 606 | 3.84375 | 4 | class node:
def __init__(self, data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def __repr__(self):
node = self.head.next
nodes = []
while node is not None:
nodes.append(str(node.data))
... |
273c2c0cb615ed409783d7106216a5bdafe8f346 | kinjalpatel27/python_code | /chap1_arrays_string/q1_1.py | 617 | 3.75 | 4 | def is_unique(ip_string):
hashmap = {}
unique = True
for i in range(len(ip_string)):
if ip_string[i] in hashmap:
hashmap[ip_string[i]] += 1
else:
hashmap[ip_string[i]] = 1
for key in hashmap.keys():
if hashmap[key] > 1:
unique = False
... |
96e84269f9c90bba1cc504db71b39d7dd971b497 | kinjalpatel27/python_code | /chap1_arrays_string/q1_4.py | 690 | 3.578125 | 4 | def perm_palnd(ip_string):
hashmap = {}
for i in range(len(ip_string)):
char = ip_string[i].lower()
if char in list(hashmap.keys()):
hashmap[char] += 1
else:
hashmap[char] = 1
odd = 0
for key in hashmap.keys():
if key == " ":
cont... |
abcc8ab5ee2d02acd53001a9c76ab507d18d16b3 | kinjalpatel27/python_code | /chap1_arrays_string/q1_5.py | 750 | 3.578125 | 4 | def one_away(str1, str2):
diff = 0
ind1 = 0
ind2 = 0
if abs(len(str1) -len(str2)) > 1:
return False
first = str1 if len(str1) > len(str2) else str2
sec = str2 if len(str2) > len(str1) else str1
while ind1 < len(first) and ind2 < len(sec):
if first[ind1] != sec[ind2]:
... |
4dd878552e91dc5050f81743f8fab477eaefa9c5 | kinjalpatel27/python_code | /chap4_trees_graphs/q4_3.py | 1,627 | 3.78125 | 4 | import numpy as np
from binarytree import Node, tree
class BinaryNode(Node):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class LinkedListNode:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
... |
468a25a3cddbc00b953d4d5be424f8b5d80a9dcc | MaxHung/instaplode | /tree3.0.py | 331 | 3.546875 | 4 | def init(n):
return [0] * (2**n)
def modify_l(l, i, x):
l[i*2+1] = x
def modify_r(l, i, x):
l[(i+1)*2] = x
lst = init(4)
print lst #prints [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
modify_l(lst,5,10)
print lst #prints[0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,]
modify_r(lst,6,33)
print lst #prints [0,0,0,0,0,0,0,0,0,0,0,1... |
2524d073787734297cfed4c7230172fbcf6e3ebb | MaxHung/instaplode | /fibo.py | 226 | 3.8125 | 4 | def fibo(n):
if n <= 0:
return False
elif n==1:
return 1
elif n==2:
return 1
else:
return (fibo(n-2)+fibo(n-1))
print fibo(5) #This returns 5
print fibo(7) #This returns 7
print fibo(10) #This returns 55 |
fec0f57c126d36435cb9733db4d0983af2aaaa0c | ryanrych/Middle-School | /lawOfCosines.py | 191 | 3.90625 | 4 | import math
while True:
a=float(raw_input('Enter side A'))
b=float(raw_input('Enter side B'))
C=float(raw_input('Enter angle c'))
print 'C=',math.sqrt(a**2+b**2-2*a*b*math.cos(C)) |
4e0c6b7fbee90238ab21018fde6b8fd5f3a0d05f | knoxTIMATE/questiopython3 | /Trial and error stuff/ex8_4.py | 265 | 4.03125 | 4 | fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
print(line.rstrip())
for word in line.split():
if word in lst:
continue
elif word not in lst:
lst.append(word)
print (lst)
|
3399d81698ce88dc96a175b0fdf43b0d4056cc7f | Cyki89/RealTimeTrackingApplication | /user_interface/boxes/info_box.py | 682 | 3.515625 | 4 | import tkinter as tk
from tkinter import simpledialog
class InfoBox(simpledialog.Dialog):
def __init__(self, master, infos):
self.infos = infos
super().__init__(master)
def body(self, master):
for i, info in enumerate(self.infos):
key, value = info.split(';')
t... |
f0c0f767756762b9e746f00444526c15412d0846 | benblaut/cse491-drinkz | /drinkz/load_bulk_data.py | 2,381 | 3.65625 | 4 | """
Module to load in bulk data from text files.
"""
# ^^ the above is a module-level docstring. Try:
#
# import drinkz.load_bulk_data
# help(drinkz.load_bulk_data)
#
import csv # Python csv package
import recipes
import db # import from local package
def loa... |
c203eb173393758bc2872e9121b1c7a52c18be13 | GauravKodmalwar/IBM_Training_Apr2020 | /Day3/databaseOps.py | 665 | 3.5625 | 4 | import sqlite3
try:
conn = sqlite3.connect("MyDB.db")
cursor = conn.cursor()
#cursor.execute("Create table employee (id number, name text,"
# "job text, department text)")
#cursor.execute('insert into employee values'
# '(1, "Python", "Development", "R&D")')
#con... |
2b5afb0c23f01c5cd78462e373b86c2985bc0b81 | tarunna01/Prime-number-check | /Prime number check.py | 271 | 4.15625 | 4 | num = int(input("Enter the number to check for prime"))
mod_counter = 0
for i in range(2, num):
if num % i == 0:
mod_counter += 1
if mod_counter != 0:
print("The given number is not a prime number")
else:
print("The given number is a prime number")
|
bfd09644dc48fca95bbcb7cc513c6345be15d1b4 | judegarcia30/cvx_python101 | /02_integer_float.py | 910 | 4.40625 | 4 | # Integers are whole numbers
# Floats are decimal numbers
num = 3
num_float = 3.14
print(type(num))
print(type(num_float))
# Arithmetic Operators
# Addition: 3 + 2
# Subtraction: 3 - 2
# Multiplication: 3 * 2
# Division: 3 / 2
# Floor Division: 3 // 2
# Exponent: 3 ** 2
# Modulus: ... |
add8fcc6d2c338a540ceae2ab33c08d652687ef5 | judegarcia30/cvx_python101 | /exercises/dictionary_exercise.py | 2,125 | 3.6875 | 4 | # Below are the two lists convert it into the dictionary
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
# Expected output:
# {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
# Merge following two Python dictionaries into one
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty':... |
0e3f7d61c853088014a4c90cca82f09e08b7fc6a | Aphinith/Python101 | /dataTypes/loops.py | 469 | 4.59375 | 5 | # example of for loop
item_list = [1, 2, 3, 4, 5]
# for item in item_list:
# print(item)
# example of while loop
i = 1
# while i < 5:
# print('This is the value of i: {}'.format(i))
# i = i +
# examples of using range
first_range = list(range(0,10))
# print(first_range)
# for x in range(0,20):
# print('test... |
a13c70e010bef70756e9caa7c9f06c21259f22bb | Aphinith/Python101 | /panda_exercises/multi_index.py | 1,068 | 3.65625 | 4 | import numpy as np
import pandas as pd
from numpy.random import randn
# Index levels
outside = ['G1', 'G1', 'G1', 'G2', 'G2', 'G2']
inside = [1, 2, 3, 1, 2, 3]
hier_index = list(zip(outside, inside))
# print(hier_index)
# print('\n')
hier_index = pd.MultiIndex.from_tuples(hier_index)
# print(hier_index)
df = pd.Dat... |
9b75ef791bea94604b2b494ccbf5135fb9dc765b | aichallenge/trueskill | /sample.py | 2,455 | 3.609375 | 4 | #!/usr/bin/env python
from __future__ import print_function
import trueskill,random
# The output of this program should match the output of the TrueSkill
# calculator at:
#
# http://atom.research.microsoft.com/trueskill/rankcalculator.aspx
#
# (Select game mode "custom", create 4 players each on their own team,
# c... |
fb8a4caee78d7255d4c39762416a2b0db842a328 | XavierYu/PythonNote | /Python Tut - Generator & Yield.py | 579 | 4.0625 | 4 | # Python Tutorial- Generator & Yield
# Especially useful for memory sensitive application
in python 2.x, range(3) create a list consumes memory
in python 3.x, range(3) create a generator object that does not have a len(), members are calculated using yield on the fly
EG:
>>> print(next(the_generator)) ... |
65dab460ceec6f58ac8ee6da7caf313cba4fc234 | Nalini2799/Customise_subplots | /subplots.py | 1,214 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 17:39:30 2021
@author: ASUS
"""
#create subplots of multiple plots in one figure
#import pyplot
#open the files in read mode and read lines
# Import the pyplot
import matplotlib.pyplot as plt
f =open('salesdata2.csv','r')
salefile= f.readlines()
#create sales list
sal... |
27c67443cdbd823f25dd6fb7163c35173cfdf423 | zakaleiliffe/IFB104 | /Week Work/Week 4/Building IT Systems/Week04-questions/homework_questions/1_three_the_same.py | 1,128 | 3.96875 | 4 | #---------------------------------------------------------
#
# Three the same
#
# Define a "predicate" function (one that returns True or False)
# with three parameters. The function should return True
# only if all three parameters have the same value.
#
# Comment: This is very easy in Python compared to some older
#... |
f0ec0a36fef58a10d02dae1cb042a156cc0248b2 | zakaleiliffe/IFB104 | /Week Work/Week 3/IFB104-Lecture03-Demos/01-stars_and_stripes.py | 2,566 | 4.3125 | 4 | #---------------------------------------------------------------------
#
# Star and stripes - Demo of functions and modules
#
# To demonstrate how functions can be used to structure code
# and avoid duplication, this program draws the United States
# flag. The U.S. flag has many duplicated elements -
# the repeated st... |
f2ed50358ac9a0e776a08353f5fcb47e43c33416 | zakaleiliffe/IFB104 | /Week Work/week 10/BUilding IT/Questions/2-alert_print_date.py | 2,393 | 4.59375 | 5 | #---------------------------------------------------------
#
# Alert date printer
#
# The following function accepts three positive
# numbers, expected to denote a day, month and year, and
# prints them as a date in the usual format.
#
# However, this function can be misused by providing
# numbers that don't form a val... |
281669198fd194e77dc2380c416d6ffb32d76c68 | zakaleiliffe/IFB104 | /Week Work/Week 4/Building IT Systems/IFB104-Lecture04-Demos/5-keyboard_input.py | 781 | 4.3125 | 4 | # Keyboard input
#
# This short demo highlights the difference between Python's raw_input
# and input functions. Just run this file and respond to the prompts.
text = raw_input('Enter some alphabetic text: ')
print 'You entered "' + text + '" which is of type', type(text)
print
number = raw_input('Enter a number: ')
... |
4c51cbab748aa26bdab3322a4427a9b097672e6b | zakaleiliffe/IFB104 | /Week Work/WEEK 6/Building IT systems/Week06-Questions/1-line_numbering.py | 1,893 | 4.46875 | 4 | #----------------------------------------------------------------
#
# Line numbering
#
# Define a function which accepts one argument, the name of a
# text file and prints the contents of that file line by line.
# Each line must be preceded by the line number. For instance,
# the file 'joke.txt' will be printed as fol... |
0ebc0fa0ed1b48382ef36c87f6aab350e3f02636 | zakaleiliffe/IFB104 | /Week Work/week 2/Building IT systems/demo week 2/IFB104-Lecture02-Demos/3-draw_Pacman.py | 1,257 | 4.4375 | 4 | #---------------------------------------------------------------------
#
# Demonstration - Draw Pacman
#
# As an introduction to drawing using Turtle graphics, here we'll
# draw a picture of the pioneering computer games character, Pacman.
# (Why Pacman? Because he's easy to draw!)
#
# Observation: To keep the code sho... |
05bd4cd46abc7ac340def95d084dde7f997d65e0 | zakaleiliffe/IFB104 | /Week Work/week 2/Building IT systems/week 2 quetions/Week02-questions/Done/3_random_min_and_max.py | 2,344 | 4.4375 | 4 | #------------------------------------------------------------------------#
#
# Minimum and Maximum Random Numbers
#
# In this week's exercises we are using several pre-defined
# functions, as well as character strings and lists. As a simple
# exercise with lists, here you will implement a small program which
# generat... |
1fd51daff7b2075a7371b380abddb323ea3cba72 | zakaleiliffe/IFB104 | /Week Work/Week 3/Week03-questions/DONE/3_stars_and_stripes_reused.py | 1,891 | 4.3125 | 4 | #--------------------------------------------------------------------
#
# Stars and stripes reused
#
# In the lecture demonstration program "stars and stripes" we saw
# how function definitions allowed us to reuse code that drew a
# star and a rectangle (stripe) multiple times to create a copy of
# the United States fl... |
b8acae07aa6e29d555d6cd592f00fa2b49fb3bbc | balintsera/deeplearningaz | /rnn.py | 2,994 | 3.609375 | 4 | # Part 1. data preprocessing
#%%
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#%%
# Importing the training set
dataset_train = pd.read_csv('/work/rnn-dataset/Google_Stock_Price_Train.csv')
training_set = dataset_train.iloc[:, 1:2].values
training_set
#%%
# Feture scaling
from sklearn.preproc... |
689cb7e9c11aedc04d083eadf29b2a1a5521bf10 | anantkaushik/algoexpert | /Binary-Search.py | 581 | 4.1875 | 4 | """
Problem Link: https://www.algoexpert.io/questions/Binary%20Search
Write a function that takes in a sorted array of integers as well as a target integer. The function should use the Binary Search algorithm
to find if the target number is contained in the array and should return its index if it is, otherwise -1.
""... |
95b94e2744fae0f5fc3554f57aa514f980bdbd17 | anantkaushik/algoexpert | /Two-Number-Sum.py | 718 | 4.25 | 4 | """
Problem Link: https://www.algoexpert.io/questions/Two%20Number%20Sum
Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum.
If any two numbers in the input array sum up to the target sum, the function should return them in an array, in sorted order.
If no ... |
2aed5bf0085aa04ef2e70914b24854171372d75e | anantkaushik/algoexpert | /Smallest-Difference.py | 1,103 | 3.921875 | 4 | """
Problem Link: https://www.algoexpert.io/questions/Smallest%20Difference
Write a function that takes in two non-empty arrays of integers. The function should find the pair of numbers (one from the first array,
one from the second array) whose absolute difference is closest to zero. The function should return an ar... |
76e6d52d0b21779500dce7198ab324f66b444f60 | sebastien-blain/BoneAppleTea | /Parser/parser_recipe.py | 691 | 3.5 | 4 | import re
def pa(recipe):
steps = recipe["instructions"]
ingredients_array = re.split('\n', steps)
recipe["instructions"] = ingredients_array
while "" in ingredients_array:
ingredients_array.remove("")
def add_keyword(new_keyword):
file = open("keyword_file.txt", "r+")
... |
ad1815b5fa41d2eda2499c0f152c266884ad70c7 | ksjpswaroop/HackerRank-1 | /Python/Search/median_List.py | 2,363 | 3.90625 | 4 | def insertNumber(array,number):
if not array:
array.append(number)
return
if len(array) == 1:
if number > array[0]:
array.append(number)
else:
array.insert(0,number)
return
si = 0
ei = len(array)-1
binarySearchInsert(array,number,si,ei)... |
72a685a739b26fa104f4496985e96439d0844d08 | jorgecba8989/Lab3Python | /Strings/ejer1-7.py | 441 | 3.96875 | 4 | '''
1.7. Solicitar el ingreso de una clave por teclado y almacenarla en una cadena de
caracteres. Controlar que el string ingresado tenga entre 10 y 20 caracteres para que
sea válido, en caso contrario mostrar un mensaje de error.
'''
clave = input ("Ingresa una clave entre 10 y 20 caracteres: ")
... |
ca75fcf80c218b087d40e37b987161cad2b165bb | jorgecba8989/Lab3Python | /Strings/ejer1-1.py | 314 | 3.90625 | 4 | '''
1.1. Realizar la carga del nombre de una persona y luego mostrar el primer caracter del
nombre y la cantidad de letras que lo componen.
'''
nombre = input("Carga el nombre de una persona: ")
print(f'El nombre comienza con la letra: {nombre[0]} y tiene un tamanio de: {len(nombre)}')
|
b1d1debb8eb36330536d87d0d68c4cde852cff43 | jorgecba8989/Lab3Python | /Listas/ejer2-18.py | 495 | 3.796875 | 4 | '''
2.18. Crear una lista por asignación. La lista tiene que tener 5 elementos. Cada elemento
debe ser una lista, la primera lista tiene que tener un elemento, la segunda dos
elementos, la tercera tres elementos y así sucesivamente. Sumar todos los valores de
las listas.
'''
lis... |
ab7cfd2acc6cf956893a25ddeb9fe71e2657119f | ycyuxin/beginning | /tests/test_operator.py | 594 | 3.640625 | 4 | import unittest
from beginning.operator import slices, cut
class OperatorTestCase(unittest.TestCase):
def test_slices(self):
now = '2018-06-12 11:22:33'
expected = now[0:4], now[5:7], now[8:10], now[11:13], now[14:16], now[17:19]
result = slices[0:4, 5:7, 8:10, 11:13, 14:16, 17:19](now)
... |
30afed88a7b0f98a002d4ec2e2fa51be09900424 | deimelperez/HackerRank | /Problem Solving/Beautiful Days at the Movies.py | 460 | 3.53125 | 4 | import math
import os
import random
import re
import sys
# Complete the beautifulDays function below.
def beautifulDays(i, j, k):
days = range(i, j + 1)
cont = 0
for d in days:
if not (d - int(str(d)[::-1])) % k:
cont += 1
return cont
if __name__ == '__main__':
ijk = input()... |
7ef9ff5f960026ff66275a4486bda174e98b7cc4 | deimelperez/HackerRank | /Problem Solving/Counting Valleys.py | 533 | 3.734375 | 4 | import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(s):
b = True
level = 0
count = 0
for letter in s:
if letter == 'U':
level += 1
else:
level -= 1
if level < 0:
if b:
... |
a344ec9eaf17e5dd96922d6abdefb4a6796d905a | deimelperez/HackerRank | /Problem Solving/Drawing Book.py | 679 | 3.71875 | 4 | import os
import sys
#
# Complete the pageCount function below.
#
def pageCount(n, p):
#
# Write your code here.
#
if p == 1 or p == n or (p == n - 1 and n % 2):
return 0
result1 = 1
for i in range(2, n, 2):
if p in [i, i + 1]:
break
result1 += 1
result... |
bcf1fe75632a822286909ab3fc68b161a23815c9 | BarnabasG/Project_Euler | /amicable_chains(95).py | 1,798 | 3.84375 | 4 | '''
The proper divisors of a number are all the divisors excluding the number itself.
For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these
divisors is equal to 28, we call it a perfect number.
Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper
divisors of ... |
975c387e56c0e68da27fd859c9908f1169307442 | Freddy875/Python | /Numeros/Numeros.py | 1,531 | 4.59375 | 5 | '''
Existen 3 tipos numeircos en Python
int
float
complex
'''
x =1
y = 2.8
z = 1j
print(type(x))
print(type(y))
print(type(z))
#Enteros
print("Enteros")
'''
Los entrsos son todo numero positivo
o negativo sin decimales
de longitud indefinida
'''
x = 1
y = 123456789
z = -987654321
print(x)
print(type(x))
print(y... |
4b3cd2a324ba26d888e2fdf7506cb9250a2508da | Freddy875/Python | /Listas/Acceso_A_Las_Listas.py | 585 | 4.21875 | 4 | #Acceso a la listas
estalista =["manzana","bananas","cereza"]
print(estalista[1])
#Indice negativo
print(estalista[-1])
#Rango de index
estalista =["manzana","bananas","cereza","naranja","kiwi","limon","melon","mango"]
print(estalista[2:5])
print(estalista[:4])
#Esto devuelve los valores del indice 0 al indice 4
... |
231d6754fd2227e76aee3e2d1352231a9e49ff6c | Freddy875/Python | /Introduccion/Diccionarios.py | 2,167 | 4.09375 | 4 | #Diccionarios
#Son otro tipo de coleccion
# donde los elementos tambien se guardan desordenados
# Tienen dos elementos por posicion
# La clave y el valor
# La clave no puede estar duplicada
diccionario = {}
#Esto es un diccionario vacio
print(diccionario)
#Agregar valores a un diccionario
diccionario = {"... |
463b20e3ffb0428dd7f5e73e034ee7b96fcd4ae9 | Freddy875/Python | /Introduccion/AreaYLongitudDeUnCirculo.py | 733 | 4.03125 | 4 | #Ingresar el radio de un circulo
#y reportar su area y la longitud
#de la circuenferencia
#print("Este programa te dice la longitud y area de un ciruclo")
#fRadio = float(input("Ingresa el radio del circulo: "))
#PI = 3.1416
#Declaramos el valor de PI co
#fArea = PI * (fRadio**2)
#fLongitud = 2 * PI * fRadio
... |
f5ba637446b4eab8b78d6529a44764d05a7af847 | Freddy875/Python | /Operadores/OperadoresAritmeticos.py | 541 | 4.125 | 4 | '''
Operadores son usados para desempenio de operaciones con valores y variables
'''
#Operadores artimeticos
x = 5
y = 3
#Suma
print("Suma")
print(x + y)
#Resta
print("Resta")
print(x - y)
#Multiplicacion
print("Multipliacion")
print(x*y)
#Division
x = 12
y = 3
print("Division")
print(x/y)
#Modulos
x = 5
y = 2 ... |
26777d3a822041c22fb7f861b63766dd18a223dd | Freddy875/Python | /Introduccion/Pilas(conListas).py | 509 | 4.1875 | 4 | #Pilas
#Las pilas pueden emularse con Listas
#Las pilas son una estructura de datos
#de tipo LIFO (Last In-First Out)
pila = [1,2,3]
print(f"La pila inicila {pila}")
#Agregar elementos por el final de la pila
pila.append(4)
pila.append(5)
print(f"La pila despues de agregar dos valores {pila}")
#Sacar elementos... |
9e5f03b807c6d4c2084df3bba0266904c42b1c27 | Freddy875/Python | /Pirple/List.py | 702 | 3.78125 | 4 | myUniqueList = []
LeftoverList = []
def appeandElement(element):
flag = False
if element not in myUniqueList:
myUniqueList.append(element)
flag = True
return flag
else:
LeftoverList.append(element)
flag = False
return flag
def messenger(element):
if(app... |
59f519d465be899ce477c316246d63fc014ab226 | bennyhana/RDVelho-Challenge-Two | /dashboard.py | 2,584 | 3.578125 | 4 | import time
from math import sin, cos, radians
from urllib.request import urlopen
data = ((0, 1, 2, 3, 4, 5), (0, 10, 22, 50, 88, 121), (0, 3, 3.5, 5, 8, 10.8))
geoLetters = {0: "N", 45: "NE", 90: "E", 135: "SE", 180: "S", 225: "SW", 270: "W", 315: "NE"}
def drivingCar(power, speed, consumption):
direction =... |
cda12b34911751dae1910693b0001edb57cac3b6 | Sasete/LaxtaniaBank | /SignUp.pyw | 2,373 | 3.59375 | 4 | import tkinter
from tkinter import messagebox
import socket
import sys
host = "laxtaniabank.ddns.net"
port = 7676
def SignUp():
m_email = email.get()
m_username = username.get()
m_password = password.get()
message = 'SignUp/' + m_email + ',' + m_username + ',' + m_password
s = socket.socket... |
256e54d2d6aeffd190c12c4104699f0a3fb64052 | DanDaydy/blacktea | /CPLEX/DOcplex Python Modeling API/DOcplex Scheduling 入门/CP入门 Scheduling/7.状态函数.py | 7,849 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Chapter 7. Using state functions: house building with state incompatibilities
# 这里有两个工人,每个任务需要两个工人中的一个。 一部分任务要求房子打扫干净,而其他任务则使房子变脏。 需要一个过渡时间才能将房屋的状态从脏到干净。
# Problem to be solved
#
# 问题在于,以计划满足时间约束并使表达式最小化的方式,将开始日期分配给一组任务。 此问题的目的是最大程度地减少总的完成日期。
#
# 对于房屋建筑项目中的每种任务类型,下表显示了以天为单... |
a2c8dbb155f2f7cbeceeff0208d053dd5e158131 | colo6299/super-octo-enigma | /HW6/rna_transcription.py | 740 | 3.75 | 4 | """
Good inputs: 'ACGTCCCGTAGCAACATTAACCCTG', 'agctaatcccgagt', 'GATTACA'
Bad inputs: 25, 'f', 'ACGTCCCGTAGCAACATTAACCCTG', 'aCGTCCCGtAGCaACAtTAACCcTG', 'ACG7CCCGTA23CAACAT]AACCCTG'
Edge cases: '', 'a',
"""
# NOTE: what's with exercism? All the good stuff is locked up >:/
def rna_transcription(dna_string: str):
... |
c6022748093254c40e75549962454823ba1b501b | trishamrkt/heapsort | /heapsort.py | 2,156 | 4.0625 | 4 | import math
# Prints values of an array
def print_array(arr):
string = ""
for num in arr:
string += str(num) + " "
print string
def bubble_down(arr, i):
# Base Cases:
# 1. Reached end of tree
# 2. arr[i] > arr[child nodes]
#1. index of child nodes > max index of array
if 2... |
1e13ac183a87e7adc0f7bb7b50f1892c3d38f669 | Sheenazz/pythonlessons | /slice-and-splice/lessons.py | 444 | 3.78125 | 4 | def copiedArray(firstArray, secondArray, toInsertIndex):
print(firstArray[1:toInsertIndex])
firstArray[toInsertIndex:toInsertIndex] = secondArray
return firstArray
# for index, secondArrayElement in enumerate(secondArray):
# firstArray.insert(toInsertIndex+index, secondArrayElement)
# return... |
c02181a9f0462eab2d12230e5519a5c2b9ba572a | Sheenazz/pythonlessons | /title-case-a-sentence/lessons2.py | 345 | 3.5 | 4 | sentence = "HERE IS MY HANDLE HERE IS MY SPOUT"
def capitalizeFirstLetter(supersentence):
wordsArray = sentence.split()
finalCapitalizedLetter = []
for index, word in enumerate(wordsArray):
finalCapitalizedLetter.append(word.capitalize())
return " ".join(finalCapitalizedLetter)
print (capitali... |
8c5cb2887b2d96d280544be32fd77852f679d270 | JEOO2327/calculator | /adder.py | 171 | 3.96875 | 4 |
a=int(input("Input 1st number:"))
b=int(input("Input 2nd number:" ))
print(a,'+',b,'=',a+b)
print(a,'-',b,'=',a-b)
print(a,'*',b,'=',a*b)
if b != 0;
print(a'/'b'='a/b)
|
3993611aefc744ba2e767b742a923fd351653815 | gchwalik/advent_of_code | /day1/solution.py | 1,580 | 4.09375 | 4 | from functools import reduce
from typing import List, Tuple
GOAL_NUM = 2020
def get_input(filename: str) -> List[int]:
"""Returns contents of filename as list of ints"""
with open(filename, "r") as fh:
lines = fh.readlines()
return [int(x.strip()) for x in lines]
def sum(nums: List[int]) -> in... |
5065666f4a53942579809f927f1b70e90445328b | jjfllr/MTGOScrapper | /Classes/Deck.py | 680 | 3.546875 | 4 | class Deck:
pilot = ""
score = ""
mainboard = []
sideboard = []
def __init__(self, pilot="", score="", mainboard=[], sideboard=[]):
self.pilot = pilot
self.score = score
self.mainboard = mainboard
self.sideboard = sideboard
def display(self):
print("pilo... |
c4d49ba491e26da695784818594f1ca97c224d08 | huobingli/pyAlgorithm | /binsearch.py | 452 | 3.859375 | 4 | def bin_search(items, key):
"""折半查找"""
start, end = 0, len(items) - 1
while start <= end:
mid = (start + end) // 2
if key > items[mid]:
start = mid + 1
elif key < items[mid]:
end = mid - 1
else:
return mid
return -1
def main():
ite... |
e75a8fb7eb01d39e13c2b3f7365ce8d21be9e689 | dibery/UVa | /vol120/12024.py | 256 | 3.6875 | 4 | from math import factorial as fact
for t in range( int( input() ) ):
n, ans = int( input() ), 0
for i in range( n + 1 ):
ans += fact( n ) / fact( i ) // fact( n - i ) * ( -1 ) ** i * fact( n - i )
print( '%d/%d' % ( ans, fact( n ) ) )
|
adbe5bffb8299c851409a9ff670d5c203969db76 | dibery/UVa | /vol131/13178.py | 87 | 3.84375 | 4 | for t in range( int( input() ) ):
print( 'NO' if int( input() ) % 3 == 1 else 'YES' )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.