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 |
|---|---|---|---|---|---|---|
3f1ceb924f3eeb79ea7f10ac1da8fe5b90749bc6 | jsadden/RottenScraper | /rottenPlotter.py | 1,685 | 3.546875 | 4 | import matplotlib.pyplot as plot
#get and open data file
DATAFILE = 'rottenScraperData.txt'
rottenFile = open(DATAFILE, 'r')
DELIMITER = '\t'
#read the headers in the first line
headers = rottenFile.readline().strip().split(DELIMITER)
#dictionaries which will contain the genre's counted movies, the sum of the gaps i... |
d3576db422263e91404d9f807f6cbbd79aa275e8 | Fluff18/Parallelism | /Python/Multq.py | 1,021 | 3.703125 | 4 | import threading
import queue
import random
class multiple:
def __init__(self):
self.queue = queue.Queue()
self.lock = threading.Lock()
def get(self):
if (not self.empty()):
self.lock.acquire()
i= self.queue.get()
print(threading.currentTh... |
199c6b9a84de01cbeebce71d7abe6330b92c1395 | premkumarr1989/pythonnew | /func.py | 79 | 3.625 | 4 | def printmyname(x):
print(x)
name=input("Enter a Name")
printmyname(name) |
8403b11bff972b88e9104e81a81114c3954f28e5 | LesterAGarciaA97/IntroductionToProgramming | /01/Laboratories/IP_LAB_5.py | 1,191 | 4.09375 | 4 | class Estudiante(object):
"""Representa a un estudiante"""
def __init__(self, nombre, nota1, nota2, nota3):
"""Constructor de la Clase Estudiante"""
self._nombre = nombre
self._nota1 = nota1
self._nota2 = nota2
self._nota3 = nota3
def getNombre(self):
... |
ac64fdd3927a90b3c1b19108133dc59f4a0d5b89 | jorgeperezrojas/discursos | /src/suffix_array.py | 4,573 | 3.796875 | 4 | # from https://stackoverflow.com/questions/13560037/effcient-way-to-find-longest-duplicate-string-for-python-from-programming-pearl/13693834#13693834
from itertools import groupby
from operator import itemgetter
def longest_common_substring(text):
"""Get the longest common substrings and their positions.
>>> ... |
3475d1e8b927ef11b0ee366b87bdd520b2743e67 | AntoinePaoliEce/souffl-utile | /button.py | 1,300 | 4 | 4 | #https://pythonprogramming.altervista.org/buttons-in-pygame/
import pygame
class Button:
"Create a button, then blit the surface in the while loop"
def __init__(self, text, font, x=0, y=0, bg="black"):
self.x = y
self.y = x
self.font = font
self.text = text
... |
32f975235c250d297404d57f17f9246c2c8e0b44 | rrhoades10/Prework | /question5.py | 205 | 3.78125 | 4 | a_list = [1, 2, 3, 4, 5, 6, 7]
def is_consecutive(a_list):
for i in range(len(a_list) - 1):
if a_list[i] + 1 != a_list[i+1]:
return False
return True
is_consecutive(a_list)
|
f4f538830b060cf13cad9e9cf11336ac97a81bf5 | nssathish/learning-python | /codewithmosh/numbers.py | 416 | 4.03125 | 4 | print (10 / 3)
print (10 // 3)
print (10 % 3)
print (10 ** 3)
x = 10
x //= 3
print (x)
# BODMAS
# (B)rackets or parenthesis
# (O)rder or exponentiation
# (D)ivision
# (M)ultiplication
# (A)ddition
# (S)ubtraction
x = 10 + 3 * 2 ** 2
#x = 10 + 3 * 4
#x = 10 + 12
#x = 22
print(x)
x = 3.5
x = 3.4
print(roun... |
4f638bb4df750d61adda46e431d069e8fb333314 | nssathish/learning-python | /codewithmosh/conditional_statements.py | 288 | 4.09375 | 4 | weather = input('How is the weather? ')
if weather.lower() == 'hot':
print('''
It's a hot day
Drink plenty of water
''')
elif weather.lower() == 'cold':
print('''
It's a cold day
Wear warm clothes
''')
else:
print("It's a lovely day ") |
863c9baf3dc3c5edeac26137c907c091b80680cb | nssathish/learning-python | /codewithmosh/for_loop.py | 147 | 3.671875 | 4 | for item in 'Python':
print(item)
for item in ['sathish', 1, 2, ""]:
print(item)
#range function
for item in range(50):
print(item) |
074ace93b3f1c450d73ac63393117431095ecaa0 | nssathish/learning-python | /revisitpythonprogramming/working_with_textual_data.py | 295 | 4.03125 | 4 | print("Hello Sathish\'s computer")
message = 'Helloworld'
print (message[0:5])
for _ in range(0, 5):
print(message[_])
for i in range(0,5):
print(message[i])
print(message[6:])
#string count - word count - letter count etc.,
print(message.count("Hello"))
print(message.count("l")) |
ca5903883d3c1af3e3acac559d416914839cf1cf | nssathish/learning-python | /codewithmosh/Exceptions.py | 227 | 3.734375 | 4 | try:
age = int(input("Age: "))
income = 20000
risk = income / age
print (f'Age: {age} and risk: {round(risk)}')
except ValueError:
print('Invalid Age')
except ZeroDivisionError:
print('Age cannot be 0') |
8e0fba4ebefd6061f4e9541deae754e294ba662a | nssathish/learning-python | /codewithmosh/list_methods.py | 474 | 3.8125 | 4 | numbers = [1,2,3,4,5]
numbers.append(6)
print(numbers)
numbers.insert(3,1341234)
print(numbers)
print(numbers.pop())
print(numbers)
print(numbers.index(1341234))
# print(numbers.index(1000))
#
# print(1000 in numbers)
print(5 in numbers)
print(numbers.sort())
print(numbers)
print(numbers.count(5))
numbers2 = ... |
723f3706b55fbd16d92fa04183e61cb1a681523e | rjraiyani/Repository2 | /d23.py | 315 | 4 | 4 | user_input1 = input('Enter a string ')
#if l == '!':
# print(user_input1.upper())
#else:
# print(user_input1.lower())
vowels = ['a','e','i','o','u','A','E','I','O','U']
for idx,letter in enumerate(user_input1):
if letter in vowels:
user_input1 = user_input1.replace(letter,'')
print(user_input1)
|
e0058dfbb608836b24d131f6c92cabc1c551ad68 | rjraiyani/Repository2 | /larger_number.py | 272 | 4.125 | 4 | number1 = int(input('Please enter a number ' ))
number2 = int(input('Please enter another number ' ))
if number1 > number2:
print('The first number is larger.')
elif number1 < number2:
print('The second number is larger.')
else:
print('The two numbers are equal.' )
|
84b13b5ca2d438daac8c08a6a4d339f0ee9eb653 | rjraiyani/Repository2 | /exercise2.py | 266 | 4.375 | 4 | x = int(input('Please enter a number '))
m = x % 2
n = x % 3
if m == 0: #Even number
if n == 0:
print('Even and Divisible by 2')
else:
print('Even')
else:
if n == 0:
print('odd and divisible by 3')
else:
print('odd')
|
31dd2b221c2ffb9cf7024343ebeef3892857c721 | rjraiyani/Repository2 | /d22.py | 152 | 4.0625 | 4 | user_input1 = input('Enter Letter to be counted ')
l = user_input1[-1]
if l == '!':
print(user_input1.upper())
else:
print(user_input1.lower())
|
5f74f8e0f43f842bc4e2cfea1580b6f170792c6a | supermikol/coursera | /Algorithm Toolbox/Week 5/primitive_calculator/primitive_calculator.py | 793 | 3.75 | 4 | # Uses python3
import sys
def optimal_sequence(n):
val = [0] * (n + 1)
for i in range(2,n+1):
div_three = float("inf")
div_two = float("inf")
if i % 3 == 0:
div_three = val[i//3] + 1
if i % 2 == 0:
div_two = val[i//2] + 1
plus_one = val[i-1] + 1
... |
9232da8a0220cbb65e49a061ddf034e152018dd6 | supermikol/coursera | /Algorithm Toolbox/Week 3/fractional_knapsack/fractional_knapsack.py | 721 | 3.640625 | 4 | # Uses python3
import sys
def get_optimal_value(capacity, weights, values):
# write your code here
limit = capacity
n = len(weights)
weighted_values = sorted([[v/w, w] for v,w in zip(values,weights)], key = lambda l:l[0], reverse = True)
i = 0
value = 0
while limit > 0 and i < n:
a = ... |
bf7d395d7f79c13c18027ed9e18674be01971c47 | agiegerich/german-grammar-practice | /main.py | 847 | 3.65625 | 4 | from random import randrange
words = [1, 2, 3]
print (words[randrange(len(words))])
print('Hello world')
class Noun:
def __init__(self, english, gender, german, german_plural):
self.definite_article = gender
self.english = english
self.german = german
self.german_plural = german_... |
a286c63dfc7e9a0f66cf01b4a6ad8ae12b9f3913 | inwk6312winter2019/week4labsubmissions-saiharsit12 | /lab4.py | 7,591 | 3.75 | 4 | #TASK1
import string
def file_read():
"""Reads a file and prints the words in the file"""
fin=open("book.txt")
count=0
for line in fin:
line = line.replace("-", " ")
word=line.split()
for item in word:
item=item.strip(string.punctuation + string.whitespace)
... |
d9372f885c5191ab27215ad5cfb2c41cbb86536e | Andchenn/Lshi | /day08/06-使用类名调用父类的方法.py | 736 | 3.78125 | 4 | class Animal(object):
# 对象方法(需要有对象才可以调用)
def run(self):
print("动物跑起来了")
class Dog(Animal):
# 可以调用父类的方法(但是子类重写父类的方法,会调用自身,死循环)
def run(self):
# 调用父类的方法(不建议使用)
# self.run()
# 使用类名去调用父类的方法
# Animal.run(self)
# Dog表示类继承链的下一个类(指定的继承链中指定类的下一个类)
# self ... |
6ea19069627f3626d58186c7afa3511370fca291 | Andchenn/Lshi | /day03/budingc.py | 983 | 4.0625 | 4 | # 函数的不定长传参:1.不定长位置参数2.不定长关键字传参数
# 不定长参数:调用函数的时候不确定传入多少个参数
# 可能是0个或者多个
# ----------不定长位置参数的定义及调用--------------
# *args代表不定长位置参数,约定俗称起的名字
def sun_num(*args):
# 提示:args:会把调用函数传入的位置参数封装到一个元组里面
print(args, type(args))
# 计算结果变量
result = 0
for value in args:
result += value
return result
r... |
45183a97fb37526c07b5937b1bccfa0559e97b3d | Andchenn/Lshi | /day02/循环.py | 637 | 4.0625 | 4 | # continue:结束本次循环 然后继续下一个循环,整个循环不一定结束
num = 0
while num < 5:
num += 1
if num == 2:
continue
print(num)
else:
print("结束循环")
# break :跳出整个循环(结束)
print("--------------")
num = 0
while num < 5:
num += 1
if num == 2:
break
print(num)
else:
# 注意:break,会不执行else的代码
print("结... |
e8b74ec6a3a3b244167c81e771771e6721aa9770 | Andchenn/Lshi | /day05/07-函数文档说明.py | 295 | 4.03125 | 4 | """
这是一个多行注释
"""
def sum_num(num1, num2):
# 一般情况程序员不去写文档说明
# 第三方公司
"""
:param num1:第一个数字
:param num2:第二个数字
:return:返回值
"""
return num1 + num2
result = sum_num(1, 2)
print(result)
|
a628c0ea177a7e4f9c97496115974a0c6b5e4327 | Andchenn/Lshi | /day06/07-文件的操作.py | 2,292 | 3.59375 | 4 | # 文件的访问模式:
# 1.r:只读,文件不存在会崩溃
# 2.w:只写
# 3.a:追加
# 4.rb:以二进制方式读取文件:常用
# 5.wb:以二进制的方式写入文件:常用
# 6.ab:以二进制的方式追加数据:常用
# r+,w+,a+ 支持读写
# rb+,wb+,ab+ 支持二进制方式读写操作
# 读取文件
# ----------r模式(只读)
# 如果没有此文件会崩溃
# 打开文件解码过程(解析)
file = open("1.txt", "r", encoding="utf-8")
# 读取文件所有的数据
content = file.read()
print(content)
# 关闭文件(必须的)
file... |
848a52c613e4255b96b686dd39634b39fd7cc735 | Andchenn/Lshi | /day05/02-引用.py | 572 | 4 | 4 | # 引用:通俗理解就是程序中的数据在内存中的地址“简称内存地址”
# 底层:数据结构
# a存储的是一个内存地址,10的内存地址
a = 10
# b存储的是什么(也是内存地址,a的内存地址,10的内存地址)
b = a
# 打印内存地址
print("a的内存地址为", id(a))
print("a的内存地址为", id(b))
# 16进制的内存地址
print("a的内存地址为", hex(id(a)))
print("b的内存地址为", hex(id(b)))
# 相当于重新开辟一个内存空间,称内存地址
a=20
print("a的内存地址为",id(a)) |
c9e0bff26b0856ae1e480a41ebec2cacf93b4dc8 | Andchenn/Lshi | /day05/09-返回函数.py | 994 | 4.03125 | 4 | # 在函数内部返回一个函数,返回的这个函数就是返回函数
# 函数嵌套
def show():
def show1():
print("今天天气很冷")
return show1
# newfunc就是show1
new_func = show()
new_func()
# 返回函数也是高阶函数的一种
# 根据传入的不同参数,返回不同的函数(返回函数的重要意义所在)
def calc(operation):
if operation == "+":
def sun_num(num1, num2):
result = num1 + num2... |
fb0b081a528e8d3b02d597720e50ccd1753b0161 | Andchenn/Lshi | /day10/04-json序列化.py | 845 | 3.75 | 4 | import json
# 数据格式json(解析json)xml
# 只支持部分数据类型(列表字典,int...)
# 序列化自定义类型
my_list = [{"name": "张三", "age": "20"}]
file = open("mylist1.txt", "w", encoding="utf-8")
# 序列化
json.dump(my_list, file)
file.close()
# 反序列化
file = open("mylist1.txt", "r", encoding="utf-8")
my_list = json.load(file)
print(my_list)
file.close()
... |
837e57d5a2751f378a6d51770a219754400b7197 | Andchenn/Lshi | /day02/集合.py | 1,021 | 4.21875 | 4 | # 集合:以大括号形式表现的数据集合,集合里面的数据不可以重复
# 集合可以根据下标获取数据,也可以添加和删除
# 不可以以此种方式定义空的集合
# my_set = {} #dict字典
my_set = {1, 4, "abc", "张三"}
print(my_set)
# 删除数据(删除指定数据)(不能删除没有的数据)
# my_set.remove("22")
# print(my_set)
# 增加数据
# 不可以添加重复的数据
my_set.add("5")
my_set.add("5")
my_set.add("5")
print(my_set)
# 删除集合里面的数据(删除没有的数据不会崩溃)
# my_se... |
edd5cf21f14675cf6a4af3d6f20a082bd48ab1ae | davidlkang/foundations_code | /shopping_list.py | 1,423 | 4.125 | 4 | def show_help():
print("""
Type 'HELP' for this help.
Type 'CLEAR' to clear your list.
Type 'DEL X' where 'X' is the number of the element you want to remove.
Type 'SHOW' to display your list.
Type 'DONE' to stop adding items.
""")
def add_to_list(user_input):
shopping_list.append(user_input.lower())
prin... |
7ca179a45c2136eb638a635b700909482a5376fb | davidlkang/foundations_code | /login_app.py | 1,277 | 4.25 | 4 | users = {
"user1" : "password1",
"user2" : "password2",
"user3" : "password3"}
def accept_login(users, username, password):
if username in users:
if password == users[username]:
return True
return False
def login():
while True:
if input("Do you want to sign in?\n(... |
ade42f961f18dbf673c39ab73ce7ff0b39a07480 | sidasu92/pynet_test_dev | /day1_str_ex2.py | 166 | 3.703125 | 4 | #!/usr/bin/env/python
ip_address = input("Enter an IP address: ")
ipList = ip_address.split(".")
print(f"{ipList[0]:12}{ipList[1]:12}{ipList[2]:12}{ipList[3]:12}")
|
6e97c079069c3582f1d83e732073c36b1f4431d3 | pshemekhinca/xyz-reqruitment_task | /task_2.py | 1,842 | 3.953125 | 4 | import re
class DigitsRangeError(Exception):
"""Custom exception class to describe error raised when digits are given out of the range from 2 to 9."""
def __init__(self, given):
super().__init__(
f"In given number <{given}> found '1', '*', or '#'. For more than one digit numbers, only dig... |
f02e6f8d9a81b072ab3582f1469a62cc25b0905b | takaakit/design-pattern-examples-in-python | /structural_patterns/flyweight/main.py | 901 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from structural_patterns.flyweight.large_size_string import LargeSizeString
'''
Display a string consisting of large characters (0-9 digits only).
Large character objects are not created until they are needed.
And the created objects are reused.
Example Output
-----
Pleas... |
ed10cf8117e023c472003bf299f634721662806e | takaakit/design-pattern-examples-in-python | /creational_patterns/factory_method/main.py | 694 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from creational_patterns.factory_method.credit_card.credit_card_factory import CreditCardFactory
'''
The subject is a factory to make credit cards. The Factory defines how to create a credit card,
but the actual credit card is created by the CreditCardFactory.
The "createP... |
1a7d255cc658f6b602c56cde978656dbb048938f | Brunodev09/developer-task-manager | /main/utils/sqlite.py | 1,797 | 3.546875 | 4 | import sqlite3
from sys import exit
NO_COL = "no such column"
NO_TABLE = "no such table"
EXISTS = "already exists"
class sql:
try:
def __init__(self):
self.conn = sqlite3.connect('dtv-bdv.db')
self.c = self.conn.cursor()
def get_cursor(self):
return self.c
... |
bad357e547032486bc7e5b04b7b92351148a2b19 | 21milushcalvin/grades | /Grades.py | 1,649 | 4.25 | 4 | #--By Calvin Milush, Tyler Milush
#--12 December, 2018
#--This program determines a test's letter grade, given a percentage score.
#--Calvin Milush
#-Initializes variables:
score = 0
scoreList = []
counter = 0
total = 0
#--Calvin Milush
#-Looped input for test scores:
while (score != -1):
score = in... |
aebc43c166ee6b2aa11cc31246ed4fd2d6def6d9 | manal-hasan/facoders | /Python/week3.py | 369 | 3.75 | 4 | x=input("Enter student's name: ")
s1= ['Ahmad', 18, 17, 19.5, 8, 25]
s2= ['Sami', 20, 20, 19, 9, 28]
s3= ['Faris', 14.5, 16, 13, 7, 23]
if x==("Ahmad") :
s1.remove("Ahmad")
y=sum(s1)
print (x ,y)
elif x=="Sami":
s2.remove("Sami")
z=sum(s2)
print(x,z)
elif x=="Faris":
s3.remove("Faris")
v=sum(s3)
print... |
9df973b36d84ba5a9beb0fe1d15cb799b1d3fae2 | xiaoanning/python | /timeT.py | 693 | 3.515625 | 4 | #coding=utf-8
import time
print time.time() #输出时间戳
print "2017-07-07 18:33:59" > ""
struct = time.localtime(time.time()) #返回结构体 time.struct_time(tm_year=2010, tm_mon=7, tm_mday=19, tm_hour=22, tm_min=33, tm_sec=39, tm_wday=0, tm_yday=200, tm_isdst=0)
print struct
currentTime = str(time.strftime('%Y-%m-%d %H:%M:... |
5239fe8abfac26eedd32a7431b7ae346c2e87122 | KDL-in/NextStepOfMachineLearning | /week2/hw2_probabilistic.py | 4,207 | 3.65625 | 4 |
import numpy as np
def predict(X, w, b):
# This function returns a truth value prediction for each row of X
# by rounding the result of logistic regression function.
return np.round(f(X, w, b)).astype(np.int)
def accuracy(Y_pred, Y_label):
# This function calculates prediction accuracy
acc = 1 ... |
24175b5d498c925f6a5896f4ee8cbcf51acccac8 | wildenali/RaspberryPi-Basic | /14-OpenCV/p-draw-rectangle.py | 965 | 3.65625 | 4 | import cv2
img = cv2.imread("myimage.jpg")
# draw rectangle on image, cv2.rectangle(<image>, (x0,y0), (xt,yt), (B, G, R), thickness)
# (x0,y0) : Vertex of the rectangle,
# (xt,yt) : Vertex of the rectangle opposite (x0,y0)
cv2.rectangle(img,
(15,25), # Vertex of the rectangle (top-left-corner rec... |
03f02ed041e4535331c551ed3f4416249fcfd968 | ChrisKneller/fundamentals | /sorting/quicksort.py | 1,005 | 4.09375 | 4 | import random
def quicksort(iterable):
'''
Return a new list containing all items from the iterable in ascending order.
This version takes the pivot to be the last item in an iterable.
'''
low = 0
high = len(iterable)-1
if high <= 0:
return iterable
return quicksorter(iterabl... |
66d0baf598971a7a362e5fb51c6db57c3dc31ce1 | pullannagari/python-training | /HelloWorld/strings.py | 551 | 4.03125 | 4 | print("It is a good day to learn python")
print("we can use python's single quote inside double quotes")
print('we can also use python"s double quote inside single quotes')
print('hello' + " world")
greeting = "Hello"
name = "Sharmila"
nameInput = input('Please enter a name')
print(greeting + ' ' + nameInput)
# data t... |
3f2832d039f29ef99679e8c51d42f5fb08b1dcff | pullannagari/python-training | /ProgramFlow/contrived.py | 425 | 4.21875 | 4 | # con·trived
# /kənˈtrīvd/
# Learn to pronounce
# adjective
# deliberately created rather than arising naturally or spontaneously.
# FOR ELSE, else is activated if all the iterations are complete/there is no break
numbers = [1, 45, 132, 161, 610]
for number in numbers:
if number % 8 == 0:
#reject the lis... |
d99494ac87348c5d674af9c10c23fbf7e8aa1a7d | pullannagari/python-training | /Sequences/lists_intro.py | 575 | 3.859375 | 4 | computer_parts = ["computer",
"monitor",
"keybord",
"mouse",
"mouse mat"]
print(computer_parts)
# computer_parts[3] = "trackball"
print(computer_parts[3:])
computer_parts[3:] = ["trackball"]
print(computer_parts)
# for part in computer_parts:
# ... |
7f9b228de7c12560ac80445c6b1a4d7543ddc263 | pullannagari/python-training | /Functions_Intro/banner.py | 1,312 | 4.15625 | 4 | # using default parameters,
# the argument becomes
# optional at the caller
def banner_text(text: str = " ", screen_width: int = 60) -> None:
"""
centers the text and prints with padded ** at the start and the end
:param text: string to be centered and printed
:param screen_width: width of the screen on... |
593459f7dcdb6a76ed92378d2041b3bf018a81e9 | pullannagari/python-training | /HelloWorld/repfields.py | 495 | 4.03125 | 4 | age = 24
print("My age is " + str(age) + " years") # coerce int to str
print("My age is {0} years".format(age)) # doesn't coerce int to str
print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6} and {7}".format(31, "Jan", "Mar", "May", "Jul", "Aug", "Oct",
... |
b8f22de999eefd642c9de7d444d89c81820a1dde | marcelblijleven/adventofcode2020 | /day10/test_solution.py | 552 | 3.5625 | 4 | from unittest import TestCase
from day10.solution import find_differences, TEST_INPUT
class TestFindDifferences(TestCase):
def test_find_differences(self):
lst = [1, 2, 3, 6, 8, 9]
differences = find_differences(lst)
self.assertEqual([1, 1, 1, 2, 3, 2, 1, 3], differences)
def test_fin... |
a71f9961d5dfed426e3a83ec77d3ce12a8f1526a | pirsquare4/NPHard | /solver.py | 7,670 | 3.609375 | 4 | import networkx as nx
import numpy as np
import operator as op
import copy
import os
###########################################
# Change this variable to the path to
# the folder containing all three input
# size category folders
###########################################
path_to_inputs = "./all_inputs"
###########... |
17a1a39c578111a972d7af6794303ae58ec33af8 | lassefolkersen/highfrontier | /market_decisions.py | 44,505 | 3.75 | 4 | import global_variables
import datetime
import primitives
import random
import string
import company
class market_decisions:
"""
Class that holds all the algorithms pertaining to market decision.
The class consists of self dictionaries, organized by theme:
pick_reseach
sta... |
b69a9014bd4442b4e0d130d8ce97d8a2197cedae | lassefolkersen/highfrontier | /branches/mgodfrey1981/src/highfrontier/hscrollbar.py | 10,601 | 3.59375 | 4 | import math
import global_variables
import pygame
import primitives
import time
import random
class hscrollbar():
def setRect(self,r):
self._rect=r
return
def rect(self):
return self._rect
def __init__(self,surface, function, topleft, length_of_bar_in_pixel, range_of_values, range_... |
ecac6c5b680be4dbd29a237ca4660fe6dbf755da | bsedg/sandbox | /travelling-salesman/map.py | 495 | 3.734375 | 4 | #!/usr/bin/env python
import sys
from math import sqrt, pow
def distance(x1, y1, x2, y2):
return sqrt(pow((x1 - x2),2.0) + pow((y1 - y2),2.0))
# input comes from standard input
for line in sys.stdin:
line = line.strip()
name1, x1, y1, name2, x2, y2 = line.split(',', 5)
try:
x1 = float(x1)
... |
232c40b3f47c42c8a33fcc5d7e4bde2719969080 | Hemalatah/Python-Basic-Coding | /Practice2.py | 2,684 | 4.125 | 4 | #CRAZY NUMBERS
def crazy_sum(numbers):
i = 0;
sum = 0;
while i < len(numbers):
product = numbers[i] * i;
sum += product;
i += 1;
return sum;
numbers = [2,3,5];
print crazy_sum(numbers);
#FIND THE NUMBER OF PERFECT SQUARES BELOW THIS NUMBER
def square_nums(max):
num = 1;
count = 0;
while num < max:
produ... |
1ba2daae4ad916e06b92b9277ca113d64bbd3a84 | miss-faerie/Python_the_hard_way | /ex3.py | 507 | 4.25 | 4 | hens = int(25+30/6)
roosters = int(100-25*3%4)
eggs = int(3+2+1-5+4%2-1/4+6)
print()
print("I will now count my chickens:")
print("Hens",hens)
print("Roosters",roosters)
print("Now I will count the eggs:",eggs)
print()
print("Is it true that 3+2 < 5-7 ?",(3+2)<(5-7))
print("What is 3+2 ?",3+2)
print("What is 5-7 ?",5... |
57cd92be27fd020a630b0349c24731a5d2c6a43c | achkataa/Python-Advanced | /ErrorHandling/2.Repeat Text.py | 205 | 4 | 4 | def repeat_text(text, times):
return text * times
try:
text = input()
times = int(input())
print(repeat_text(text, times))
except ValueError:
print("Variable times must be an integer") |
61257f182e1e56bada9fc19d6c2fc1e04cc072a0 | achkataa/Python-Advanced | /Comprehensisons/4.Flattening Matrix.py | 314 | 3.671875 | 4 | size = int(input())
matrix = []
for i in range(size):
line = [int(r) for r in input().split(", ")]
matrix.append(line)
#FIRST WAY
# result_ll = []
#
# result = [[result_ll.append(el) for el in line] for line in matrix]
#
# print(result_ll)
#SECOND WAY
print([x for row in matrix for x in row])
|
a27446459e38c382c0ef49057b85e6dfe2359105 | achkataa/Python-Advanced | /Lists As Stacks and Queues/1.Reverse Strings.py | 102 | 3.84375 | 4 | string = input()
s = []
for char in string:
s.append(char)
while s:
print(s.pop(), end="") |
596b2e3268e8d8b8edcf35268c8dc94d8a0d37d7 | achkataa/Python-Advanced | /Comprehensisons/2.No Vowels.py | 137 | 4 | 4 | string = input()
vowels = ["a", "A", "o", "O", "u", "U", "e", "E", "i", "I"]
print(''.join([i for i in string if i not in vowels]))
|
20f1fb2273fd5575d6465f65a6696fe8910b5fc7 | achkataa/Python-Advanced | /Comprehensisons/9.Bunker.py | 2,356 | 3.671875 | 4 | # food_categories = {category: ([], [], []) for category in input().split(", ")}
#
# n = int(input())
#
# for i in range(n):
# category_and_product = input().split(" - ")
# current_category = category_and_product[0]
# product = category_and_product[1]
# quantity_and_quality = category_and_product[2].spl... |
36cf32ef264b006a5890598ee88402b21916937f | achkataa/Python-Advanced | /Lists As Stacks and Queues/Cups and Bottles.py | 1,021 | 3.578125 | 4 | from collections import deque
cups = [int(cup) for cup in input().split()]
cups = deque(cups)
bottles = [int(bottle) for bottle in input().split()]
wasted_water = 0
cups_left = []
bottles_left = []
while cups:
cup = cups[0]
if bottles:
bottle = bottles.pop()
if bottle < cup:
c... |
55e136a4bc7dc3170e38564c14f8ffe09bd16bdd | achkataa/Python-Advanced | /Functions Advanced/5.Odd or Even.py | 352 | 4.125 | 4 | command = input()
numbers = [int(num) for num in input().split()]
def print_results(nums):
print(sum(nums) * len(numbers))
def needed_numbers(nums):
if command == "Odd":
nums = [num for num in nums if num % 2 != 0]
else:
nums = [num for num in nums if num % 2 == 0]
print_results(nums)... |
5a32daf0b947e3cdc017bf4c73c87c467c936c0c | achkataa/Python-Advanced | /FileHandling/5.Word Count.py | 740 | 3.625 | 4 | # import re
import re
def assign_changes_to_file(res):
with open("output.txt", "w") as file:
file.writelines("\n".join(res))
def check_if_words_in_text(words, text_in_file):
result_dict = {}
for word in words:
if word in text_in_file:
result_dict[word] = text_in_file.count(wo... |
1043dec7f7919b246a93a3c87427140d5dfc987d | Zebralt/pyutils | /cameo.py | 2,234 | 3.609375 | 4 | from functools import wraps
"""
A decorator could only perform side effect operations, such as
checking that a value exists in a global dictionary, but you
can really do anything with them, including messing with the
arguments passed to the function.
The thing is, in the case where argument order matters, you
have ... |
16e176e7b1f43c5c78feea53472ad5cdf2949955 | tsabz/ITS_320 | /Option #2: Repetition Control Structure - Five Floating Point Numbers.py | 1,321 | 4.25 | 4 | values_dict = {
'Module 1': 0,
'Module 2': 0,
'Module 3': 0,
'Module 4': 0,
'Module 5': 0,
}
# first we want to have the student enter grades into set
def Enter_grades():
print('Please enter your grade for Module 1:')
values_dict['Module 1'] = int(float(input()))
print('Please enter y... |
fe19bd77f75d828d0f20f6241e82a113f3989881 | nishio/atcoder | /abc177/d1.py | 1,899 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
def debug(*x):
print(*x, file=sys.stderr)
def find_root(x):
p = parent[x]
if p == -1:
return x
p2 = find_root(p)
parent[x] = p2
return p2
def unite(x, y)... |
3030f4224c9bd148b16b0a0951e54e797d4a660c | nishio/atcoder | /abc171/c.py | 650 | 3.65625 | 4 | from string import ascii_lowercase
def solve(N):
"""
>>> solve(2)
b
>>> solve(27)
aa
>>> solve(703)
aaa
"""
q = N
ret = ""
while True:
q, r = divmod(q - 1, 26)
ret = ascii_lowercase[r] + ret
if q == 0:
print(ret)
return
def ... |
5de36d0999953a504b949d457591d9c801fa221d | nishio/atcoder | /libs/unionfind.py | 2,280 | 3.71875 | 4 | """
Union-Find Tree / Disjoint Set Union (DSU)
"""
def init_unionfind(N):
global parent, rank, NUM_VERTEX, num_edges, num_vertex
NUM_VERTEX = N
parent = [-1] * N
rank = [0] * N
num_edges = [0] * N
num_vertex = [1] * N
def find_root(x):
p = parent[x]
if p == -1:
return x
p... |
fd1a247f2bca441033071c39b3e4bd6ef641b761 | nishio/atcoder | /abc175/a.py | 170 | 3.84375 | 4 | def main():
X = input().strip()
if X == "RRR":
return 3
if "RR" in X:
return 2
if "R" in X:
return 1
return 0
print(main())
|
132190f2987267ad7665f38bbe638b8fc95a2733 | nishio/atcoder | /libs/graph_to_tree.py | 474 | 3.6875 | 4 | def graph_to_tree(N, edges, root):
from collections import defaultdict
children = defaultdict(list)
parents = [None] * N
root = 0
parents[root] = root
stack = [root]
while stack:
v = stack.pop()
for u in edges[v]:
if parents[u] is not None:
# alrea... |
28437d6ed76d6eed3e956cceda3a859cfa7728eb | nishio/atcoder | /abc191/f.py | 2,238 | 3.515625 | 4 | # included from libs/divisor.py
"""
get all divisors
"""
def get_divisors(n, includeN=True):
"""
>>> get_divisors(28)
[1, 2, 4, 7, 14, 28]
>>> get_divisors(28, includeN=False)
[1, 2, 4, 7, 14]
Derived from https://qiita.com/LorseKudos/items/9eb560494862c8b4eb56
"""
lower_divisors, upp... |
e541e59c574b6743a8489ffcb464ca24435448a2 | nishio/atcoder | /yosupo/shortest_path_2.py | 2,668 | 3.765625 | 4 | # included from libs/dijkstra.py
"""
Shortest Path (Dijkstra)
edges: dict<from:int, dict<to:int, cost:number>>
"""
from heapq import heappush, heappop
def shortest_path(
start, goal, num_vertexes, edges,
INF=9223372036854775807, UNREACHABLE=-1):
distances = [INF] * num_vertexes
prev = [None... |
2f1b2957ef91fd18716ff29424d13d429980aeb6 | cjycjycjy/cjy | /PLec7/PLec7/PLec7.py | 1,648 | 3.90625 | 4 |
from abc import ABCMeta,abstractmethod
class Terran(metaclass = ABCMeta):
def __init__(self,name):
self.name = name
@abstractmethod
def attack(self):
pass
class Tank(Terran):
def __init__(self, name, damage):
super().__init__(name)
self.damage = damage
def a... |
d47a9c0166f5e11ce7c08d31312f7acab9341b35 | jishamu8/Python | /paritat.py | 984 | 3.625 | 4 | def paritat():
numero=int(input("Indica un numero:"))
if numero % 2 == 0:
print("Es parell")
else:
print("Es senar")
def construir_matriu(n, m):
M = []
for i in range (n):
f=[]
for j in range(m):
f.append(0)
M.append(f)
return M
def escriure_... |
3961933710251d0c651f1b335d6b4b0e8839c701 | jishamu8/Python | /ordenar.py | 597 | 3.5 | 4 | def ordenat(v):
n=len(v)
for i in range(n-2):
if v[i] >= v[i+1]:
return "no"
return "si"
def ordenar(v):
n = len(v)
for i in range(n):
for j in range(n):
if i<j:
# si i<j es cierto quiere ecir que el elemento v[i]
# ... |
4efcb42032d71cb296b7845688ca139bdcbed835 | canibal/Course6 | /final/report_email.py | 1,664 | 3.5 | 4 | #!/usr/bin/env python3
"""Main functionality."""
import os
import datetime
import reports
import emails
def load_data(directory, file_list):
"""Load the contents of filename as a JSON file."""
data = []
for x in file_list:
item = []
with open(os.path.join(directory, x), 'r') as f:
... |
524cce821d5a7025f6f6419da0691796d84110ab | js-glass/First-Text-Game | /encounters.py | 11,653 | 3.75 | 4 | """ === Travel=== """
import random, time, items, player, enemies, events
player = player.hero
def travel_chance(nsew):
""" REDO THIS ENTIRE FUNCTION! """
chance = random.randint(0, 1000)
if chance < 665:
time.sleep(1)
print("You travel a mile {}".format(nsew))
elif chance >= 665 and chan... |
4a75eccabd9c8af8f54613b74df0e33bc6545d90 | aadilshabier/jeepercentile | /main.py | 932 | 3.75 | 4 | import matplotlib.pyplot as plt
import numpy as np
from config import starting_rank, ending_rank, \
no_of_plots, expected_students_lower, expected_students_upper, style
def percentile(x, rank):
return (x-rank)/x*100
def main():
x = np.arange(expected_students_lower, expected_students_upper+1, 10000)
... |
407b1a366ea1e151ed161b38b3a89aa8d5a8b605 | xshi0001/base_function | /tushare_offline.py | 938 | 3.796875 | 4 | # -*-coding=utf-8-*-
__author__ = 'Rocky'
import pandas as pd
import datetime
from pandas import DataFrame
def getData():
filename = "300333.csv"
df = pd.read_csv(filename)
date = df['date']
print date
# df1=df.drop(0)
#print df1
df1 = df.set_index('date')
#print df.index.values
pr... |
e85171d8373bce8c2d58614177e818bcc92d8be3 | xshi0001/base_function | /time_function.py | 4,810 | 3.984375 | 4 | # -*-coding=utf-8-*-
# 日期函数的使用
import time, datetime
class Data_test(object):
day = 0
month = 0
year = 0
def __init__(self, year=0, month=0, day=0):
self.day = day
self.month = month
self.year = year
def out_date(self):
print "year :"
print self.year
... |
4c9363dcaff5b09b63b0a502b4361e55db1fc21b | xshi0001/base_function | /inherit_test.py | 708 | 4.03125 | 4 | # -*-coding=utf-8-*-
__author__ = 'Rocky'
'''
http://30daydo.com
Contact: weigesysu@qq.com
'''
#注意这里需要用object, 这样定义的class是新类,基于python3的
class base(object):
def __init__(self):
print "base constructor"
def foo(self):
print "base foo"
class base2():
def __init__(self):
print "base2 ... |
c95146a4e60c1a943fcdedc455a9453de9b1bc56 | AdrianMusungu/Data-Analysis-Basics | /5. Data Analysis Techniques and Methodologies/pivot-tables.py | 431 | 3.625 | 4 | import numpy as np
import pandas as pd
from pandas import Series, DataFrame
url = "https://en.wikipedia.org/wiki/Pivot_table"
df_list = pd.io.html.read_html(url)
df = df_list[0]
#print df
new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header... |
b6ac5776ba35a25d2709100debbb5e72cf5818bf | RZachLamberty/project_euler | /p17.py | 1,963 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
module: p17.py
author: Zach Lamberty
created: 2014-02-16
Description:
If the numbers 1 to 5 are written out in words: one, two, three, four,
five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand... |
612986aae25a4019eacb7a37c1d58a6ad0262689 | RZachLamberty/project_euler | /p14.py | 1,379 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
module: p14.py
author: Zach Lamberty
created: 2014-02-16
Description:
The following iterative sequence is defined for the set of positive
integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we ge... |
73acd31b06ff39348e9b2af300e270fce5c3810c | RZachLamberty/project_euler | /p28.py | 1,261 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
module: p28.py
author: Zach Lamberty
created: 2014-02-22
Description:
Starting with the number 1 and moving to the right in a clockwise direction
a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
... |
cd0549076b296c935267de5ded6ed84f45a7448f | RZachLamberty/project_euler | /p32.py | 1,362 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
module: p32.py
author: Zach Lamberty
created: 2014-02-23
Description:
We shall say that an n-digit number is pandigital if it makes use of all
the digits 1 to n exactly once; for example, the 5-digit number, 15234, is
1 through 5 pandigital.
The produ... |
d43b5d75e51af529a407a70b04ef9eaf890b8495 | RZachLamberty/project_euler | /p44.py | 4,126 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
module: p44.py
author: Zach Lamberty
created: 2014-03-09
Description:
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first
ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 2... |
0df12a3d9516f91d7be6cf6a13623974a303a972 | deep094/chongshui | /004.py | 847 | 3.875 | 4 | '''year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
leap = 0
sum = 0
months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
if 0 < month <= 12:
sum = months[month - 1]
sum += day
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
leap = 1... |
978229a911aca7c02d6554ddde27242498717752 | soomok-lee/python_examples | /network/mixin.py | 495 | 3.53125 | 4 | '''
mixin
'''
class CarMinIn:
def ready(self):
print("mixin ready")
def start(self):
print("{} {}".format(self.name, self.speed))
class Performance:
def __init__(self, name, speed):
self.name = name
self.speed = speed
self.ready()
class SuperCar(CarMinIn, Performanc... |
32a0f6a59ac57797ddd20e70d54bd9d4bd583854 | akocur/education | /Coffee Machine/Problems/Difference of times/task.py | 303 | 3.78125 | 4 | # put your python code here
hours_start = int(input())
minutes_start = int(input())
seconds_start = int(input())
hours_end = int(input())
minutes_end = int(input())
seconds_end = int(input())
print((hours_end - hours_start) * 3600 + (minutes_end - minutes_start) * 60 + (seconds_end - seconds_start))
|
9739a809b2b56d02e69a71a4e54a4a13f64b4fcb | akocur/education | /Tic-Tac-Toe/Problems/CapWords/task.py | 81 | 3.640625 | 4 | words = [word.capitalize() for word in input().split('_')]
print(''.join(words))
|
870644203e799700ef78b960bd619a5dcd3e6a83 | akocur/education | /Tic-Tac-Toe/Tic-Tac-Toe/task/tictactoe/tictactoe.py | 3,366 | 3.640625 | 4 | class TicTacToe:
def __init__(self, data='_' * 9):
self.cells = [[data[i * 3 + j] for j in range(3)] for i in range(3)]
self.state = 'Game not finished'
self.players = {'X': [False, 0], # [is_win, count]
'O': [False, 0]}
self.current_player = 'X'
def di... |
0c03a44fd734e2adeb4a58fc539d3b7d1ebd67a4 | akocur/education | /Coffee Machine/Problems/Tax brackets/task.py | 298 | 3.875 | 4 | def percent(income_):
if income_ >= 132407:
return 28
if income_ >= 42708:
return 25
if income_ >= 15528:
return 15
return 0
income = int(input())
print(f'The tax for {income} is {percent(income)}%. That is {income * percent(income) / 100:.0f} dollars!')
|
31cec44417058d604b67a19c897310dcb23fd153 | adam-gomez/codeacademy-practice | /pandas_intro.py | 7,248 | 3.859375 | 4 | import pandas as pd
df1 = pd.DataFrame({
'name': ['John Smith', 'Jane Doe', 'Joe Schmo'],
'address': ['123 Main St.', '456 Maple Ave.', '789 Broadway'],
'age': [34, 28, 51]
})
df1 = pd.DataFrame({
'Product ID': [1, 2, 3, 4],
# add Product Name and Color here
'Product Name': ['t-shirt', 't-shirt', 's... |
6287c6f103b4b4acb1ccaa5b0dce40253d8d8b11 | gladlyunicorn/march-hols | /assignments/03-minigame.py | 691 | 3.859375 | 4 | import random
numberofGuesses = 0
number = random.randint(1,100)
print("I'm thinking of a number between 1-100. You have 7 guesses.")
while numberofGuesses < 7:
guess = raw_input(" guess ")
guess = int(guess)
numberofGuesses = numberofGuesses + 1;
guessesLeft = 7 - numberofGuesses;
if guess < number:
... |
58a59c40ca3039766fb86d513e258c9fe9e4e234 | davidfliu/SearchAlgorithms | /pythonSearchAlgorithms.py | 3,283 | 4.25 | 4 | import random
#Linear search program that takes a list and a search value
#with a return value of true or false depending if the search value was found.
def linear(aList, searchValue):
i = 0
count = 0
size = len(aList)
while i < size:
if aList[i] == searchValue:
count += 1
return True, count #Returns tr... |
e41f075f270ab861ac1ea79602f25f0b1f06f91c | markgjackson/dsp | /python/advanced_python_regex.py | 2,089 | 3.59375 | 4 | import csv
f = open('faculty.csv')
csv_f = csv.reader(f)
# DegreeList=["PhD","ScD","MD","JD","BSEd"]
degreeList=[]
frequencyList=[]
for row in csv_f:
# print row
cleanedDegrees=row[1].replace(".","")
wordDegree = ""
for char in cleanedDegrees:
if char != " ":
wordDegree = wordDegree + char
# ... |
78cdac06fa71e43ee155f47e262af89cff166640 | hecris/TechnicalInterviewPrep2020 | /assignments/week2/day2/Christopher_He_LC_24.py | 527 | 3.578125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
def solution(head):
if not (head and head.next):
return head
... |
a4b156047ad02df98ddb1cd62cc2a2d606d5cf9c | hecris/TechnicalInterviewPrep2020 | /assignments/week2/day1/Christopher_He_LC_509.py | 296 | 3.6875 | 4 | # Fibonacci Number
class Solution:
def fib(self, N: int) -> int:
first = 0
if N == 0:
return first
second = 1
for i in range(2, N + 1):
sum = first + second
first = second
second = sum
return second
|
d76602a4ba3f1386810b14ed5a153ed3ce398a5f | kamillys/cucs_demo | /examples/is_sorted.py | 282 | 3.515625 | 4 | #!/usr/bin/python
import os,sys
import fileinput
prev = 0
isSorted = True
fails = 0
for line in fileinput.input():
cur = int(line, 2)
if prev > cur:
isSorted = False;
fails = fails + 1
prev = cur
print isSorted
if not isSorted:
print "Fails", fails |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.