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 |
|---|---|---|---|---|---|---|
403458aa24b81b8c8b78980f506b6e67d11e0515 | hoon4233/Algo-study | /2020_summer/2020_07_22/1922_JJ.py | 652 | 3.546875 | 4 | from heapq import *
#집합 대표 찾기
def find(a):
if parent[a] == a:
return a
else :
return find(parent[a])
def merge(a,b):
a_p = find(a)
b_p = find(b)
parent[a_p] = b_p
#입력
n = int(input())
m = int(input())
valid_edge = 0
parent = [ i for i in range(n)]
edge = []
total_cost = 0
for _ in... |
52eb3496608487777d1687b66cdc58e202fee7e6 | cdoorenweerd/seqselector | /seqselector.py | 1,928 | 3.796875 | 4 | #/usr/bin/env python
#Camiel Doorenweerd 2018
import csv
import argparse
from Bio import SeqIO
parser = argparse.ArgumentParser(description="Select a subset of sequences from a FASTA file using a csv file with a list of target sample names.")
parser.add_argument("-i", "--fastainput", metavar="", required=True,
... |
b85fa031bc98d742db21ab6c581822477de3b119 | MyCloudream/python_test | /numpy_demo/Test03.py | 299 | 3.703125 | 4 | import numpy as np
a = np.array([
[1, 2],
[3, 4]
])
b = np.array([
[5, 6],
[7, 8]
])
'''
对应位置元素相乘,结果为:
[[ 5 12]
[21 32]]
'''
print(a * b)
'''
矩阵相乘,结果为:
[[19 22]
[43 50]]
'''
print(a.dot(b))
# 矩阵相乘,同上
print(np.dot(a, b))
|
64f403486709bb9b9aea41424466d4b212e3fdcc | Roshanbhuvad/Peewee--Python-MySQLite | /Insert_table/single_instance.py | 769 | 3.640625 | 4 | import peewee
import datetime
#the example shows how to retrieve a single instance(Table data according to table colums name) in two ways
db = peewee.SqliteDatabase('test2.db')
class Note(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default=datetime.date.today)
class Meta:
database = db
... |
90f9d7d4a2924d6160a86aac897931fc26d1d01c | Roshanbhuvad/Peewee--Python-MySQLite | /Insert_table/one2many.py | 968 | 3.78125 | 4 | import peewee
import datetime
db = peewee.SqliteDatabase('test.db')
#In the example we define two models that map to the tables. Then we select a customer and show his reservations.
class Customer(peewee.Model):
name = peewee.TextField()
class Meta:
database = db
db_table = 'customers'
cla... |
b322b1b2bbd8242c539e9740568605e35c50054f | mrar3007/lessons_on_python | /codewars/701.py | 810 | 3.671875 | 4 | '''def Xbonacci(signature,n):
#your code here
l = len(signature)
if n >= l:
for i in range(l, n):
signature.append(sum(signature[-l:]))
return signature
return signature[:n]
print(Xbonacci([1,0,0,0,0,0,0,0,0,0],20))'''
def order_weight(s):
mass = []
arr = [[int(j) ... |
b585541533e8c82d7bb2c7b761ae432f8e5f546c | mrar3007/lessons_on_python | /codewars/1501.py | 474 | 3.71875 | 4 | '''def proper_fractions(n):
count = 0
for i in range(1, n):
arr = [j for j in range(2, i+1) if i % j == 0 and n % j == 0]
if len(arr) == 0:
count += 1
return count
'''
def proper_fractions(n):
phi = n > 1 and n
for p in range(2, int(n ** .5) + 1):
if not n % p:
... |
997c19ccf4dd24a5e7c966191f50d4444d4b79b3 | WangyuanhaoNB/ECE364 | /Lab03/.svn/text-base/simpleTasks.py.svn-base | 4,761 | 3.515625 | 4 | #! /usr/bin/env python3.4
#Nithin Varadharajan ECE 364 Fall 2017
#Problem 1
def find(pattern):
with open('sequence.txt', 'r') as myFile:
content = myFile.read()
result = []
for num in range(len(content)):
test=True
patterntest=""
if((len(content)-num) ... |
c0dd7650ce48ea315594e1bfd0ad5e7e6138e090 | coldrecd/theproj | /calc.py | 285 | 3.546875 | 4 | import sys
x = []
for line in open(sys.argv[1]):
num = int(line)
x.append(num)
avg = sum(x) / float(len(x))
diffs = []
for num in x:
diff = num - avg
diffs.append(diff**2)
print 'average is', sum(x) / float(len(x))
print 'sumsqdiffs is', sum(diffs)
print "hello world" |
0396867a1a1e8076b83cf7017a6530cfab3c9dc1 | njuro/advent-of-code-2017 | /day17/spinlock.py | 574 | 3.5 | 4 | '''
https://adventofcode.com/2017/day/17
'''
def spinlock(part2=False):
answer, position, size, step = 0, 0, 1, 370
buffer = [0]
max_val = 50 * 10 ** 6 if part2 else 2017
for i in range(1, max_val + 1):
position = (position + step) % size + 1
if part2:
if position == 1:
... |
9ccb15a04374058ac63ef983242cd2191a3414fe | eskra/Jarvis | /addToDictionary.py | 572 | 3.640625 | 4 | #!/usr/bin/python
import json
while True:
f = open('data.txt', 'r')
# decode the file
data = json.loads(f.read().replace("\'",'"'))
user_input_word = raw_input("Hi, what word would you like to know about?")
if user_input_word in data.keys():
print data[user_input_word]
continue
user_input_definition = r... |
9aee72eb4c98c67456d8162c56c140f536e2a760 | joostpieters/Internshala-Python-Training | /fibrecu.py | 254 | 3.984375 | 4 | def fib(n):
if(n<=1):
return n
else:
return(fib(n-1)+fib(n-2))
num=int(input("enter the no.of terms"))
if(num<=0):
print("enter a positive number")
else:
for i in range(0,num):
print(fib(i))
|
946b30d4292a7de195920b9d7a3bf36f079e5594 | concealedtea/Coding-Interview-Prep | /Hard/0297_Serialize_Deserialize_BTree.py | 971 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
80d1e4ebcf64112fdadff8fa4eca7a2e23709450 | concealedtea/Coding-Interview-Prep | /Easy/0111_Minimum_Depth_Binary_Tree.py | 692 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
... |
3d954967ff1dc06514a488a26411b6e1e1692bfd | Schmidty88/Lab1 | /Source/File5.py | 5,278 | 3.75 | 4 | class Occupant:
def __init__(self, name, phone_number, cell_phone_number, rooms, people, in_date, Days, Rooms):
self.guest_name=name
self.user_phone = phone_number
self.ID = cell_phone_number
self.amount_of_rooms = rooms
self.party_size = people
self.check_in = in_dat... |
a92651738e0155aa3e10ff912de900eb1157fb09 | StephenClarkApps/AdventOfCode2018 | /day_one/bad_solution.py | 2,017 | 3.78125 | 4 | # Advent of Code - Day One
#
# Haven't really optimized the efficiency of this approach, so, yeah :/
import operator
import re
import sys
frequency_cache = []
current_frequency = 0
end = False
def get_operator(op):
return {
'+' : operator.add,
'-' : operator.sub,
}[op]
def append_to_cache... |
eb1eb959de9a0a81609590597af8598f1fe93223 | AryanSharma5/python-OOPS | /python OOPS/Polymorphism.py | 681 | 4 | 4 | class English:
def greet(self,name):
print('Good Morning', name)
class French:
def greet(self, name):
print('Bonjour', name)
class German:
def greet(self, name):
print('Guten Morgan', name)
def greetings(language, name):
language.greet(name)
print('1.English\
2.French\
3.German\
... |
c63e3de08b0b05c40f437c88d1756e47fd7e03c1 | Shushuda/Clearcode-Intern-Summer-Task | /test_main.py | 5,117 | 3.625 | 4 | import unittest
import main
class TestMain(unittest.TestCase):
def test_calculate_right_solution(self):
"""
Test that the returned solution is correct.
"""
items_data = [
('dolan.jpg', 126, 6),
('smutna_zaba.png', 221, 10),
('t-series.avi', 522,... |
452ae414135febbb386c9b88ff2edb723fef119e | agoila/rnn-tutorial | /PartA/calculator.py | 2,734 | 3.90625 | 4 | ''' author: samtenka
changed: 2017-10-06
created: 2017-10-06
descr: demonstrate the techniques and significance of persistent state by building a calculator
usage: Run `python calculator.py`.
A prompt should appear. Enter in a few numbers and observe the
displayed stack grow. En... |
1637538e45a7b7a92ae1cfda89357abfc7d13e7b | huchaoyang1991/py27_class | /py27_06day/05条件判断小案例‘.py | 1,458 | 3.6875 | 4 | """
============================
Author:柠檬班-木森
Time:2020/2/15 11:11
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
# 登录小案例:事先存储一组账号密码,提示用户输入账号,密码,然后判断账号密码是否输入正确
# 第一步:事先存储账号密码
data = {"user": "python27", "pwd": "lemonban"}
# 第二步:提示用户输入账号,密码
user = input("请输入账号:")
pwd = input("请输入密码:... |
558b9ca0268c270cd0616047ae6da189ad4dc773 | huchaoyang1991/py27_class | /py27_05day/task_05day.py | 2,489 | 4.0625 | 4 | # 1、 将字符串中的单词位置反转,“hello xiao mi” 转换为 “mi xiao hello”
# (提示:通过字符串分割,拼接,列表反序等知识点来实现)
import random
str = 'hello xiao mi'
li = str.split(' ')
print(li)
li.reverse()
print(li)
s_blank = ' '
str2 = s_blank.join(li)
print(str2)
# 2、字典的增删查改操作: 某比赛需要获取你的个人信息,编写一段代码要求如下:
# 1、运行时分别提醒输入 姓名、性别、年龄 ,输入完了,请将数据通过字典存储起来,
dic... |
9b25a8023ec39aa11ed9fb3a0275bfb8e9841930 | huchaoyang1991/py27_class | /py27_03day/task_03day.py | 1,737 | 4.03125 | 4 | import random
# 1、现在有变量 a = ‘hello’ , b = ‘python18’ c = ‘!’ ,通过相关操作转换成字符串:'hello python18 !'(注意点:转换之后单词之间有空格)
s_blank = " "
a = 'hello'
b = 'python18'
c = '!'
print(s_blank.join((a, b, c)))
# 2、使用random模块和字符串拼接的方法,随机生成一个130开头的手机号码(只能使用上课学过的知识去做)。
phone = '130'
for i in range(8):
num = str(random.randin... |
546b2b4085448254ea096c8f99c35f1f110ad6aa | huchaoyang1991/py27_class | /py27_07day/08函数的返回值.py | 544 | 3.8125 | 4 | """
============================
Author:柠檬班-木森
Time:2020/2/18 21:58
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
函数的返回值:return
"""
# 需求:定义一个完成两个数相加的函数
def add_number(a, b):
print("a+b的结果:", a + b)
return a+b
res = add_number(11, 22)
print(res)
# 调用函数之后,接收到的数据为None,... |
64d0971a4ea0c5f827a4b00c429d080627500bf9 | huchaoyang1991/py27_class | /py27_12day/task_11day.py | 4,449 | 3.765625 | 4 | """
============================
Author:柠檬班-木森
Time:2020/2/28 17:05
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
import random
def work1():
print('---石头剪刀布游戏开始----')
print('请按下面提示出拳:')
# 创建一个列表来存储 石头 剪刀 布
li = ['石头', '剪刀', '布']
while True:
print('石头【1】 ... |
92f16b121eab09f09b19bf3b05883bbecd6eabee | huchaoyang1991/py27_class | /py27_13day/09关于多继承的扩展学习.py | 684 | 3.609375 | 4 | """
============================
Author:柠檬班-木森
Time:2020/3/3 21:54
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
多继承
"""
class BaseA(object):
attr_a = 100
def func_a(self):
print("func_a---------aaa")
def func(self):
print("func---------aaa")
... |
ce3476fc4d8bbd9db172e0c91ef30b70771d7a24 | huchaoyang1991/py27_class | /py27_06day/07条件循环的使用.py | 728 | 3.90625 | 4 | """
============================
Author:柠檬班-木森
Time:2020/2/15 11:51
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
while循环
语法:
while 条件:
# 条件成立,循环执行的代码一
# 条件成立,循环执行的代码二
# 条件成立,循环执行的代码三
# 条件成立,循环执行的代码四
# .......
# 如果条件一直成立,则一直循环做条件满足的事情,直到条件不成立,结束循环
# 死循环
... |
e005a6045eceab1e5c38b360695d6979c2950116 | deeplearningfromscratch/learning-python3 | /print/ex15.py | 344 | 3.71875 | 4 | '''Reading Files'''
from sys import argv
script, filename = argv
#filename = 'ex15_sample.txt'
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())
txt.close() # it should be closed.
print("Type the filename again.")
file_again = input('> ')
txt_again = open(file_again)
print(txt_again.r... |
6b3c9e414503f3b249e372f690c97e6f8cd52d78 | Keikoyao/learnpythonthehardway | /Ex20.py | 881 | 4.25 | 4 | # -- coding: utf-8 --
from sys import argv
script, input_file = argv
#read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中
def print_all(f):
print (f.read())
#seek() 移动文件读取指针到指定位置
def rewind(f):
f.seek(0)
#readline() will read the file line by line as if there is a for next loop automatically vs readlines()一次读取整个文件
def prin... |
22f53caa886c3da9fc518ab99a317c8969a38daf | Keikoyao/learnpythonthehardway | /Ex.42_2.py | 1,957 | 4.0625 | 4 | mystuff = {'apple': "I AM APPLES!"}
print(mystuff['apple'])
def apple():
print("I AM APPLES!")
'''
import mystuff
mystuff.apple()
'''
def apple():
print("I AM APPLES!")
# this is just a variable
tangerine = "Living reflection of a dream"
'''
#访问
import mystuff
mystuff.apple()
print(mystuff.tangerine)
#使用... |
1a0260d0313bdf1d6c79434f2916383d54670312 | yusufcimenci/programlama_lab | /uzaktan_eğitim_hafta_4.py | 2,216 | 4.125 | 4 | #min_heapyfy(array,i) : bir dizinin i indeksindeki elemanı ile o elemanın sağındaki ve solundaki elamanlan büyüklük kıyaslaması yapar. Küçük olanı üste çıkartır. diziyi heap yapısına çevirir
#build_min_heapy(array) : aldığı dizinin yarısından itibaren geriye doğru kontrol edee ve bütün diziyi MinHeap düzenine sokar.
... |
72b9a98a40f92e42b7a78d2bd207012ff8dbab3a | seanthony/gas_card_tracker | /simple_app.py | 624 | 4 | 4 | print('welcome')
# get the user input
date = input('What is the date? ')
mileage = input('What is the mileage? ')
# get the current mileage
with open('alternative_tracker.txt', 'r') as file:
text = file.read()
# check the last updated mile total
last_item = text.split(',')[-1].strip()
if last_item.isdigit() and ... |
9536b37131542932747618a964e336e1138f7628 | synchronizedsynecdoche/Python-Cryptography-Environment | /ModuleMonitor.py | 1,734 | 3.5625 | 4 |
class Monitor(object):
#make the inputhandler pass the which one, instead of the current spaghetti conditionals
def Cipher(self, whichOne):
if whichOne == "AES":
print "Rijndael is the de-facto symmetric encryption " \
"algorithm. It takes a key of ... |
69a423bb98832e2f2845e50b5500bf72d914416b | Elicarlos/algoritmos-ifpi | /linguagem-python/dicionario.py | 144 | 3.59375 | 4 |
dicionario = dict()
dicionario['codigo'] = 'Par do Cógido'
print("O tamanho do dicionarion {}" . format(len(dicionario)))
print(dicionario)
|
abd720790959cd85b3842e19c8a2d95fab5fe588 | itoledoc/Project2 | /osm_to_json.py | 8,694 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
This python set of functions help to parse, check, reshape and write into a JSON
file an OSM data file.
"""
import xml.etree.ElementTree as ETree
import re
import codecs
import json
import datetime as dt
CREATED = ["version", "changeset", "timestamp", "user", "uid"]
def get_db(db_name):
... |
b88a333116d522766fd762239322b66858124a20 | Alexeggers/Codeeval | /Medium/reverse_groups.py | 786 | 3.5625 | 4 | from sys import argv
file_name = "reverse_groups.txt"
#file_name = argv[1]
with open(file_name, "r") as file:
cases = [x for x in file.read().splitlines() if x]
def reverse_in_steps(list, steps):
new_list = []
for i in range(0,len(list),steps):
sublist = list[i:i+steps]
sublist = sublist[... |
9be0296bb66b8dfbd925804a3069634e7a11e8c4 | Alexeggers/Codeeval | /Easy/happy_numbers.py | 476 | 3.515625 | 4 | from sys import argv
with open(argv[1], "r") as file:
test_cases = (int(x) for x in file.read().splitlines() if x)
def square_up(x):
numbers = [int(i)**2 for i in list(str(x))]
x = sum(numbers)
return x
for case in test_cases:
already_found = []
while case != 1:
case = square_up(case... |
ce28a71ad1edab2ab1aef7fd69c8549ea49236a1 | Alexeggers/Codeeval | /Hard/string_permutations.py | 542 | 3.53125 | 4 | from sys import argv, exit
from math import factorial
from random import shuffle
#file_name = argv[1]
file_name = "string_permutations.txt"
with open(file_name, "r") as file:
for line in (x.strip() for x in file.read().split("\n") if x):
line_length = len(line)
outputs = []
while len(outpu... |
fd8197d4dc7fb3caa5066187687a49c72cfd3e5e | AIHackerTest/justin007755_Py101-004 | /Chap3/project/decorator_test.py | 396 | 3.921875 | 4 |
def float_args_and_return(function):
def wrapper(*args, **kwargs):
args = [float(arg) for arg in args]
return float(function(*args, **kwargs))
return wrapper
@float_args_and_return # 等价于“mean = float_args_and_return(mean)”
def mean(first, second, *rest):
numbers = (first, second) + rest
... |
267bcdf3b8750d5f6e67f4a5cb7ff2ee29fef0d3 | lalitsharma16/python | /sequential_character_remove.py | 883 | 3.734375 | 4 | #!/usr/bin/python
import sys
import random, string
DOCSTRING=''' To remove the sequential duplicate characters in the lis.
original = [a, x, b, b, x, d]
output = [a, d]
'''
LIST = []
for i in range(20):
LIST.append(random.choice(string.ascii_lowercase))
LIST = ['y', 'w', 'w', 'u', 'j', 'p', 'm', 'f', 'm', 'a', 'd'... |
70a625de9597018dcfcc3f9430c82268fadeef58 | lalitsharma16/python | /decimal_return.py | 566 | 3.859375 | 4 | #/usr/bin/python
def solution(A, B):
# Check if number is present in the bigger number
if str(A) in str(B):
# print the length of series for checking the index for the number and then find the index of the number using if condition.
result = [n for n in range(len(str(B))) if str(B).find(str(A), n) == n]
... |
4f4df9013cc0d99ab6e0cc451de3ccf1f51667a5 | wangyiqing108/cmdb | /user/code2/exists_names.py | 249 | 3.859375 | 4 | #encoding: utf-8
names = ['woniu', 'kk', 'wd']
name = 'wd'
exists = False
for _name in names:
if _name == name:
exists = True
break
if exists:
print '在'
else:
print '不在'
#list:访问, max, min, len |
19f8f2f0176f109eb18106146c1ccdd54fac1903 | kbohinski/Problem-Solving-Practice | /projectEuler/prob6.py | 720 | 3.609375 | 4 | '''
Kevin Bohinski
bohinsk1@tcnj.edu
2015-3-7
Problem-Solving-Practice
projectEuler
prob6.py
Copyright (c) 2015 Kevin Bohinski. All rights reserved.
'''
'''
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + ... |
23e9f5cdb18b0d2a7c08607f14a095894efe758d | DWJ01/Map-project | /plot.py | 966 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 7 10:36:31 2018
@author: liuconnie
"""
import pandas as pd
import matplotlib.pyplot as plt
#This is a plot of all pickup and dropoff location
#which is a preprocessing step to see density of cab pickup and dropoff
df = pd.read_csv('train.csv')... |
1877ff3d68d6f597efb888433ef2ee6a28700689 | iosmichael/interview-prep | /sorting.py | 704 | 3.9375 | 4 | class Sorting(object):
def __init__(self, data):
self.data = data
self.n = len(data)
def merge_sort(self, data):
pass
def merge(self, arr1, arr2):
pass
def quick_sort(self, data, lo, hi):
if lo < hi:
p = self.partition(data, lo, hi)
self.quick_sort(data, lo, p-1)
self.partition(data, p+1, hi)
... |
d895f64833671f9fecef3bdd667931a6c37981f8 | w2k31984/Selenium_WebDriver_Python | /Manejo_Ficheros.py | 1,126 | 3.703125 | 4 | #Los ficheros sirven para guardar datos .csv o bien importar datos, para diferentes situaciones.
#Para consulta o guardar datos.
#a adicionar Añadir elemento a un fichero.
#w Modo de escritura de ficheros
#r modo de lectura de ficheros
#Agregar informacion nueva en un fichero
nombre = input('Nombre :')
#+ adicionar fu... |
72aabc3a2996f3c538ce83a5d14c66b3ced70f52 | w2k31984/Selenium_WebDriver_Python | /Diccionarios.py | 716 | 4.03125 | 4 | #Ultimo conjunto de datos de Python
#Esta definido con llaves
a = {'persona':'Cristian Parada','fruta':'Guineo','color':'Azul','edad':20, 'fecha nacimiento':'08/09/84'}
#for i in a:
# print(a[i])
# La funcion para poder hacer un contenido de un diccionario es dict
b = dict(nombre='Cristian Menendez', color='negro',f... |
7c115541a916f1d00dfc705c671ab3702ddc3a2a | xanthosgeorge/Computers | /project5.py | 457 | 3.625 | 4 | f = open("project.txt", "r")
# Άνοιγμα αρχείου
words = f.read()
words = words.split()
print (words)
for i in range(0,len(words)):
if len(words[i])>3:
# Αφαίρεση πρώτου γράμματος
tomi = words[i][:-(len(words[i])-1)]
#print(tomi)
# Βάζουμε τα γράμματα όπως τα ζητάει η εκφώνηση
... |
abb91a8ef85b947a3359ec0c8e04420a1d3424f2 | ksoltan/comprobo_final | /mdp_planner/src/Action.py | 1,079 | 3.625 | 4 | from collections import OrderedDict
import math
'''
Class: Action
Enumeration of possible robot actions.
The change in pose generated by each action is
a tuple of (linear, angular) change.
'''
class Action:
LEFT = -1
FORWARD = 0
RIGHT = 1
ACTION_MAP = OrderedDict()
# action : (lin... |
23b877b4f59755ecfa7d4496c4214719eaee8d7f | azraelamll/hello-world | /AMLL_ex19.py | 1,152 | 4.0625 | 4 | # Ejercicio 19
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"¡Tienes {cheese_count} quesos!")
print(f"¡Tienes {boxes_of_crackers} cajas de galletas!")
print("¡Hombre, eso es suficiente para una fiesta!")
print("Consigue una manta. \n")
print("Podemos darle los números a la func... |
b8ebbb9b080dbcb1edd28a280ffdcf6e2798288e | vivekpatani/ai-ml-projects-data-science | /project-word-sense-disambiguation/bagofwords.py | 6,061 | 3.53125 | 4 | from nltk.corpus import wordnet as wn
from nltk.stem.porter import *
from subprocess import call
def readfile(filename,location="input/"):
"""
Read the input files
"""
file_data = open(location+filename).read()
file_data = file_data.split('.')
return file_data
def get_bag_of_words(word, import... |
8de78ef992ed493faa15b97bdbbe9761cb45f2f5 | Pimonon/linebot | /p05.py | 245 | 3.890625 | 4 | def cube(x):
return x**3
def power(x,y):
return x**y
def fac(x):
if x == 1:
return 1
if x ==2:
return 2
return x * fac(x-1)
x = 2
y = cube(x)
print(x,y)
print(power (5,2))
#print('FAC' fac(1000))
|
1948f4f706ca8f6629675a2e50e314921b3ca12b | cvincent14/calculCourse | /calculCourse.py | 1,132 | 3.6875 | 4 | from random import randint
class student:
def __init__(self, l):
names = ["Corentin","Erwin","Nils","Benjamin","Baptiste","Léo","Maxence","Minh Khieu"]
self.name = names[randint(0,len(names)-1)]
self.laps = [0]*l
def getName(self):
return self.name
def setLapTime(self, lap,... |
01bf1a07e6ff3619676c501ede4b76601b8abd5e | eilyi/IS685_Week5 | /fibRecursive.py | 185 | 3.75 | 4 | #def fibRecursive(n):
def fibRecursive(n):
#fib_n = fib_n-1 + fib_n-2
if n== 0 :
return 0
if n== 1:
return 1
return fibRecursive(n-1) + fibRecursive(n-2)
print(fibRecursive(9)) |
df3aa5aa347b63d551cbde6e6d8d502bc0e1e95e | KrinkovD/agazati_prog | /ágazati gyak óra/mertanikozep.py | 362 | 3.828125 | 4 |
import math
def middle():
list = []
for i in range(0, 5):
number = int(input("Szám: "))
list.append(number)
result = calcMiddle(list)
print("A mérteni közép: {:>20.3f}".format(result))
def calcMiddle(list):
# sqrt(szamok * )
multiple = 1
for i in list:
multiple *= i
result = pow(multiple, 1 /le... |
479b1e222b0d7e85eedd5aecdc33307898b6a424 | shubham3063/udacity-hadoop-intro-course | /purchases/mapper-daywise-tales.py | 937 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 31 08:24:22 2015
@author: hduser
"""
# Sample input line
# 2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex
import sys
from datetime import datetime
# read input line by line from the standard input
for line in sys.stdin:
try:
# ... |
33e1e11d95b94d22e1fc939c716cd8251d04b034 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex34 - Accessing Elements of Lists.py | 2,096 | 4.21875 | 4 | # Remember, if it says "first," "second," then it's using ORDINAL, so subtract 1.
# If it gives you CARDINAL, like "The animal at 1", then use it directly.
# Check later with Python to see if you were correct.
animal = ['bear','python3.7', 'peacock', 'kangaroo', 'whale', 'platypus']
# Q1. The animal at 1. ... |
2ffa957733ffcd46c2fd448b75f6bbe9c64043ec | TwoChill/Learning | /Learn Python 3 The Hard Way/ex32 - Loops and Lists.py | 1,770 | 4.5625 | 5 | hair = ['brown', 'blond', 'red']
eye = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print(f'This is c... |
545cbfef3ca36549f96c421a54fafc0c0c92d318 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex15 - Reading Files.py | 1,845 | 4.625 | 5 | # This line imports the variable argument argv from the sys module.
from sys import argv
# These are the TWO command line arguments you MUST put in when running the script.
script, filename = argv
# This line opens the filename argument and puts it content in a variable.
txt = open(filename)
print("\n\nTHIS IS THE ... |
1ba8d3a533dbd2173d3da1830c6f3820eb033b56 | TwoChill/Learning | /Head First Python/ex2 - Challenge (List Methods).py | 986 | 3.796875 | 4 | # phrase = "Don't panic!"
# plist = list(phrase)
# print(phrase)
# print(plist)
#
#
#
# Your code here
#
#
#
# new_phrase = ''.join(plist)
# print(plist)
# print(new_phrase)
####################################################
########### Below is code from MdeFrance ###########
#####################################... |
87c4374dcfb0a8e1fdadbeefed9d8c774bb7e7a9 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex19 - Functions and Variables - Shopping List (Program Practice).py | 875 | 4.0625 | 4 | ###############################################################################
print("#" * 35, "\n")
print("PRACTICE FUNCTIONS - SHOPPING LIST\n\n")
print("#" * 35, "\n")
def shopping_list():
list_name_items = []
print("Type 'quit' to see the results.\nPress ENTER to add another shopping Item.\n\... |
4c7fdd6fe35f53ac8a12e8b3a3c69a64e08b3b28 | cazzara/mycode | /random-stdlib/use-random.py | 2,112 | 4.65625 | 5 | #!/usr/bin/env python3
import random
## Create a random number generator object
# This can be used to instantiate multiple instances of PRNGs that are independent of one another and don't share state
r = random.Random()
## Seed random number generator
# This initializes the state of the PRNG, by default it uses the... |
8068f6de2b10e0d0673a0d96f8a62135223624f7 | cazzara/mycode | /if-test2/if-test2.py | 380 | 4.1875 | 4 | #!/usr/bin/env python3
# Author: Chris Azzara
# Purpose: Practice using if statements to test user input
ipchk = input("Set IP Address: ")
if ipchk == '192.168.70.1':
print("The IP Address was set as {}. That is the same as the Gateway, not recommended".format(ipchk))
elif ipchk:
print("The IP Address was se... |
5eca3115baaf3a1f4d09a92c3e8bef73b5e655e8 | cazzara/mycode | /datetime-stdlib/datetime-ex01.py | 931 | 4.28125 | 4 | from datetime import datetime # required to use datetime
## WRITE YOUR OWN CODE TO DO SOMETHING. ANYTHING.
# SUGGESTION: Replace with code to print a question to screen and collect data from user.
# MORE DIFFICULT -- Place the response(s) in a list & continue asking the question until the user enters the word 'quit'
... |
6d97910dec4e43babf5cd72af25ea9783d02e599 | tuhuuxxx/Learning-Python | /Ki Ba Lan Class.py | 4,730 | 4.125 | 4 | import math
binary_operators = ['^', '*', '/', '+', '-']
unary_operators = ['!', 'sin', 'cos', 'tan', 'cot']
parenthese = ['(', ')']
def is_operand(ch):
return ch.isdigit()
def is_binary_operators(ch):
return ch in binary_operators
def is_unary_operators(ch):
return ch in unary_operators
def is_operator(ch)... |
1ed15bd4d250bfc4fc373c26226f84f83c40cdcd | shishir7654/Python_program-basic | /listcomprehension1.py | 513 | 4.375 | 4 | odd_square = [x **2 for x in range(1,11) if x%2 ==1]
print(odd_square)
# for understanding, above generation is same as,
odd_square = []
for x in range(1, 11):
if x % 2 == 1:
odd_square.append(x**2)
print( odd_square)
# below list contains power of 2 from 1 to 8
power_of_2 = [2 ** x f... |
5fb3dbd6297ff7cecb008041f59d18f121c557f2 | shishir7654/Python_program-basic | /pattern3.py | 174 | 3.796875 | 4 | for i in range(5,0,-1):
for k in range(5-i,0,-1):
print(' ', end = '')
for j in range(1,(2*i-1)+1):
print(j, end = '')
print()
|
d945727a9469d18c9a4e3b3db7a703a2a020501e | shishir7654/Python_program-basic | /override.py | 382 | 3.84375 | 4 | # Method Overriding
class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;
class ICICI(Bank):
def getroi(self):
return 8;
b1 =Bank()
b2=SBI()
b3= ICICI()
print("Bank Rate of interest:",b1.getroi());
print("SBI Rate of interest:",b2.g... |
abc7a8dfd2791d9339c3c552cca2cb780b331c9e | shishir7654/Python_program-basic | /date6.py | 196 | 4.15625 | 4 | # Print today's year, month and day
from datetime import date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
|
0e9fecfedd6eb862931556a4e51afd608cbd0f57 | shishir7654/Python_program-basic | /function2.py | 297 | 3.953125 | 4 | #defining the function
def change_list(list1):
list1.append(20);
list1.append(30);
print("list inside function = ",list1)
#defining the list
list1 = [10,30,40,50]
#calling the function
change_list(list1);
print("list outside function = ",list1);
|
c084419e361233b87f85c9a688e29f6471376579 | brennanmcfarland/physics-class | /18-1a.py | 1,469 | 4.125 | 4 | import matplotlib.pyplot as plt
import math
def graphfunction(xmin,xmax,xres,function,*args):
"takes a given mathematical function and graphs it-how it works is not important"
x,y = [],[]
i=0
while xmin+i*xres<=xmax:
x.append(xmin+i*xres)
y.append(function(x[i],*args))
i+=1
... |
2e90f8168a9c8d07ff60d72028a511d8e61c9423 | necessary129/xMonit | /src/settings.py | 549 | 3.546875 | 4 | import sqlite3
from collections import defaultdict
users = set()
def check_db():
try:
with sqlite3.connect("users.db") as db:
c = db.cursor()
sql = 'CREATE TABLE IF NOT EXISTS users (users text)'
c.execute(sql)
except:
raise
check_db()
def fill():
with s... |
d8e409bc923a246e40ad1b6e68639dd72b40f4a7 | yanjia92/SpacNN | /src/util/FormatUtil.py | 681 | 3.828125 | 4 | # -*- coding:utf-8 -*-
def str2num(val):
'''
将一个代表字符串转化为数字
:param val: number in str
:return: number
'''
if isinstance(val, str):
result = None
try:
if '.' in val:
result = float(val)
elif val.isdigit():
result = int(val)
... |
f5547f50dd6dd6b623ff735c59e5283e55e8dd58 | yanjia92/SpacNN | /src/test/unittest/SingletonAnnotationTest.py | 626 | 3.53125 | 4 | from unittest import TestCase
from util.AnnotationHelper import singleton
@singleton
class Singleton(object):
def __init__(self, obj):
self.obj = obj
class NotSingleton(object):
def __init__(self, obj):
self.obj = obj
class Test(TestCase):
def setUp(self):
self.singleton1 = Sin... |
292b22d01113d9b64b09e06d6ba9d6343ba9c0f7 | tbvanderwoude/research-project | /python/mstar/bfsnode.py | 710 | 3.515625 | 4 | from __future__ import annotations
from python.coord import Coord
class BFSNode:
def __init__(self, pos: Coord, move_cost, prev_pos):
self.pos = pos
self.move_cost = move_cost
self.prev_pos = prev_pos
def __gt__(self, other: BFSNode) -> bool:
return self.move_cost > other.mov... |
6504082309bd8390d384410010010f59c616c7f2 | patrickmalg/aulas-python | /PYTHON-MUNDO 2/SOMA_SOMENTE_PARES.py | 265 | 3.734375 | 4 | soma = 0
cont = 0
for num in range(1, 7):
valores = int(input("Digite o {}° valor: ".format(num)))
if valores % 2 == 0:
cont = cont + 1
soma = soma + valores
print("Você informou {} valores pares e a soma deles é {}.".format(cont, soma))
|
3cae3ffe998863835c9172c31debe43aebcbf016 | patrickmalg/aulas-python | /PYTHON-MUNDO 2/py-ex038.py | 366 | 3.8125 | 4 | nome = str(input("Nome do aluno: "))
n1 = float(input("Primeira nota: "))
n2 = float(input("Segunda nota: "))
media = (n1 + n2) / 2
print("A Média do aluno {} é {:.1f}".format(nome, media))
if media <= 5.0:
print("Situação: REPROVADO.")
elif media > 5.0 <= 6.9:
print("Situação: em RECUPERAÇÃO.")
elif media >= 7... |
9729ee567d146d3fbb87ee9107f40a9735f320d9 | patrickmalg/aulas-python | /PYTHON-MUNDO 1/random.py | 717 | 3.90625 | 4 | print("-" * 70)
print("AUTO ESCOLA SP")
print("Preencha os dados a baixo para saber se está apto a dirigir.")
print("-" * 70)
nome = str(input("Digite seu nome completo: "))
nasc = int(input("Digite o ano em que você nasceu: "))
estado = str(input("Em qual estado você mora? "))
idade = 2019 - nasc
print(" ")
prin... |
b4f7c0ae4e940f22c9ebe895d2b9f369efab1d62 | patrickmalg/aulas-python | /PYTHON-MUNDO 1/py-ex004.py | 304 | 4 | 4 | n = int(input("Digite um número: "))
dobro = n * 2
triplo = n * 3
raiz = n ** (1/2)
metade = n / 2
print('O dobro de {} vale {}.'.format(n, dobro))
print('O triplo de {} vale {}.'.format(n, triplo))
print('A raiz de {} vale {:.2f}.'.format(n, raiz))
print('E a metade de {} vale {}.'.format(n, metade)) |
805c02073e9b1be3c070391d3ce1985094ee5beb | patrickmalg/aulas-python | /PYTHON-MUNDO 1/aula01-tupla.py | 200 | 3.875 | 4 | #a diferença entre listas e tuplas é que tuplas tem um tamanho fixo, nao da para adicionar elementos nela
# é inicializada com parenteses
tupla = (1, 2, 3, "str1")
print(type(tupla))
print(tupla) |
06b02f32999facdb5ba1c19bdc668a9503534f0d | Trietptm-on-Security/snippy | /Python/convert.py | 1,621 | 3.9375 | 4 | #!/usr/bin/env python
"""
just some base conversions
@WRK
"""
def useage():
print "-c Base-converts Integer values. Automatically: 0x - hex, 0 - oct..."
print "-d2h decimal to hexadecimal"
print "-d2o decimal to octal"
print "-d2b decimal to binary"
print... |
7d850e54afbd0ee59b2a5c248fadd7f11a0f0e3b | chehao2628/ImprovedCasper | /utils.py | 2,538 | 3.515625 | 4 | import torch
import numpy as np
import torch.nn.functional as F
# This file contains some fucntions for helping work and testing
# define a function to plot confusion matrix
def plot_confusion(input_sample, num_classes, des_output, actual_output):
confusion = torch.zeros(num_classes, num_classes)
for i... |
65a294810e1afc9d10fa24f84d8a4d60b5ec02c3 | jle33/PythonLearning | /PythonMasterCourse/PythonMasterCourse/GenetratorExample.py | 1,494 | 4.25 | 4 | import random
#Generator Example
def get_data():
"""Return 3 random integers between 0 and 9"""
print("At get_data()")
return random.sample(range(10), 3)
def consume():
"""Displays a running average across lists of integers sent to it"""
running_sum = 0
data_items_seen = 0
print("At top of ... |
e13a2b8ce478d24152a61f7fa81423d31de8b132 | jle33/PythonLearning | /PythonMasterCourse/PythonMasterCourse/DocStrings.py | 1,366 | 3.796875 | 4 | class Song: #docstrings - should be """ some string """ to keep it consistent with everyone's docStrings
"""Class to represent song
Attributes:
title(str): Title of song
artist(Artist): An artist object representing the songs creator.
duration(int): The duration of the song in seconds. C... |
4ebb35b2cefcf4b50df65e3e941b1e7af1567105 | ShiyuanLin/csc411 | /A2/1/HW1 CODE/logistic.py | 5,313 | 3.96875 | 4 | """ Methods for doing logistic regression."""
import numpy as np
from utils import sigmoid
def logistic_predict(weights, data):
"""
Compute the probabilities predicted by the logistic classifier.
Note: N is the number of examples and
M is the number of features per example.
Inputs:
... |
5984cfb77a71baa4d01c4155c12cfd02b3d17cb5 | tclh123/iplot | /website/Interpreter/common/frange.py | 606 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tclh123'
def frange(start, end=None, inc=1.0):
"A faster range-like function that does accept float increments..."
if end == None:
end = start + 0.0
start = 0.0
else: start += 0.0 # force it to be a float
count = int((end - st... |
e3c207b272eee4af05a453e2423abc3f508bef5f | hiepnguyen034/cs224n-solutions | /a4/test.py | 771 | 3.734375 | 4 | def pad_sents(sents, pad_token):
""" Pad list of sentences according to the longest sentence in the batch.
@param sents (list[list[str]]): list of sentences, where each sentence
is represented as a list of words
@param pad_token (str): padding token
@returns sents_padded (list[list[str]]): list of sentence... |
041a7ac9b7475ca0c881056ae359687dcddc1d61 | Jayasree-Suresh/Scientific-Calculator | /src/driver/scientific_calc.py | 984 | 4.09375 | 4 | """This module is used for calculating scientific operation(e^x)"""
import logging
logging.basicConfig(filename='ScientificCalculatorLog.log', level=logging.ERROR,
format='%(name)s - %(levelname)s - %(message)s - %(asctime)s '
'- %(lineno)d - %(module)s - %('
... |
218254f6a4c1152326423160bebdb9d8461d05a2 | jodaz/python-sandbox | /automate-boring-stuff-python/tablePrinter.py | 1,093 | 4.34375 | 4 | #! python3
# tablePrinter.py - Display a list of lists of strings in
# a well-organized table.
table_data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def print_table(main_arr):
col_widths = [0] * len(main_... |
b3bba5c4526cff24bd9b71a60aadddcf6e623228 | jodaz/python-sandbox | /automate-boring-stuff-python/strongPassword.py | 424 | 4.34375 | 4 | #! python3
# strongPassword.py - Find is your password is strong.
import re
password = input('Introduce your password: ')
find_upper = re.compile(r'[A-Z]').findall(password)
find_lower = re.compile(r'[a-z]').findall(password)
find_d = re.compile(r'\d').search(password)
if find_upper and find_lower and find_d and le... |
d1c1b93dfb01b82d6f42ca008f8f3cff54dd2be0 | yatw/Algorithms | /MergeSort.py | 1,506 | 3.6875 | 4 | # Divide and conquer approach
# recurrence equation is
# T(n) = 2T(n/2) + n - 1 , if n > 1
# = 0 , if n = 1
# a = 2, b = 2, k = 1, use simplified Method
# a = b, case 2
# (n^k)logn = (n^1)logn = nlogn
# T(n) = θ(nlogn)
def MergeSort(A,first,last):
'''
Split array into two equal subarrays
S... |
01e0aeec90695f8d9483d794773cc9743e3c4655 | nicholasarchambault/CIA_factbook | /Analyzing CIA Factbook Data with SQL.py | 4,569 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Analyzing CIA Factbook Data with SQL
# by Nicholas Archambault
#
# In this project, we'll analyze data from the CIA Factbook, a compendium of statistics about every country on Earth. The Factbook includes the following demographic information:
#
# * `name` - The country's... |
7d0cc180ab6f96a11d13baef47be5cf4021791b0 | Arain-sh/RBNN | /binpacking/Bin.py | 535 | 3.515625 | 4 | """
Bin class.
Author: Arain, Linli
Date: March 29, 2019.
Bin data:
Example for 2-D bin packing
(x, y, u) tuples.
x is the width, y is the height, u is 1 packed or 0 for unpacked.
"""
class Bin():
"""
Bin class.
(x, y, u) tuples.
x is the width, y is the height, u is 1 packed or 0 for ... |
6ae960938d0ae347ec91f094a032aa1061a1f456 | Peaches255/leetcode | /problems/1678.py | 621 | 3.640625 | 4 | class Solution(object):
def interpret(self, command):
"""
:type command: str
:rtype: str
"""
array = list(command)
interpretString = ""
for index in range(len(array)):
print array[index]
if array[index] =='G':
interpret... |
57f34a3bbae49208e751d9e4c30dbff6444bac8b | crazymonkeycoder/coding-tutorial | /lesson07.py | 9,053 | 4.5625 | 5 | #!/usr/bin/env python3
# We're going to quickly go back to conditional expressions for a bit, and nail
# down some nitty gritty details today.
# First off, we're going to learn about a *variable type* called *booleans*.
# We learned about 2 of the "types of variables" that Python has - the string
# and the integer.
... |
325e9e0bcd2db5bcd654eb94863564a3aec42a7c | crazymonkeycoder/coding-tutorial | /lesson08.py | 6,152 | 4.625 | 5 | #!/usr/bin/env python3
# We're going to learn about floating points (or just floats) and some funky
# operators with strings.
# Remember that when we tried to divide integer values as is, we got this long
# decimal number? Something like:
#a = 5 / 3
#print(a) # this prints 1.6666666667
# The variable 'a' contains ... |
bfefcb852b99db2aa42dcce6a7629bc86e771fde | alfredchavez/LearningProject | /randomcsv.py | 664 | 3.625 | 4 | import random
import csv
import string
import sys
VOWELS = "aeiou"
CONSONANTS = "".join(set(string.ascii_lowercase) - set(VOWELS))
def generate_word(length):
word = ""
for i in range(length):
if i % 2 == 0:
word += random.choice(CONSONANTS)
else:
word += random.choice... |
98f72a0486ba5cc22b42028c6bb0cd5e79ca2597 | Peterbamidele/PythonDeitelChapterOneExercise | /2.3 Fill in the missing code.py | 394 | 4.125 | 4 | """(Fill in the missing code) Replace *** in the following code with a statement that
will print a message like 'Congratulations! Your grade of 91 earns you an A in this
course' . Your statement should print the value stored in the variable grade :
if grade >= 90"""
#Solution
grade = 90
if grade >= 90:... |
f8648cd5ab8308f5fda74aee003af87f93322182 | Pascal1755/Equation-Symbol-Visualization | /graphFromText/fxnFromText/fxnGraph.py | 32,599 | 4.09375 | 4 | '''
The getParenLvl3() parses through a text which has parenthesis
and determines the grouping of characters based upon the number
of parenthesis it has encountered. For instance, if the input
text were as follows:
text = 'x+f(y,z,g(x))'
then the output would be a list of
[0,0,0,0,1,1,1,1,1,1,2,2,2,1]
where the values ... |
4b8c702f3608e7761c7e4137187636a6aa695e07 | 3JohnJL/Intro-to-ComSci | /boxes.py | 528 | 3.875 | 4 | #Lydia John
def print_square(): #prints out a 5x5 square
print ("*****")
print ("* *")
print ("* *")
print ("* *")
print ("*****")
def print_rectangle(w, l):
print ("*"*w) #prints out a rectangle according to user specified widt... |
4c6ba06ba9557a0be4d49497e61518fada7ae0a6 | 3JohnJL/Intro-to-ComSci | /extract.py | 344 | 3.515625 | 4 | s=input('Enter the raw data:\n')
l=s.find('BEGIN')
y=s.find('_')
d=s.find(':')
i=s.find(',')
a=s.find('END')
p=s[i+6:a-1]
lo=p[::-1]
ll=lo.lower()
print('Site information:')
print('Location:',ll.capitalize())
print('Coordinates:',s[i+1:i+6],s[d+1:i])
print('Temperature:',s[l+5:y],' C',sep='')
print('Pressu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.