blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
651416b2a4ea2345de5a02e3c2e5b31cfbf454ba | 0xRamadan/IEEE-Rookies-30-Day-Program | /IEEE_Rookies_30_Days_program/IEEE_Rookies_task_06_part_02.py | 552 | 4.25 | 4 | # IEEE_Rookies_task_06_part_01
# name: Mahmoud_Ramadan
# task: find a string
def count_substring(string, sub_string):
c = 0
str_len = len(string)
sub_len = len(sub_string)
for i in range(str_len - sub_len + 1):
if (string[i:(i + len(sub_string))] == sub_string):
c = c + 1
return c
if __name__ == '__main__':
string = input("enter a string: ").strip()
sub_string = input("enter a substring: ").strip()
count = count_substring(string, sub_string)
print(count)
input('press enter to exit...')
|
d61e6c78e8457ff4fc6fb4bd5e78533f386f4a90 | chosaihim/jungle_codingTest_study | /FEB/15th/예은_짝지어제거하기.py | 398 | 3.6875 | 4 | def solution(s):
answer = 0
stack = []
for one in s:
if len(stack) == 0:
stack.append(one)
elif stack[-1] == one:
stack.pop()
else:
stack.append(one)
answer = 1 if len(stack) == 0 else 0
return answer
s = "baabaa"
# s = "cdcd"
# s = "aaaaaaaaaaaaaaaaaaaaabbaaaaaaaaabbbbbbaaaaaaabbaaaaaaaaabbbb"
print(solution(s))
|
f69992682b0f93461b8f956fb43e61fec2321b4f | umunusb1/PythonMaterial | /python3/13_OOP/34_singleton_design_pattern.py | 661 | 4 | 4 | #!/usr/bin/python
"""
Purpose: To create a class with singleton design pattern
It means, If an instance of that class is already created,
Instead of creating new instance, make use of already created instance
"""
from pprint import pprint
# Question: __new__ vs __init__
# baby born => __new__
# baby named => __init__
class Logger(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_logger'):
cls._logger = super(Logger, cls).__new__(cls, *args, **kwargs)
return cls._logger
l1 = Logger()
pprint(vars(Logger))
print(f'l1:{l1}')
print(vars(l1))
l2 = Logger()
print(id(l1), id(l2))
assert l1 is l2
|
5697d14d00d23be9f1a649d62501d06af5613db1 | Tifinity/LeetCodeOJ | /105.从前序与中序遍历序列构造二叉树.py | 551 | 3.65625 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
if not preorder:
return None
root = TreeNode(preorder[0])
#print(root.val)
i = inorder.index(root.val)
root.left = self.buildTree(preorder[1:i+1], inorder[:i])
root.right = self.buildTree(preorder[i+1:], inorder[i+1:])
return root
s = Solution()
a = s.buildTree([3,9,20,15,7], [9,3,15,20,7]) |
d6c91d78b45e4bf40b25f94cf9dcbeca41238feb | viniciusjulianirossi/Python | /Comprehension e Funções Integradas/Any_and_all.py | 1,117 | 4.15625 | 4 | """
Any e All
all() retorna True se todos os elementos do iteravel são verdadeiros ou ainda se o iteravel está vazio
"""
# Exemplo all()
print(all([0,1,2,3,4,3])) # Todos os numeros são verdadeiro: False
print(all([1,2,3,4,3])) # Todos os numeros são verdadeiro: True
print(all([])) #Todos os numeros são verdadeiro: True
print(all({1,2,3,4,3})) # Todos os numeros são verdadeiro: True
nomes = ["Carlos", "Camila", "Carla", "Cassioano" , "Cristina" ]
print(all([nome[0] == 'C' for nome in nomes]))
print(all([letra for letra in "eio" if letra in "aeiou"])) # Obs: um iteravel vazio convertido é False, mas o all() entende como True
print(all([num for num in [4,2,10,6,8] if num%2 == 0]))
"""
Any, Retorna True se qualquer elemento do iteraval for verdadeiro, se o iteravel estiver vazio, retorna True
Any- "algum"
"""
print(any([1,2,3,4,5,6])) # True
print(any([0,0,0,0,0])) # False
print(any([0,0,0,0,1])) # True
nomes = ["Carlos", "Camila", "Carla", "Cassioano", "Cristina" , "vanessa"]
print(any([nome[0] == 'a' for nome in nomes ]))
print(any([num for num in [4,2,10,6,8,9] if num %2 == 0]))
|
22289714ea2fbe425879687cb94416a2cd1ce004 | idealgupta/pythgon-practis | /ifelif3.py | 477 | 3.84375 | 4 | #discount
bill_amount=int(input("enter the amount : "))
if bill_amount>=5000:
bill_amount=bill_amount - 500
elif bill_amount>=4000 and bill_amount<=4999:
bill_amount=bill_amount - 400
elif bill_amount>=3000 and bill_amount<=3999:
bill_amount=bill_amount - 300
elif bill_amount>=2000 and bill_amount<=2999:
bill_amount=bill_amount - 200
elif bill_amount>=1000 and bill_amount<=999:
bill_amount=bill_amount -100
print("final amount ",bill_amount) |
e5498a3759f01f423d61279f1839106f15496a73 | tylerbrowndev/aoc2020 | /3.py | 593 | 3.625 | 4 | f = open("input/3.txt", "r")
lines = f.readlines()
forest = []
for line in lines:
forest.append([c for c in line.strip()])
x_len = len(forest[0])
y_len = len(forest)
# part 1
trees = 0
x = 0
y = 0
while y < y_len - 1:
x = (x + 3) % x_len
y += 1
if forest[y][x] == '#':
trees += 1
print(trees)
# part 2
slopes = [ [1,1], [3,1], [5,1], [7,1], [1,2] ]
product = 1
for slope in slopes:
trees = 0
x = 0
y = 0
while y < y_len - 1:
x = (x + slope[0]) % x_len
y += slope[1]
if forest[y][x] == '#':
trees += 1
print(trees)
product *= trees
print(product) |
2ab55c24620fa4ed54555e827693530452ba9a1a | Day-bcc/estudos-python | /02-recursos_avancados/manipulando-arquivos/armazenameto-with.py | 247 | 3.59375 | 4 | #Armazenando dados de arquivos dentro de variáveis
#readlines() -> armazena cada linha do arquivo em uma lista
arquivo = 'numeros.txt'
with open(arquivo) as numeros:
linhas = numeros.readlines()
for linha in linhas:
print(linha.rstrip()) |
8c9a96fa6bb2b8826252ddbfb54db35472108a38 | DimitarPetrov77/py-course | /conditional_statements/Greater number.py | 191 | 4.125 | 4 | num1 = int(input('Enter first number:'))
num2 = int(input('Enter second number: '))
if num1 > num2:
print('Greater number: ' + str(num1))
else:
print('Greater number: ' + str(num2))
|
897514f549187bdb15cfe050ed60c70c30256c0c | Yuvv/LeetCode | /0501-0600/0535-encode-and-decode-tinyurl.py | 839 | 3.703125 | 4 | import binascii
import hashlib
class Codec:
"""
https://leetcode.com/problems/encode-and-decode-tinyurl/
编码/解码 url
"""
def __init__(self):
self.urls = {}
self.salt = 'Ax97'
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
crc32_sum = binascii.crc32((self.salt + longUrl).encode())
self.urls[crc32_sum] = longUrl
return crc32_sum
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.urls.get(shortUrl)
if __name__ == "__main__":
codec = Codec()
e = codec.encode('https://leetcode.com/problems/design-tinyurl')
print(e)
print(codec.decode(e))
|
68102f5a87ce1fb7256b8b8a45df5d1746ed3da8 | Tiyasa41998/py_program | /list.py | 157 | 4.1875 | 4 | MyList=[1,2,3,4,2,5,3,7]
print(MyList)
NewList=[]
for i in (MyList):
if i not in NewList:
NewList.append(i)
print(NewList)
|
12e8f9bfb5aa3fc8e0bf6fd0a6cb2537e20c60f6 | Bwade95/Enrollment-Problem | /person.py | 817 | 4.03125 | 4 | from address import Address
class Person:
def __init__(self, firstName, lastName, dob, phoneNum, address):
self.first_name = firstName
self.last_name = lastName
self.date_of_birth = dob
self.phoneNum = phoneNum
self.addresses = []
if isinstance(address, Address):
self.addresses.append(address)
elif isinstance(address, list):
for entry in address:
if not isinstance(entry, Address):
raise NameError("Invalid Address...")
self.addresses = address
else:
raise NameError("Invalid Address...")
def add_address(self, address):
if not isinstance(address, Address):
raise NameError("Invalid address...")
self.addresses = address
|
f73be97bfeeed6f010d097d6c84b8524eda68914 | AndrianDenys/Labs | /dz_1.py | 3,770 | 3.953125 | 4 | #1
class Classroom(Object):
def __init__(self, number, capacity, equipment):
self.number = number
self.capacity = capacity
self.equipment = equipment
def is_larger(self, classroom):
if self.capacity is > classroom.capacity:
return True
else:
return False
def equipment_differences(self, classroom):
i = 0
res = []
while i < len(self.equipment):
if self.equipment[i] is not in classroom.equipment:
res.append(self.equipment[i])
i+= 1
else:
i += 1
def str(self):
print "Classroom %s has a capacity of %s persons and has the following equipment: %s. " % (self.number, self.capacity, self.equipment)
def repr(self):
a = "Classroom(%s, %s, %s)" %(self.number, self.capacity, self.equipment)
return a
#2
class AcademicBuilding(Building):
def __init__(self, adress, classrooms):
super(self.__class__, self).__init__(adress)
self.classrooms = classrooms
def total_equipment(self, classrooms):
total = []
i = 0
j = 0
while i < len(classrooms):
while j < len(self.classrooms[i].equipment)
total.append(self.classrooms[i].equipment[j])
j += 1
i += 1
j = 0
def str(self, classrooms):
print(self.adress)
i = 0
while i < len(self.classrooms):
classrooms[i].repr()
i += 1
#3
class Point:
'Represents a point in two-dimensional geometric coordinates'
def __init__(self, x=0, y=0):
'''Initialize the position of a new point. The x and y coordinates can be
specified. If they are not, the point defaults to the origin.'''
self.move(x, y)
def move(self, x, y):
"Move the point to a new location in 2D space."
self.x = x
self.y = y
def rotate(self, beta, other_point):
'Rotate point around other point’
dx = self.x - other_point.get_xposition()
dy = self.y - other_point.get_yposition()
beta = radians(beta)
xpoint3 = dx * cos(beta) - dy * sin(beta)
ypoint3 = dy * cos(beta) + dx * sin(beta)
xpoint3 = xpoint3 + other_point.get_xposition()
ypoint3 = ypoint3 + other_point.get_yposition()
return self.move(xpoint3, ypoint3)
def get_xposition(self):
return self.x
def get_yposition(self):
return self.y
#Whatthehell
# def add(self):
# pass
# def iadd(self):
# pass
# def sub(self):
# pass
# def isub(self):
# pass
#4
class Triangle(Object):
def __init__(self, point1, point2, point3):
self.point1 = point1
self.point2 = point2
self.point3 = point3
def is_triangle(self):
#(x - x1)/(x2 - x1) == (y - y1)/(y2 - y1)
# There is always triangle between 3 points EXCEPT this points are on th one line
if (point3.get_xposition() - point1.get_xposition()) / (point2.get_xposition - point1.get_xposition()) == (point3.get_yposition() - point1.get_yposition()) / (point2.get_yposition - point1.get_yposition()):
return False
else:
return True
def perimeter(self):
import Math
#line = sqrt((x1 - x2)^2 + (y1 - y2)^2)
pass
#5
class Building(Object):
def __init__(self, building, adress):
self.building = building
self.adress = adress
class House(Building):
def __init__(self, adress, rooms):
super(self.__class__, self).__init__(adress)
self.rooms = rooms
|
fc86ae90a3d59d060755fb1e307be7e754c7f681 | kathedore/request_sender | /DBconnection.py | 1,626 | 3.65625 | 4 | import psycopg2
from psycopg2 import pool
query = "INSERT INTO main_table (request, response, request_type) VALUES(%s,%s,%s)"
def database(record_to_insert):
try:
postgreSQL_pool = psycopg2.pool.SimpleConnectionPool(1, 20, user="postgres",
password="annawintour",
host="192.168.50.80",
port = "5432",
database = "dbMeraki")
if(postgreSQL_pool):
print("Connection pool created successfully")
ps_connection = postgreSQL_pool.getconn()
if (ps_connection):
print("successfully recived connection from connection pool ")
ps_cursor = ps_connection.cursor()
ps_cursor.execute(query, record_to_insert)
ps_connection.commit()
count = ps_cursor.rowcount
print(count, "Record inserted successfully into main_table")
# Use this method to release the connection object and send back to connection pool
postgreSQL_pool.putconn(ps_connection)
print("Put away a PostgreSQL connection")
except (Exception, psycopg2.DatabaseError) as error:
print("Error while connecting to PostgreSQL", error)
finally:
#closing database connection.
# use closeall method to close all the active connection if you want to turn of the application
if (postgreSQL_pool):
postgreSQL_pool.closeall
print("PostgreSQL connection pool is closed") |
59df48ba31c73faddca53658b2468f678718182a | hellion86/pythontutor-lessons | /1. Ввод и вывод данных/Следующее и предыдущее.py | 411 | 4.21875 | 4 | '''
Условие
Напишите программу, которая считывает целое число и выводит текст, аналогичный приведенному в примере (пробелы важны!).
'''
num = int(input())
print('The next number for the number '+ str(num) + ' is '+ str(num +1))
print('The previous number for the number '+ str(num) + ' is '+ str(num -1))
|
417bb0e9983ba8a6a95ff4ff2f6212f3251ae508 | kjovan27/RealLife_problem_OOP | /oop.py | 1,554 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 4 13:27:57 2017
@author: Don Quan
"""
class Computer(object):
#"""A real world problem modelled using OOP"""
#initialising a class variable
pcCount = 0
#initialization
def __init__(self, RAM, processor_speed, hardDisk):
self.RAM = RAM
#Data hiding(making variable processor_speed private)
self.__processor_speed = processor_speed
self.hardDisk = hardDisk
Computer.pcCount += 1
def display_specifications(self):
print ('RAM :', self.RAM, 'processor_speed :', self.__processor_speed, 'harddisk :', self.hardDisk)
def print_documents(self):
print ('i can print documents')
pc1 = Computer('2Gb', '2.4Ghz', '500Gb')
pc2 = Computer('4Gb', '2.3Ghz', '1Tb')
pc3 = Computer('8Gb', '2.7Ghz', '2Tb')
pc1.display_specifications()
pc2.display_specifications()
pc3.display_specifications()
print ("Total PCs %d" %Computer.pcCount)
print ("Computer._doc_:", Computer.__doc__)
print ("Computer._name_:", Computer.__name__)
print ("Computer._module_:", Computer.__module__)
print ("Computer._bases_:", Computer.__bases__)
print ("Computer._dict_:", Computer.__dict__)
class mac(Computer):
def print_document(self, colored):
print ("Am overriding method")
overriding = mac()
overriding.print_document()
def mac_open_documents(self):
print ("Mac can open documents")
|
297cd71028f8f743121eb080c4b56e6591b03a83 | Theoblanc/algorithm | /Sort/selectionsort.py | 853 | 3.65625 | 4 | # # 선택정렬
# 최소 값을 선택헤서 정렬 하는 방법
# # 시간복잡도 n^2 for 2번
list = [10, 5, 6, 8, 2, 1]
# def sel_sort(a):
# n = len(a)
# for i in range(0, n - 1):
# min_idx = i
# for j in range(i+1, n):
# if a[j] < a[min_idx]:
# min_idx = j
# temp = a[i]
# a[i] = a[min_idx]
# a[min_idx] = temp
# # a[i], a[min_idx] = a[min_idx], a[i] //둘다 가능
# sel_sort(list)
# print(list)
def selection_sort(arr):
n = len(arr)
for i in range(0, n-1):
min = i
for j in range(i+1, n):
if a[j] < a[min_idx]:
min_idx = j
# temp = a[i]
# a[i] = a[min_idx]
# a[min_idx] = temp
a[i], a[min_idx] = a[min_idx], a[i] // 둘다 가능
selection_sort(list)
print(list)
|
a6e8c6dac15297d5eb16ccbacba1b206147874c8 | TM1066/-Arcane-Aristocracy- | /Spells.py | 1,889 | 3.59375 | 4 | #Internal Files
from Utils import *
from Characters import *
#Class for the Spells in the game
class Spell:
def __init__(self,name,element,manacost,damage,level):
self.name = name
self.element = element
self.manacost = manacost
self.damage = damage
#self.effect = effect - Doing this later, just get 'em Down first
def add(self,Char):
Char.spells.append(self)
def cast(self,Caster,Recipient):
os.system("clear")
#Successful Cast
if Caster.MP >= self.manacost:
Caster.MP -= self.manacost
if self.damage >= 0:
Recipient.HP -= self.damage
elementTXTs[self.element].out(Recipient.name + " took " + str(self.damage) + " Points of Damage!")
elif self.damage < 0:
Recipient.HP += -self.damage
elementTXTs[self.element].out(Recipient.name + " was healed for " + str(-self.damage) + " Points of Damage!")
#Failed Cast
elif Caster.MP < self.manacost:
TXT.out("You don't have enough Mana!")
#if Recipient.attitude = ???peaved???, etc:
#RecipientTXT.out("MY GUY I AM SOOOAKED.")
#Ya get it.
#Could roll this feature into elemental stuff, so, for example, water spells do get reaction related to water and fire about being singed or something without having to write a new reaction for each spell. Help to speed up development. Intensity levels? Like, a spell could have an intensity level of between 1:3 and then I could just write 3 reactions for each attitute at each level per element? Maybe.
pass
def print(self):
elementTXTs[self.element].out(self.name + ", Damage: " + str(self.damage))
#Test Spells
#FIRE
Fireball = Spell("Fireball","Fire",1,3,1)
#WATER
Waterball = Spell("Waterball","Water",1,3,1)
#NATURE
Heal = Spell("Heal","Nature",2,-3,1)
#ELECTRIC
Shock = Spell("Shock","Electric",1,3,1)
def updateEffects(Caster,Rival):
pass |
f84852e02446f49a260b6ce07033c309d16b9d9b | ivan-yosifov88/python_basics | /Exams -Training/01. Oscars ceremony.py | 259 | 3.5 | 4 | rent_of_hall = int(input())
statuettes_price = rent_of_hall * 0.7
catering_price = statuettes_price * 0.85
sound_system_price = catering_price / 2
total_money = rent_of_hall + statuettes_price + catering_price + sound_system_price
print(f"{total_money:.2f}")
|
d1cdbf7e05123d70329bb087c9ebef2aa5106d9d | HunterLaugh/codewars_kata_python | /kata_8_Sum_The_Strings.py | 764 | 3.875 | 4 | '''
8 kyu
Sum The Strings
Create a function that takes 2 numbers in form of a string as an input, and outputs the sum (also as a string):
sumStr("4", "5") // should output "9"
sumStr("34", "5") // should output "39"
If either input is an empty string, consider it as zero. If both inputs are empty, output "0".
HINT: Check these links out about parseInt() (Number() is also valid) and .toString(): https://www.w3schools.com/jsref/jsref_parseint.asp (NOTE: Radix is not necessary) https://www.w3schools.com/jsref/jsref_tostring_number.asp
'''
# if empty string is false
def sum_str(a,b):
if a and b:
return str(int(a)+int(b))
elif not a and b:
return b
elif a and not b:
return a
elif not a and not b:
return '0'
|
c1d856bb48373492a8492b281659550821f2f98b | KushalVenkatesh/pycard | /pycard/holder.py | 648 | 3.890625 | 4 | class Holder(object):
"""
A credit card holder.
"""
def __init__(self, first, last, street, post_code):
"""
Attaches holder data for later use.
"""
self.first = first
self.last = last
self.street = street
self.post_code = post_code
def __repr__(self):
"""
Returns a typical repr with a simple representation of the holder.
"""
return u'<Holder name={n}>'.format(n=self.name)
@property
def name(self):
"""
Returns the full name of the holder.
"""
return u'{f} {l}'.format(f=self.first, l=self.last)
|
30b823f9d4d6787160fe4222ae5a9be873dfd568 | felipeonf/Exercises_Python | /curso_py/ex049.py | 351 | 4.03125 | 4 | valores = []
while True:
valor = int(input('Digite um valor: '))
if valor in valores:
print('Valor duplicado, não vou adicionar!')
else:
valores.append(valor)
opcao = input('Deseja continuar(s/n) ?').strip().lower()[0]
if opcao == 'n':
break
print(f'Você digitou os valores {sorted(valores)}')
|
62c4ff63236635d461215c116e30d5338ba3c1ec | bknie1/Code-Challenges | /Valid Parentheses/valid_parentheses.py | 1,155 | 4.25 | 4 | """
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid
but "(]" and "([)]" are not.
"""
def is_valid(test):
"""
:type s: str
:rtype: bool
Replaces all valid pairings with empty strings.
If there's a remaining length it means there was an invalid pair.
True = remaining length, invalid.
False = No remaining length, valid.
"""
length = len(test)
while length != 0 and length % 2 == 0:
test = test.replace("()", "")
test = test.replace("[]", "")
test = test.replace("{}", "")
if length > len(test): # Accounts for replaced values.
length = len(test)
else: # If no change, then we're out of text.
length = 0
return not bool(len(test)) # Remaining length determines validity.
TEST_1 = "(){}[]{}()[]"
TEST_2 = "()[]{]}([})"
TEST_3 = "([])"
TEST_4 = "(("
TEST_5 = "["
print(is_valid(TEST_1))
print(is_valid(TEST_2))
print(is_valid(TEST_3))
print(is_valid(TEST_4))
print(is_valid(TEST_5))
|
7fc998d47d86661f4ad46be64a51a6eb39460166 | UCD-pbio-rclub/Pithon_Michelle.T | /pithon_06272018/pithon_0627_ex2.py | 893 | 4.15625 | 4 | ### 2. Write a function which takes a sentence as input and returns the reverse order of the words. ie "these are words" --> "words are these". Bonus: Capitalize the the first letter of the first word and end the returned string with the same punctuation as the input string. ie "these are words!" --> "Words are these!"
def rev_sent():
sent = input('Sentence to reverse').lower()
if sent[-1].isalpha() == True: #if there is no punctuation
rev_sent = sent.split()[::-1]
rev_sent[0] = rev_sent[0].capitalize() #make first word cap
print(' '.join(rev_sent))
else:
punct = sent[-1]
sent = sent.replace(punct, '')
rev_sentlist = sent.split()[::-1]
rev_sentlist[0] = rev_sentlist[0].capitalize()
print(' '.join(rev_sentlist) + punct)
## flaw if the last character is a number.
## use string punctuation
import string
string punctuation
#if sent[-1] in string punctuation:
|
516993d36ac1faa0a2fc052c45f7202714437bed | KillaTomato1001/MySchoolPrograms | /odd and even.py | 259 | 4.15625 | 4 | n=int(input('upto which number'))
ctr=1
sum_even=sum_odd=0
while ctr<=n:
if ctr%2==0:
sum_even+=ctr
else:
sum_odd+=ctr
ctr+=1
print('the sum of even integers is',sum_even)
print('the sum of odd integers is',sum_odd)
|
bde1f1ca8f898633414b876fec80f04360bde62c | quantrocket-llc/zipline | /zipline/data/_minute_bar_internal.pyi | 2,822 | 3.875 | 4 | def int_min(a, b): ...
def minute_value(market_opens,
pos,
minutes_per_day):
"""
Finds the value of the minute represented by `pos` in the given array of
market opens.
Parameters
----------
market_opens: numpy array of ints
Market opens, in minute epoch values.
pos: int
The index of the desired minute.
minutes_per_day: int
The number of minutes per day (e.g. 390 for NYSE).
Returns
-------
int: The minute epoch value of the desired minute.
"""
...
def find_position_of_minute(market_opens,
market_closes,
minute_val,
minutes_per_day,
forward_fill):
"""
Finds the position of a given minute in the given array of market opens.
If not a market minute, adjusts to the last market minute.
Parameters
----------
market_opens: numpy array of ints
Market opens, in minute epoch values.
market_closes: numpy array of ints
Market closes, in minute epoch values.
minute_val: int
The desired minute, as a minute epoch.
minutes_per_day: int
The number of minutes per day (e.g. 390 for NYSE).
forward_fill: bool
Whether to use the previous market minute if the given minute does
not fall within an open/close pair.
Returns
-------
int: The position of the given minute in the market opens array.
Raises
------
ValueError
If the given minute is not between a single open/close pair AND
forward_fill is False. For example, if minute_val is 17:00 Eastern
for a given day whose normal hours are 9:30 to 16:00, and we are not
forward filling, ValueError is raised.
"""
...
def find_last_traded_position_internal(
market_opens,
market_closes,
end_minute,
start_minute,
volumes,
minutes_per_day):
"""
Finds the position of the last traded minute for the given volumes array.
Parameters
----------
market_opens: numpy array of ints
Market opens, in minute epoch values.
market_closes: numpy array of ints
Market closes, in minute epoch values.
end_minute: int
The minute from which to start looking backwards, as a minute epoch.
start_minute: int
The asset's start date, as a minute epoch. Acts as the bottom limit of
how far we can look backwards.
volumes: bcolz carray
The volume history for the given asset.
minutes_per_day: int
The number of minutes per day (e.g. 390 for NYSE).
Returns
-------
int: The position of the last traded minute, starting from `minute_val`
"""
...
|
373cfbca5a305cc3316cc2707b9551bb1a47bbed | Aragnos/tf_test | /Code/FileConnector.py | 1,976 | 3.625 | 4 | """Opens, closes and writes to file"""
import PyToSh
# todo test all
def open_files(file_list, path, use):
"""
Open all files given in file list and returns the opened file handlers
:param file_list: files, which should be opened, as list
:param path: path to the file location, as string
:param use: 'a' for appending, 'r' for reading a file, as string
:return: file handlers to the opened files, as dictionary
"""
# Dictionary with all opened files
opened_files = {}
for file_name in file_list:
# a lcd can be connected, but has no file
if file_name == "lcd":
continue
file_path = "{0}/{1}.txt".format(path, file_name)
new_file = open(file_path, use)
opened_files.update({file_name: new_file})
return opened_files
def close_files(opened_files):
"""
Closes the given files
:param opened_files: currently opened files, which should be closed, as dictionary
"""
for f in opened_files:
opened_files[f].close()
def write_files(sensor_values, opened_files, timestamp):
"""
Write the sensor values to the opened files
:param sensor_values: the values from sensors, as dictionary
:param opened_files: currently opened files, as dictionary
:param timestamp: timestamp
:return:
"""
for sensor in opened_files:
try:
value = sensor_values[sensor]
write_str = "%s \t %d\n" % (timestamp, value)
opened_files[sensor].write(write_str)
except Exception as e:
print(e)
continue
return
def check_and_return(opened_file):
"""Checks if a file is present and returns its lines
:param opened_file: file, wich should be checked
:return: lines of the file
"""
values = []
try:
for line in opened_file:
values.append(line)
except IOError as e:
print(e)
pass
return values
def delete_files(path):
"""
Deletes the directory given in path, and therefore the files in the directory as well
Then create a fresh directory with same name
"""
PyToSh.popen_comm(["rm", "-r", path])
PyToSh.popen_comm(["mkdir", path])
|
400c84deeb15c3afe47c0dc80ac050cf5565e524 | brentshierk/Web1.1-homework-1 | /app.py | 1,549 | 4.3125 | 4 |
# TODO: Follow the assignment instructions to complete the required routes!
# (And make sure to delete this TODO message when you're done!)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def homepage():
"""Shows a greeting to the user."""
return 'Are you there, world? It\'s me, Ducky!'
@app.route('/penguins')
def favoriteAnimal():
'show user my favorite animal'
return 'Penguins are cute!'
@app.route('/animal/<users_animal>')
def favorite_animal(users_animal):
"""Display a message to the user that changes based on their favorite animal."""
return f'Wow, {users_animal} is my favorite animal, too!'
@app.route('/dessert/<users_dessert>')
def favorite_dessert(users_dessert):
"""show users favorite dessert"""
return f'How did you know I {users_dessert}?'
@app.route('/madlibs/<adjective>/<noun>')
def madlib(adjective,noun):
"""mad lib"""
return f'roses are {adjective}, violets are are blue and you are {noun}'
@app.route('/multiply/<number1>/<number2>')
def multiply(number1,number2):
"""multiply page
this page takes two arguments then multiplys and displays the result
"""
if number1.isdigit() == False or number2.isdigit() == False:
return 'Invalid inputs. Please try again by entering 2 numbers!'
elif number1.isdigit() and number2.isdigit():
number1 = int(number1)
number2 = int(number2)
sum = number1 * number2
return f'{number1} times {number2} equals {sum}'
if __name__ == '__main__':
app.run(debug=True)
|
47faddadc44808940e4412c55f3de46785d24ea2 | chowell2000/SQL | /study_2.py | 1,208 | 3.5 | 4 | import pandas as pd
import sqlite3
DB_FILEPATH = 'Chinook_Sqlite.sqlite'
connection = sqlite3.connect(DB_FILEPATH)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
average_query = """
SELECT
CustomerId,
AVG(Total) as av
FROM Invoice
GROUP BY CustomerID
LIMIT 5
"""
result2 = cursor.execute(average_query).fetchall()
# print("RESULT 2", result2)
for row in result2:
print('Customer #', row['CustomerId'], 'had average total', row['av'])
print("-----")
notus_query = """
SELECT
*
FROM
Customer
WHERE
Country <> 'USA'
LIMIT 5
"""
result_notus = cursor.execute(notus_query).fetchall()
# print("RESULT 2", result2)
df = pd.DataFrame(columns = result_notus[0].keys())
for row in result_notus:
df = df.append(dict(row), ignore_index = True)
# print("-----")
print(df)
sabbath_query = """
SELECT
Title, Track.Name
FROM
Album
JOIN Artist
ON
Artist.ArtistId = Album.ArtistId
JOIN Track
ON
Album.AlbumId = Track.AlbumId
WHERE
Artist.Name = 'Black Sabbath';
"""
# result_sabbath = cursor.execute(sabbath_query).fetchall()
df = pd.read_sql_query(sabbath_query, connection)
# for row in result_sabbath:
# print(tuple(row))
print(df) |
298d3c43f043a7b7066ad03551ca21c1727fdd03 | NivMeir/Niv-Meir-MySuperList-2021 | /DataBase.py | 12,768 | 3.5 | 4 | import sqlite3
import emails_and_encryption
passcheck = emails_and_encryption.Extras()
class Users:
"""
create a users table in the data base
"""
def __init__(self, tablename="users", userid = "userid", email="email", password="password", username="username"):
self.__tablename = tablename
self.__userid = userid
self.__email = email
self.__password = password
self.__username = username
conn = sqlite3.connect('Super_List_Data_Base.db')
print("Opened database successfully")
id = str(self.__userid)
query_str = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + id + " INTEGER,"
query_str += " " + self.__email + " TEXT NOT NULL UNIQUE,"
query_str += " " + self.__password + " TEXT NOT NULL,"
query_str += " " + self.__username + " TEXT NOT NULL,"
query_str += " " +"PRIMARY KEY(" + id + " AUTOINCREMENT" + "));"
conn.execute(query_str)
print("Users table created successfully")
conn.commit()
conn.close()
def __str__(self):
return "table name is ", self.__tablename
def get_table_name(self):
return self.__tablename
def get_user_id(self, email):
if self.email_isexist(email):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
for row in cursor:
if email == row[1]:
return row[0]
else:
print("id wasn't found")
def get_user_name(self, id):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
for row in cursor:
if id == row[0]:
return row[3]
def get_user_email(self, id):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
for row in cursor:
if id == row[0]:
return row[1]
def insert_user(self, email, password, username):
if not self.email_isexist(email):
conn = sqlite3.connect('Super_List_Data_Base.db')
insert_query = "INSERT INTO " + self.__tablename + " (" + self.__email + "," + self.__password + "," + \
self.__username + ") VALUES"
insert_query += "(" + "'" + email + "'" + "," + "'" + password + "'" + "," + "'" + username + "'" + ");"
conn.execute(insert_query)
conn.commit()
conn.close()
print("Record created successfully")
else:
print("This email is already in the system")
def select_user_by_email(self, email):
if self.email_isexist(email):
conn = sqlite3.connect('Super_List_Data_Base.db')
print("Opened database successfully")
strsql = "SELECT email, username, password from " + self.__tablename + " where " + self.__email + "=" + \
"\'" + email + "\'"
print(strsql)
cursor = conn.execute(strsql)
return cursor
else:
print("Email wasn't found")
def email_isexist(self, email):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT email from " + self.__tablename + ";"
print(strsql)
cursor = conn.execute(strsql)
for row in cursor:
if email == row[0]:
return True
return False
def user_isexist(self, email, password):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
for row in cursor:
if email == row[1] and passcheck.encryptiontest(row[2], password):
return True
return False
def update_password(self, email, newpass):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql ="UPDATE " + self.__tablename + " SET password= " + "'" + str(newpass) + "'" + " WHERE email= '" + email + "';"
print(strsql)
conn.execute(strsql)
conn.commit()
conn.close()
print("password changed")
class Mylist:
def __init__(self, tablename="mylist", userid = "userid", product="product", locationnum ="locationnum", locationname ="locationname", shelf = "shelf"):
self.__tablename = tablename
self.__userid = userid
self.__product = product
self.__locationnum = locationnum
self.__locationname = locationname
self.__shelf = shelf
id = str(self.__userid)
print("Opened database successfully")
query_str = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + id + " INTEGER " + ","
query_str += " " + self.__product + " TEXT ,"+ self.__locationname + " TEXT ," + self.__locationnum + " INTEGER NOT NULL " + "," + self.__shelf + " TEXT ,"
query_str += " " + " FOREIGN KEY ( userid ) REFERENCES users( userid ));"
conn = sqlite3.connect('Super_List_Data_Base.db')
conn.execute(query_str)
print("My list table created successfully")
conn.commit()
conn.close()
def __str__(self):
return "table name is ", self.__tablename
def print_table(self):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
for row in cursor:
print("product: " + row[1] + "\tdepartment: " + str(row[2]) + "\tshelf: " + str(row[4]))
def get_table_name(self):
return self.__tablename
def insert_product(self, product, locationnum, locationname, shelf, id):
print(product, locationnum, locationname, shelf, id)
if not self.product_isexist(product, id):
conn = sqlite3.connect('Super_List_Data_Base.db')
insert_query = "INSERT INTO " + self.__tablename + " (" + self.__userid + "," + self.__product + "," + self.__locationnum + "," + self.__locationname + "," + self.__shelf +") VALUES"
insert_query += "("+ "'" + str(id) + "'" + "," + "'" + str(product) + "'" + "," + "'" + str(locationnum) +\
"'" + "," + "'" + str(locationname) + "'" + "," + "'" + str(shelf) + "'" +");"
print(insert_query)
conn.execute(insert_query)
conn.commit()
conn.close()
print("Record created successfully")
else:
print("This product is already in the List")
def product_isexist(self, product, id):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
for row in cursor:
if id == row[0] and product == row[1]:
return True
return False
def creat_product(self,data, pname, pclass, pclassnum, shelf):
product = {
'pname': pname,
'pclass': pclass,
'pclassnum':pclassnum,
'shelf':shelf
}
data.append(product)
return data
def delete_product(self, product, userid):
if self.product_isexist(product, userid):
conn = sqlite3.connect('Super_List_Data_Base.db')
insert_query = "DELETE FROM mylist WHERE userid == {} AND product == '{}';".format(userid, product)
print(insert_query)
conn.execute(insert_query)
conn.commit()
conn.close()
print("Deleted successfully")
else:
print("This product wasn't in the List")
def get_my_products(self, id):
conn = sqlite3.connect('Super_List_Data_Base.db')
insert_query = "SELECT userid, product, locationname, locationnum,shelf FROM mylist ORDER BY userid ASC, locationnum ASC, shelf ASC;"
print(insert_query)
cursor = conn.execute(insert_query)
newlist = []
for row in cursor:
if row[0] == id:
addproduct = {
'pname': row[1],
'pclass': row[2],
'shelf': row[4]}
newlist.append(addproduct)
print("done sorting")
return newlist
def get_place(self, id):
conn = sqlite3.connect('Super_List_Data_Base.db')
insert_query = "SELECT userid, product, locationname, locationnum,shelf FROM mylist ORDER BY userid ASC, locationnum ASC, shelf ASC;"
print(insert_query)
cursor = conn.execute(insert_query)
newlist = []
for row in cursor:
if row[0] == id:
addproduct = {
'pclass': row[3],
'shelf': row[4]}
newlist.append(addproduct)
print("done sorting")
return newlist
class Allproducts:
def __init__(self, tablename="allproducts", product="product", locationnum ="locationnum", locationname ="locationname", shelf = "shelf"):
self.__tablename = tablename
self.__product = product
self.__locationnum = locationnum
self.__locationname = locationname
self.__shelf = shelf
print("Opened database successfully")
query_str = "CREATE TABLE IF NOT EXISTS " + tablename + "("
query_str += " " + self.__product + " TEXT ," + self.__locationname + " TEXT ," + self.__locationnum + \
" INTEGER NOT NULL ," + self.__shelf + " TEXT "+ ");"
#"FOREIGN KEY(PersonID) REFERENCES Persons(PersonID)"
conn = sqlite3.connect('Super_List_Data_Base.db')
# conn.execute("drop table users")
conn.execute(query_str)
print("All products table created successfully")
conn.commit()
conn.close()
def get_table_name(self):
return self.__tablename
def creat_product(self,data, pname, pclass, shelf):
product = {
'pname': pname,
'pclass': pclass,
'shelf': shelf
}
data.append(product)
return data
def get_products(self, location):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
productlist = ["", "Fruits and Vegetables", "Drinks", "Meat, Chicken and Fish", "Bread", "Milk, Cheese and Eggs","Snacks"]
list =[]
if not location:
for row in cursor:
list = self.creat_product(list, row[0], row[1], row[3])
elif location not in productlist:
for row in cursor:
if row[0] == location:
list = self.creat_product(list, row[0], row[1], row[3])
else:
for row in cursor:
if row[1] == location:
list = self.creat_product(list, row[0], row[1], row[3])
return list
def insert_product(self, product, shelf, locationnum, locationname):
if not self.product_isexist(product):
conn = sqlite3.connect('Super_List_Data_Base.db')
insert_query = "INSERT INTO " + self.__tablename + " (" + self.__product + "," + self.__locationnum + "," + self.__locationname + "," + self.__shelf + ") VALUES"
insert_query += "(" + "'" + str(product) + "'" + "," + "'" + str(
locationnum) + "'" + "," + "'" + str(locationname) + "'" + "," + "'" + str(shelf) + "'" + ");"
print(insert_query)
conn.execute(insert_query)
conn.commit()
conn.close()
print("Record created successfully")
else:
print("This product is already in the List")
def product_isexist(self, product):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
for row in cursor:
if product == row[1]:
return True
return False
def get_product_info(self, product):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
cursor = conn.execute(strsql)
for row in cursor:
if product == row[0]:
return (row[0], row[1], row[2], row[3])
return False
def isempty(self):
conn = sqlite3.connect('Super_List_Data_Base.db')
strsql = "SELECT * from " + self.__tablename + ";"
lines = 0
cursor = conn.execute(strsql)
for row in cursor:
lines += 1
return lines == 0
|
b7723ece54f9263dd336911b03ca8688a61dbaa2 | ReinisZonne/Pong | /main.py | 4,563 | 3.609375 | 4 | '''
Pong game
Date: 10.07.20
'''
import pygame
pygame.font.init()
from random import randrange
class Paddle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.width = 20
self.height = 70
self.speed = 5
self.score = 0
def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height))
class Ball:
def __init__(self, direction):
self.x = 500
self.y = 262
self.direction = direction
self.radius = 5
self.color = (255, 255, 255)
self.speedy = 5
self.speedx = 5
self.hitTop = False
self.hitBottom = False
def draw(self, surface):
pygame.draw.circle(surface, self.color, (self.x, self.y), self.radius)
def drawMidLine(surface, x, y):
pygame.draw.line(surface, (255, 255, 255), (x, y), (x, y + 10), 2)
# Main loop
def main():
# Display settings
width = 1000
height = width * 9 // 16
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
FPS = 30 # Frames per second
#------------------
# Redraws the game window
def reDrawWindow(surface, player1, player2, b):
surface.fill((0,0,0)) # Bg-color: Black
# Draws mid Line
lineX = width // 2
lineY = 0
while lineY <= height:
drawMidLine(win, lineX, lineY)
lineY += 25
# ---------------
# Display score
font = pygame.font.SysFont("Comic sans MS", 24)
score1 = font.render(str(player1.score), False, (255, 255, 255))
score2 = font.render(str(player2.score), False, (255, 255, 255))
win.blit(score1, (200, 50))
win.blit(score2, (800, 50))
# ---------------
player1.draw(surface)
player2.draw(surface)
b.draw(surface)
pygame.display.update()
# Classes
player1 = Paddle(10, height//2, (0, 255, 0))
player2 = Paddle(970, height//2, (255, 0, 0))
b = Ball(randrange(0,1))
#-----------
# Loop
finished = False
while not finished:
clock.tick(FPS)
# Key binding Player1
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and player1.y > 5:
player1.y -= player1.speed
elif keys[pygame.K_s] and player1.y + player1.height < height - 5:
player1.y += player1.speed
#--------------------
# Key binding Player2
if keys[pygame.K_UP] and player2.y > 5:
player2.y -= player2.speed
elif keys[pygame.K_DOWN] and player2.y + player2.height < height - 5:
player2.y += player2.speed
#--------------------
# Ball movement
if b.direction == 1:
b.y += b.speedy
b.x += b.speedx
else:
b.y += b.speedy
b.x -= b.speedx
# Collision with player1
if b.x - b.radius < player1.x + player1.width and b.y > player1.y and b.y < player1.y + player1.height:
b.speedx *= -1 # X values becomes positive
#-----------------------
# Collision with player2
if b.x + b.radius > player2.x and b.y > player2.y and b.y < player2.y + player2.height:
b.speedx *= -1 # X value becomes negative
#-----------------------
# Collision with top wall
if b.y < b.radius + b.speedx:
b.speedy *= -1
#------------------
# Collison with bottom wall
elif b.y > height - b.radius - b.speedx:
b.speedy *= -1
#------------------
# Collison with right wall
elif b.x > width - b.radius - b.speedx:
b = Ball(0)
b.x = width // 2
b.y = height // 2
player1.score += 1
#------------------
# Collision with left wall
elif b.x < b.radius + b.speedx:
b = Ball(1)
b.x = width // 2
b.y = height // 2
player2.score += 1
# Exit
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
#-----------------------
reDrawWindow(win, player1, player2, b)
main()
pygame.quit()
|
1844d5e7558dfe8d0cbea59ccbd0eb75951c7591 | zhangzhonghua1999/webapp | /hua/myproject/廖雪峰python/函数式编程/sorted函数.py | 424 | 3.90625 | 4 | print(sorted([-1,3,-4,5,-20,8]))
print(sorted([-1,3,-4,5,-20,8],key=abs))
print(sorted(['bob','alice','Zoo'],key=str.lower))
print(sorted(['bob','alice','Zoo'],key=str.lower,reverse=True))
L=[('Bob',75),('Adam',92),('Bart',66),('Lisa',88)]
#按名字排序
def by_name(t):
return t[0]
L2 = sorted(L, key=by_name)
print(L2)
#按成绩排序
def by_score(t):
return t[1]
L3=sorted(L,key=by_score)
print(L3)
|
4e4d00fe83c79c2a65715f8aec9b46cdd991454a | terasakisatoshi/HPC | /PythonMPI/MandelbrotSeq.py | 616 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import time
def mandelbrot(x,y,maxit):
c=x+y*1j#complex exporession
z=0+0j#complex expression
it=0
while abs(z)<2 and it<maxit:
z=z**2+c
it+=1
return it
#main
x1,x2=-2.0,1.0
y1,y2=-1.0,1.0
w,h=150,100
maxit=1025
C=np.zeros([h,w],dtype=int)
dx=(x2-x1)/w
dy=(y2-y1)/h
start=time.time()
for i in range(h):
y=y1+i*dy
for j in range(w):
x=x1+j*dx
C[i,j]=mandelbrot(x,y,maxit)
plt.imshow(C, aspect="equal")
plt.spectral()
end=time.time()
elapsed_time=end-start
print("time= %s" % elapsed_time)
plt.show() |
c4fb409129cbd273628c516f6aa3ccf817c9d1c9 | mrmyothet/ipnd | /ProgrammingBasicWithPython-KCL/Chapter-7/Fibonacci-sequence(recursion).py | 108 | 3.625 | 4 | def fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib (n - 2)
print(fib(10))
|
60f44a6b8288cca98929b5d9c987f5b8f498ac08 | artur-oganesyan/python_basics | /lesson_1/task_5.py | 527 | 4.03125 | 4 | proceeds = int(input('Enter proceeds: '))
costs = int(input('Enter costs: '))
if proceeds > costs:
print('You have a profit')
profit = proceeds - costs
profitability = profit / proceeds * 100
print(f'Your profitability {profitability:.2f} %')
firm_size = int(input("Enter firm size: "))
profit_for_one_employee = profit / firm_size
print(f'Profit for one employee is {profit_for_one_employee:.2f}')
elif proceeds == costs:
print('You have no profit')
else:
print('You are incurring losses')
|
96091f2df06ce67f94273d9ca9796b2e326e9b30 | talesritz/Learning-Python---Guanabara-classes | /Exercises - Module II/EX047 - Contagem numeros pares.py | 301 | 3.734375 | 4 | #Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50.
print('\033[34m-=-'*11)
print('\033[31mEX047 - Contagem de Números Pares')
print('\033[34m-=-\033[m'*11)
print('\n')
sum = 0
for count in range(1, 50, 1):
if count%2==0:
print(count)
|
85194c50f5d5bca08626654f1831768aef8aecc5 | andreikina8/eponyms_extraction | /token1.py | 864 | 3.5625 | 4 | class Token(object):
def __init__(self, string, position):
self.string = string
self.position = position
self.length = len(string)
#self.token_type = token_type
self.right_position = self.position + self.length
def __repr__(self):
if hasattr(self, "token_type") == True:
return "%s [%s...%s]..%s" % (self.string, self.position, self.right_position, self.token_type)
else:
return "%s [%s...%s]" % (self.string, self.position, self.right_position)
class NumericValue(Token):
token_type = "Numeric"
class AlphaValue(Token):
token_type = "Alpha"
class SpaceValue(Token):
token_type = "Space"
class PuncValue(Token):
token_type = "Punctuation"
class UnknownValue(Token):
token_type = "Unknown"
|
5e62669a9fcb390b7f276fbcc2608e49f4850c89 | lesliehealray/python_class | /script2.py | 187 | 3.703125 | 4 | #numbers and variables
print 5
num = 5
print type(num)
print str(num)
new = str(num)
print type(num)
print len(new)
print len(new)
print len(num) # what is this TypeError telling you?
|
39dfd63c41e3323c0baf3920eeb37839f805731c | TheCoder777/instagram | /python/flask-full-stack/model.py | 885 | 3.875 | 4 | # @thecoder777 || Python 'model.py'
""" Database managment goes here """
import sqlite3
import sys
db_path = "userdata.db"
# check if there are any problems with the database
def check_db():
try:
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute("CREATE TABLE if not exists users \
(id INTEGER PRIMARY KEY, email TEXT, name TEXT)")
return 0
except FileNotFoundError as e:
print(f"User database not found! \n ERROR:\n{e}",
file=sys.stderr)
return 1 # return 1 if sth goes wrong
# save email & username
def register_user(email, username):
if check_db():
return 1 # error code 1
else:
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute("INSERT INTO users('email', 'name') \
VALUES(?, ?)", (email, username))
conn.commit()
|
af4db1df62e23706567375d533c91dda755808f5 | edk0/ads | /util.py | 3,576 | 3.5625 | 4 | import math
from functools import reduce, partial
from itertools import starmap
from operator import attrgetter
def distance(p1, p2, cutoff=float('inf')):
"""
The distance between p1 and p2. If cutoff is supplied and is smaller than
the square of the distance, don't compute the square root and return None
instead.
"""
d2 = (p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2
if d2 > cutoff:
return None
return math.sqrt(d2)
def trivial_solution(p):
"""
Return the trivial (route per point) solution for p.
"""
s = set()
for customer in p.customers:
s.add(Route(customer.volume, [p.depot, customer, p.depot]))
return s
def merge_routes(a, b, cutoff_d2=float('inf')):
"""
Return a Route that visits all the points on a and b.
"""
c_merge = distance(a._points[-2], b._points[1], cutoff_d2)
if c_merge is None:
return
c_a = a.cost - a._post_cost
c_b = b.cost - b._pre_cost
saving = c_a + c_b - c_merge
r = Route(a.volume + b.volume,
a._points[:-1] + b._points[1:],
_costs=(c_a + c_b + c_merge, a._pre_cost, b._post_cost))
return r, saving
class Point:
"""
2d coordinates, possibly with a volume of stuff to be delivered there
"""
__slots__ = ('x', 'y', 'volume', '_hash')
def __init__(self, x, y=None, *, volume=None):
if isinstance(x, (tuple, list)):
x, y = x
if y is None:
raise TypeError
self.x = x
self.y = y
self.volume = volume
self._hash = hash(x) ^ hash(y) ^ hash(volume)
def __repr__(self):
if self.volume is not None:
return 'Point({!r}, {!r}, volume={!r})'.format(
self.x, self.y, self.volume)
return 'Point({!r}, {!r})'.format(self.x, self.y)
def __hash__(self):
return self._hash
def __eq__(self, other):
return self.x == other.x and self.y == other.y
class Route:
"""
A route, i.e. a sequence of points. Stores pre-computed cost and volume.
Unlike Point we don't override hash() for Route, so Routes will compare
equal only if they're the exact same object. This is purely a speed
optimization; we never create two objects for the same route, so we don't
need to waste the time comparing them properly.
"""
__slots__ = ('volume', '_points', 'cost', '_pre_cost', '_post_cost')
def __init__(self, volume, points, *, _costs=None):
self.volume = volume
self._points = points = tuple(points)
if _costs is not None:
self.cost, self._pre_cost, self._post_cost = _costs
return
if len(points) < 3:
raise ValueError # all routes should involve depot->somewhere->depot
self._pre_cost = distance(points[0], points[1])
self._post_cost = distance(points[-2], points[-1])
def sum_distance(s, p):
p1, p2 = p
return s + distance(p1, p2)
self.cost = reduce(sum_distance, zip(points, points[1:]), 0)
def __repr__(self):
return '<Route points={self._points!r} volume={self.volume!r} \
cost={self.cost!r}>'.format(self=self)
def npr(n, k):
"""
return n_P_k
"""
return math.factorial(n) // math.factorial(n-k)
def ncr(n, k):
"""
return n_C_k
"""
return math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
def solution_cost(s):
"""
Return the sum of the costs of a set of routes.
"""
return sum(map(attrgetter('cost'), s))
|
affbbaff8e55fa575b5d0fff0294d9835c411e41 | jethroglaudin/FraudDetectionMicroService | /fraud_detection_model.py | 2,353 | 3.5625 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def run_model():
# Importing the dataset
dataset = pd.read_csv('transactions.csv')
X = dataset.iloc[:, [1, 2, 4, 5, 7, 8]].values
y = dataset.iloc[:, 9].values
# Encoding categorical data
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0])], remainder='passthrough')
X = np.array(ct.fit_transform(X))
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
# Feature Scaling the dataset
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.fit_transform(X_test)
# Training the Logistic Regression model on the Training set
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(max_iter=100000)
classifier.fit(X_train, y_train)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score
y_pred = classifier.predict(X_test)
true_negative, false_positive, false_negative, true_positive = confusion_matrix(y_test, y_pred).ravel()
accuracy = round(accuracy_score(y_test, y_pred),4) * 100
precision = round(precision_score(y_test, y_pred),4)
recall = round(recall_score(y_test, y_pred),4)
result = [
{
'confusion_matrix': {
'Non-Fraudulent Transactions Predicted True': true_negative.item(),
'Non-Fradulent Transaction Predicted False': false_negative.item(),
'Fraudlent Transaction Predicted False': false_positive.item(),
'Fraudulent Transaction Predicted True': true_positive.item()
},
'metrics': {
'Total data size': y_train.size + y_test.size,
'Test data size': y_test.size,
'Accuacy': round(accuracy,4) * 100,
'Precision': precision,
'Recall': recall
}
}
]
return result
|
ff9410c82c3c465fe6ed4ffd7af80c2c84311d8e | Jung0Jin/Codingdojang | /2021년1월/20210104대각선길이구하기.py | 170 | 3.71875 | 4 | # https://codingdojang.com/scode/672?answer_mode=hide
def diagonal():
x=float(input())
y=float(input())
result=(x**2+y**2)**0.5
print(result)
diagonal() |
43ad6010ba04f8344c59abe135a69c566a4c21bd | JJHH06/elgamal-python-simulation | /keyUtils.py | 837 | 3.609375 | 4 | #Laboratorio 10, librería de funciones de útilidad
# Simulación de cifrado ElGamal
# Jose Javier Hurtarte 19707
# Andrei Francisco Portales 19825
# Christian Pérez 19710
from random import randrange
#k: cantidad de primos a generar
def fermatRandomPrime( k,min, max ,iteraciones = 25):
result = []
while(k >0):
prime = randrange(min,max+1)
if is_prime(prime, k=iteraciones):
result.append(prime)
k -=1
return result
def is_prime(n, k = 25):
if n ==2 or n ==1: return False
for i in range(k):
a = randrange(2, n)
if pow(a,(n-1),n) != 1%n:
return False
return True
def save(filename, data):
file = open(filename, 'w')
file.write(data)
file.close()
def read(filename):
file = open(filename, 'r')
data = file.read()
file.close()
return data
|
e8db6b23c55679003e6c86dd4a8190a5776e48bf | jessidepp17/hort503 | /assignments/A04/ex35.py | 2,892 | 4.03125 | 4 | # Text game called "Save the Princess!"
from sys import exit
# gold room fxn
def gold_room():
print("There's a chest and a locked door in the room.")
choice = input("> ")
if "open chest" in choice:
print("There's a shitload of gold! How many pieces of gold do you take?")
elif "ignore chest" in choice:
dead("You stumble around the room until you starve.")
# need to change so that any number can be entered
choice = input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else: # if no intager entered print this
dead("Man, learn to type a number.")
# this section keeps looping; need to get it to call boss_battle()
if how_much < 50: # if input is < 50 then continue
print("Nice, you're not greedy.")
print("You can go through the door now.")
elif "open door" in choice or "use key" in choice and locked_door:
boss_battle()
else:
dead("You greedy bastard!")
def boss_battle():
print("Oh no, the door has locked behind you!")
print("There's a crazy huge dragon in the room!")
print("You must slay the dragon to save the princess. GO!!!")
choice = input("> ")
if "slay dragon" in choice:
print("Hooray, you saved the princess! YOU WIN!")
else:
dead("You suck.")
def bear_room():
print("There is a bear here.")
print("The bear has a bunch of honey.")
print("The fat bear is in front of another door.")
print("How are you going to move the bear?")
bear_moved = False
while True: # I dont get this part
choice = input("> ")
if choice == "take honey":
dead("The bear looks at you then slaps your face off.")
elif choice == "taunt bear" and not bear_moved:
print("The bear has moved from the door.")
print("You can go through it now.")
bear_moved = True
elif choice == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif choice == "open door" and bear_moved:
gold_room()
else:
print("I got no idea what that means.")
def cthulhu_room():
print("Here you see the great evil Cthulhu.")
print("He, it, whatever stares at you and you go insane.")
print("Do you flee for your life or eat your head?")
choice = input("> ")
if "flee" in choice:
start()
elif "head" in choice:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why):
print(why, "Good job!")
exit(0)
def start():
print("You are in a dark room.")
print("There is a door to your right and left.")
print("Which one do you take?")
choice = input("> ")
if choice == "left":
bear_room()
elif choice == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
# call start() to begin game
start()
|
7280bb60daf596ef3c38718104ee7030e68f9e54 | Markers/algorithm-problem-solving | /BRACKETS2/free-lunch_BRACKETS2.py | 1,186 | 3.625 | 4 | import sys
class Brackets2:
def __init__(self, str):
self.str = str
self.bracketMap = {
'(' : 0,
'{' : 1,
'[' : 2,
')' : 10,
'}' : 11,
']' : 12,
}
def isValidated(self):
stack = list()
for c in self.str:
if c != '\n':
id = self.bracketMap.get(c)
# CASE : Open Case
if id < 10:
stack.append(id)
# CASE : Close Case
else :
# CASE : Stack is empty
if len(stack) == 0:
return False
# CASE : Mismatched Bracket
if stack.pop() + 10 != id:
return False
# CASE : Remain open Brackets
if len(stack) != 0:
return False
return True
if __name__ == "__main__":
rl = lambda: sys.stdin.readline()
retList = []
for _ in xrange(int(rl())):
input = rl()
bracket = Brackets2(input)
if bracket.isValidated():
print "YES"
else :
print "NO" |
6eedb219e0eb5e9a26fd77c63e80c235fd8fe705 | seanhugh/Project_Euler_Problems | /problem_7.py | 509 | 3.625 | 4 | #!/usr/bin/env python
#Problem 6 on Euler Project. Looking for the 10,001st prime number
primes = []
i = 1
q=0
def check_prime(num):
if num ==1: return 'false'
if num ==2: return 'true'
if num % 2 == 0: return 'false'
for j in range(3, int((num+1)**.5)+1, 2):
if (num % j == 0) and (num != j):
return 'false'
return 'true'
while len(primes) <10001:
if check_prime(i)=='true':
primes.append(i)
i += 1
print len(primes)
print primes[-1] |
ec9bf1367516bcbdb055175fbc296f81f92a7606 | Aasthaengg/IBMdataset | /Python_codes/p03855/s733956797.py | 1,609 | 3.828125 | 4 | class UnionFind():
# 作りたい要素数nで初期化
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
# ノードxのrootノードを見つける
def Find_Root(self, x):
if(self.root[x] < 0):
return x
else:
self.root[x] = self.Find_Root(self.root[x])
return self.root[x]
# 木の併合、入力は併合したい各ノード
def Unite(self, x, y):
x = self.Find_Root(x)
y = self.Find_Root(y)
if(x == y):
return
elif(self.rnk[x] > self.rnk[y]):
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if(self.rnk[x] == self.rnk[y]):
self.rnk[y] += 1
def isSameGroup(self, x, y):
return self.Find_Root(x) == self.Find_Root(y)
# ノードxが属する木のサイズ
def Count(self, x):
return -self.root[self.Find_Root(x)]
N, K, L = map(int, input().split())
U1 = UnionFind(N)
U2 = UnionFind(N)
for _ in range(K):
a, b = map(int, input().split())
U1.Unite(a, b)
for _ in range(L):
a, b = map(int, input().split())
U2.Unite(a, b)
Roots = [0]
dic = {}
for n in range(1, N+1):
r1 = U1.Find_Root(n)
r2 = U2.Find_Root(n)
r = r1*2*N + r2
Roots.append(r)
if not r in dic.keys():
dic[r] = 1
else:
dic[r] += 1
ans = []
for n in range(1, N+1):
ans.append(dic[Roots[n]])
print(" ".join([str(a) for a in ans])) |
58ef90f5c6624977f9cfa3f1bc6a5364ca40138f | Devtlv-classroom/strings-basics-annasolemani | /list.py | 1,066 | 3.96875 | 4 | list= [825, 262, 627, 826, 285, 221, 730, 340, 750, 989, 272, 842, 383, 575, 810]
print("There are {} numbers in the list.".format(len(list)))
print("The lowest number on the list is {}.".format(min(list)))
print("The highest number on the list is {}.".format(max(list)))
print("The sum of the list is {}.".format(sum(list)))
list2= ['spring', 'autumn', 'summer']
list2.insert(4, 'winter')
print(list2)
list2[1]='summer'
list2[2]='autumn'
print(list2)
topping = input("Please add a topping. Type 'quit' when finished adding. ")
while topping != "quit":
topping = input("You have added {}. Please add another topping. Type 'quit' when finished adding. ".format(topping))
print("Your pizza has been ordered.")
age1= input("Please enter your age ")
while age1 != "quit":
if age1 <3:
price="free"
if age1 >=3 and <12:
price="$10"
if age1 >=12:
price="$15"
age1 = input("Your ticket will be {}. Please add the next customer's age. Type 'quit' when finished adding. ".format(price))
print("Your tickets have been ordered.") |
528ca22e4625d788b17b2d232970d96e37316c57 | marijadom/Projekat | /pomocne/unos.py | 370 | 3.71875 | 4 |
def validacija_unosa_string(poruka):
unos = input(poruka)
while unos == "":
print("Ne moze se uneti prazan string!")
unos = input(poruka)
return unos
def validacija_unosa_broj(poruka):
unos = input(poruka)
while unos == "":
print("Ne moze se uneti prazan string!")
unos = input(poruka)
return float(unos)
|
cd9b2621354b41dab2657e8f0bae14493858399f | MaksimKulya/PythonCourse | /L4_task3.py | 414 | 3.796875 | 4 | # Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку.
# Подсказка: использовать функцию range() и генератор.
import random as rnd
a = [rnd.randint(20, 240) for i in range(100)]
print(a)
b = [n for n in a if n % 20 ==0 or n % 21 ==0]
print(b) |
b8d11e9ff40749f2de4f0f89bc8b28bd8c7935c4 | jso/py-bikevis | /bikevis/analyses/basic.py | 4,872 | 3.609375 | 4 | import sqlite3
import matplotlib.pyplot as plt
from util import put_add, put_list, put_val, traverse
from cdf import cdf
def demographics(con):
data = {}
cur = con.cursor()
cur.execute("SELECT gender, birth_year, COUNT(trip_id) trip_count "
"FROM trips WHERE gender NOT NULL AND birth_year NOT NULL "
"GROUP BY gender, birth_year ORDER BY trip_count DESC")
while True:
rows = cur.fetchmany(1000)
if not rows: break
for row in rows:
put_val(data, row["gender"], row["birth_year"], row["trip_count"])
cur.close()
for kvs, data in traverse(data, "gender"):
gender = kvs["gender"]
xs = list(sorted(data.keys()))
ys = [data[x] for x in xs]
total = sum(ys)
fig = plt.figure()
plt.scatter(xs, ys)
plt.yscale("log")
plt.xlabel("birth year")
plt.ylabel("number of rides")
plt.grid(axis="y")
plt.title("%s n=%d" % (gender, total))
plt.savefig("gender.%s.pdf" % gender, bbox_inches="tight")
def trip_duration(con):
c = cdf(resolution=60)
cur = con.cursor()
cur.execute("SELECT trip_duration FROM trips")
while True:
rows = cur.fetchmany(1000)
if not rows: break
for row in rows:
c.insert(row["trip_duration"])
cur.close()
fig = plt.figure()
plt.plot(*c.getData())
plt.xscale("log")
plt.xlabel("trip duration (s)")
plt.ylabel("CDF of trips")
plt.xticks(
[60, 300, 900, 1800, 3600, 7200, 14400],
["1m", "5m", "15m", "30m", "1h", "2h", "4h"])
plt.grid(axis="y")
plt.savefig("duration.pdf", bbox_inches="tight")
def station_popularity(con):
data = {}
cur = con.cursor()
cur.execute("SELECT from_station_name, to_station_name FROM trips")
while True:
rows = cur.fetchmany(1000)
if not rows: break
for row in rows:
put_add(data, row["from_station_name"], 1)
put_add(data, row["to_station_name"], 1)
cur.close()
keys = list(sorted(data, key=lambda x: data[x], reverse=True))
xs = list(xrange(len(keys)))
ys = [data[x] for x in keys]
fig = plt.figure()
plt.plot(xs, ys)
plt.xscale("log")
plt.yscale("log")
plt.xlabel("station index")
plt.ylabel("trip endpoint count")
plt.savefig("station_popularity.pdf", bbox_inches="tight")
n = 50
fig = plt.figure(figsize=(30, 4))
plt.bar(xs[:n], ys[:n], log=True)
plt.xlabel("station")
plt.ylabel("trip endpoint count")
plt.xticks(xs[:n], keys[:n])
fig.autofmt_xdate()
plt.savefig("station_popularity.top%d.pdf" % n, bbox_inches="tight")
def route_popularity(con):
data = {}
cur = con.cursor()
cur.execute("SELECT from_station_name, to_station_name FROM trips")
while True:
rows = cur.fetchmany(1000)
if not rows: break
for row in rows:
put_add(data, (row["from_station_name"], row["to_station_name"]), 1)
cur.close()
keys = list(sorted(data, key=lambda x: data[x], reverse=True))
keys_str = ["->".join(x) for x in keys]
xs = list(xrange(len(keys)))
ys = [data[x] for x in keys]
fig = plt.figure()
plt.plot(xs, ys)
plt.xscale("log")
plt.yscale("log")
plt.xlabel("station pair index")
plt.ylabel("route count")
plt.savefig("route_popularity.pdf", bbox_inches="tight")
n = 25
fig = plt.figure(figsize=(20, 4))
plt.bar(xs[:n], ys[:n], log=True)
plt.xlabel("station pair")
plt.ylabel("route count")
plt.xticks(xs[:n], keys_str[:n])
fig.autofmt_xdate()
plt.savefig("route_popularity.top%d.pdf" % n, bbox_inches="tight")
def bike_trips(con):
c = cdf()
c_dur = cdf()
cur = con.cursor()
cur.execute("SELECT COUNT(*) trip_count, SUM(trip_duration) total_time "
"FROM trips GROUP BY bike_id")
while True:
rows = cur.fetchmany(1000)
if not rows: break
for row in rows:
c.insert(row["trip_count"])
c_dur.insert(row["total_time"])
cur.close()
fig = plt.figure()
plt.plot(*c.getData())
plt.xscale("log")
plt.xlabel("number of trips")
plt.ylabel("CDF of bikes")
plt.savefig("bike_trips.pdf", bbox_inches="tight")
fig = plt.figure()
plt.plot(*c_dur.getData())
plt.xscale("log")
plt.xlabel("total trip time (s)")
plt.ylabel("CDF of bikes")
plt.savefig("bike_time.pdf", bbox_inches="tight")
if __name__ == "__main__":
con = sqlite3.connect("bikevis.db")
con.row_factory = sqlite3.Row
print "user demographics"
demographics(con)
print "trip duration"
trip_duration(con)
print "station popularity"
station_popularity(con)
print "route popularity"
route_popularity(con)
print "bike trips"
bike_trips(con)
con.close()
|
d66cb7c9ac4404d2bc4f0b2c5c0cbe2d770cfcd8 | natemurthy/misc | /toy-problems/2019-08-08/question1b.py | 654 | 4.28125 | 4 | # /*
# Given an array of integers, determine whether the array only increases or only decreases.
# Examples:
# [1, 2, 3] --> True
# [3, 2, 1] --> True
# [1, 2, 4, 4, 5] --> True
# [1, 1, 1] --> True
# */
'''
Here is a more elegant solution from g4g:
https://www.geeksforgeeks.org/python-program-to-check-if-given-array-is-monotonic/
'''
def is_monotonic(arr):
end = len(arr)-1
return (all(arr[i] <= arr[i + 1] for i in range(end)) or
all(arr[i] >= arr[i + 1] for i in range(end)))
print(is_monotonic([1,2,1]))
print(is_monotonic([1, 2, 4, 4, 5]))
print(is_monotonic([1,1,1]))
print(is_monotonic([0, 3, 1,1, 0, 0, -1, -2]))
|
d960432e7acf9e1e0de3ff591dc34fcbb2588fca | NurbaTron/psycopg2.randomData | /month1/day.17.py | 3,023 | 4.3125 | 4 | """ООП композиция"""
"""класс композиций - это у которого атрyибут является объектом другого класса"""
# class Adress:
# def __init__(self, streetname, city, homenum):
# self.streetname = streetname
# self.city = city
# self.homenum = homenum
# class Job:
# def __init__(self, jobname, salary, time):
# self.jobname = jobname
# self.salary = salary
# self.time = time
# class Worker:
# def __init__(self, name, streetname, city, homenumber, jobname, salary, time):
# self.name = name
# self.adress = Adress(streetname = streetname, city = city, homenum = homenumber)
# self.job = Job(jobname = jobname, salary = salary, time = time)
# def show_data(self):
# return f"{self.name} {self.job.jobname}, он живёт в {self.adress.city} на улице {self.adress.streetname}, а ЗП {self.job.salary} HUNDRED BUKS, а времени на работу тратит {self.job.time} часа"
# work = Worker("салокхидин", "ленин", "Оше", 11, "програмист питон", 3, 3)
# print(work.show_data())
class Human:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
class Araon:
def __init__(self, works, proffesion):
self.works = works
self.proffesion = proffesion
class Worker:
def __init__(self, name, age, gender, works, proffesion):
self.human = Human(name = name, age = age, gender = gender)
self.work =Araon(works = works, proffesion = proffesion)
def show_dat(self):
return f"My name is {self.human.name}, I am {self.human.age}, years old, I am {self.human.gender} and my proffecion is {self.work.proffesion}"
sas = Worker("Andrey", "23", "male", "in England", "builder")
print(sas.show_dat())
class Human:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def set_data(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def get_data(self):
return f"{self.name} is {self.age} years old. He is {self.gender}"
class Worker2:
def __init__(self, proffesion, name, age, gender):
self.proffesion = proffesion
self.about = Human(name = name, age = age, gender = gender)
def show_info(self):
return f"""My name is {self.about.name}, I am {self.about.age} years old, I am a {self.about.gender}, I am a {self.proffesion}"""
w = Worker2("developer", "Asian", 23, "man")
print(w.show_info())
class A:
number = 89
color = "red"
def show(self):
return f"число {self.number}"
class B(A):
pass
clasb = B()
print(clasb.show())
str1 = "apple"
print(len(str1))
lst = [5, 6, 54, True]
print(len(lst))
dict2 = {"name":"Lera", "age":17, "gender":"female"}
print(dict(dict2))
|
85d84f0ddd2195042ac4f61baaca6c020af20f96 | CodeForContribute/Algos-DataStructures | /HashCodes/sum_pair_whose_sum_is_in_arr.py | 1,089 | 4 | 4 | def sum_pair_whose_sum_is_in_arr(arr, n):
found = False
for i in range(n):
for j in range(i + 1, n):
if arr[i] + arr[j] in arr:
print((arr[i], arr[j]), end=" ")
found = True
if found is False:
print("Not Found:")
# for k in range(n):
# if arr[i] + arr[j] == arr[k]:
# print((arr[i], arr[j]), end=" ")
# found = True
def sum_pair_whose_sum_is_in_arr_in_hash(arr, n):
found = False
hash_map = dict()
for i in range(n):
if arr[i] in hash_map.keys():
hash_map[arr[i]] += 1
else:
hash_map[arr[i]] = 1
for i in range(n):
for j in range(i+1, n):
if arr[i] + arr[j] in hash_map.keys():
print((arr[i], arr[j]), end=" ")
found = True
if found is False:
print("Not Found:")
if __name__ == '__main__':
arr = [10, 4, 8, 13, 5]
n = len(arr)
sum_pair_whose_sum_is_in_arr(arr, n)
print("\n")
sum_pair_whose_sum_is_in_arr_in_hash(arr, n)
|
3f404677c0bd468f7f6e909217099277cc73e6b8 | Frankiee/leetcode | /math/ugly_number/313_super_ugly_number.py | 1,407 | 4.03125 | 4 | # [Prime-Factor, Ugly-Number]
# https://leetcode.com/problems/super-ugly-number/
# 313. Super Ugly Number
# Write a program to find the nth super ugly number.
#
# Super ugly numbers are positive numbers whose all prime factors are in the
# given prime list primes of size k.
#
# Example:
#
# Input: n = 12, primes = [2,7,13,19]
# Output: 32
# Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first
# 12
# super ugly numbers given primes = [2,7,13,19] of size 4.
# Note:
#
# 1 is a super ugly number for any given primes.
# The given numbers in primes are in ascending order.
# 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
# The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
dp = [1]
prime_num_idx = [0] * len(primes)
while n > 1:
next_num_candidates = [
primes[idx] * dp[prime_num_idx[idx]]
for idx in range(len(primes))
]
next_num = min(next_num_candidates)
for idx in range(len(primes)):
if next_num_candidates[idx] == next_num:
prime_num_idx[idx] += 1
dp.append(next_num)
n -= 1
return dp[-1]
|
8378a330186bec3cf847276768f4e397c4fbe694 | sahilkamesh/POS-Tagging | /baseline.py | 2,068 | 3.546875 | 4 | """
Part 1: Simple baseline that only uses word statistics to predict tags
"""
def baseline(train, test):
'''
input: training data (list of sentences, with tags on the words)
test data (list of sentences, no tags on the words)
output: list of sentences, each sentence is a list of (word,tag) pairs.
E.g., [[(word1, tag1), (word2, tag2)], [(word3, tag3), (word4, tag4)]]
'''
# ------------------- TRAINING -------------------
tag_freq = {}
word_tags = {}
# Iterate through training data to get most common tag overall and most common for each word
for sentence in train:
for words in sentence:
tag = words[1]
word = words[0]
# Count occurences of each tag
tag_freq[tag] = tag_freq.get(tag,0) + 1
if word not in word_tags:
# Ex: word_tags: {"rabbit":{"NOUN":15,"VERB":1}}
tag_dict = {}
tag_dict[tag] = 1
word_tags[word] = tag_dict
else:
# If tag exists in word entry, increment by one, else initialize to 1
word_tags[word][tag] = word_tags[word].get(tag,0) + 1
#
# ------------------- TESTING -------------------
# Match each word to most frequent tag for that word
tagged_words = {}
for word in word_tags:
tagged_words[word] = max(word_tags[word],key=word_tags[word].get)
# Get most common tag in training data
common_tag = max(tag_freq,key=tag_freq.get)
test_tagged = []
for sentence in test:
test_sentence = []
for word in sentence:
if word in test_sentence:
continue
elif word in tagged_words:
word_tag = tagged_words[word]
test_sentence.append((word,word_tag))
else:
test_sentence.append((word,common_tag))
test_tagged.append(test_sentence)
# Return tagged test set
return test_tagged |
d89a48ba05e25d612c07f13f57a4d199835d646a | FlinnBurgess/seprcph | /seprcph/goal.py | 3,039 | 3.796875 | 4 | """
This module contains all classes relating to the goals of the game.
"""
from seprcph.event import EventManager, Event
class Goal(object):
"""
Class that describes the player's goals
"""
def __init__(self, start_city, end_city, turns, gold_reward, points_reward, player, desc=""):
"""
Initialise a goal.
The EventManager is also made aware of the topics that Goal wants
to listen for.
Args:
start_city: The city that the player's train must first visit to
start the goal.
end_city: The city that the player's train must visit.
turns: The amount of turns that the player has to complete the goal.
gold_reward: The amount of gold that the player will receive.
points_reward: The number of points that the player will receive.
player: The player the the goal shall be assigned to.
desc: An optional description about the goal.
"""
assert turns > 0
assert points_reward > 0
assert gold_reward > 0
self.start_city = start_city
self.end_city = end_city
self.turns = turns
self.gold_reward = gold_reward
self.points_reward = points_reward
self.player = player
self.desc = desc
self._start_reached = False
EventManager.add_listener('train.arrive', self.handle_train_arrive)
def __repr__(self):
return "<start_city: %s, end_city: %s, turns remaining: %d " \
"gold_reward: %d, points_reward: %d, assigned player: %s " \
"description: %s>" \
% (str(self.start_city), str(self.end_city), self.turns, self.gold_reward,
self.points_reward, str(self.player), self.desc)
def handle_train_arrive(self, ev):
"""
The callback sent to the EventManager to be called when a train arrives
at a city.
Args:
ev: The event that is passed to the EventManager. We expect this
to contain a 'city' attribute.
"""
assert hasattr(ev, 'city')
if ev.city == self.start_city:
self._start_reached = True
elif ev.city == self.end_city and self._start_reached:
self.player.gold += self.gold_reward
self.player.score += self.points_reward
EventManager.notify_listeners(Event('goal.completed',
goal=self))
def update(self):
"""
Called each turn.
Handles the amount of turns a player has to complete a goal and
notifies the EventManager of goal failures.
"""
# TODO: Do we want progress? If so, should it show the amount of turns
# left or the distance the train has travelled?
# TODO: Do we want goal turns to be reduced on another player's turn?
self.turns -= 1
if self.turns <= 0:
EventManager.notify_listeners(Event('goal.failed', goal=self))
|
b21e6ee7a495bb06298bf6e05f8c3c21705b0194 | bkiranid4u/python | /euler_problems/Euler007_10001_Prime.py | 649 | 3.890625 | 4 | """Euler 005 -
Problem:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
from math import sqrt
def is_prime_number(n):
if n <= 3:
return n > 1
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i <= sqrt(n):
if n % i == 0 or n % (i+2) == 0:
return False
i = i + 6
return True
def get_10001_prime_number():
count = 0
i =2
while count < 10001:
if is_prime_number(i):
count += 1
i +=1
print(i-1)
get_10001_prime_number() |
297a3effd1311c6d78d1fd8abca56e50fbce301e | milotr/studying-python-files | /Object-oriented-programming/definition/privateVariable-instance.py | 884 | 4.4375 | 4 | class ExampleClass:
def __init__(self, val = 1):
self.__first = val
def setSecond(self, val = 2):
self.__second = val
exampleObject1 = ExampleClass()
exampleObject2 = ExampleClass(2)
exampleObject2.setSecond(3)
exampleObject3 = ExampleClass(4)
exampleObject3.__third = 5
print(exampleObject1.__dict__)
print(exampleObject2.__dict__)
print(exampleObject3.__dict__)
# The result is this:
# {'_ExampleClass__first': 1}
# {'_ExampleClass__first': 2, '_ExampleClass__second': 3}
# {'_ExampleClass__first': 4, '__third': 5}
# 1
# When you add an instance variable to an object and you're going to do it
# inside any of the object's methods, it goes in the following way:
# it puts a class name before your name and puts an additional underscore
# at the beginning
# It is fully accessible from outside the class
print(exampleObject1._ExampleClass__first) |
29a624569926e2c586113afca8360147e0340a11 | zunayed/puzzles_data_structures_and_algorithms | /practice_problems_python/insertion_sort.py | 428 | 4.125 | 4 | def insertionSort(num_list):
for item in range(1,len(num_list)):
current = num_list[item]
position = item
print "current"
print current
print num_list
while position > 0 and num_list[position - 1] > current:
print "in"
num_list[item] = num_list[position - 1]
position = position - 1
num_list[position] = current
return num_list
num_list = [54,26,93,17,77,31,44,55,20]
print insertionSort(num_list) |
a83766cc721dc159d2aa2f7df2aa4236bf3f3bb4 | ktaletsk/daily-problem | /191219/Python/solution.py | 342 | 3.734375 | 4 | def getBonuses(performance):
return [1 +
((1 if performance[i]>performance[i-1] else 0) if i>0 else 0) +
((1 if performance[i]>performance[i+1] else 0) if i<len(performance)-1 else 0) for i in range(len(performance))]
def main():
print(getBonuses([1, 2, 3, 2, 3, 5, 1]))
if __name__== "__main__":
main() |
5b29f5b66eb705527e330e27f1d143de275f1e7c | sMamooler/Higgs-Boson-Classification | /implementations.py | 5,260 | 3.703125 | 4 | import numpy as np
from proj1_helpers import *
def compute_gradient(y, tx, w):
"""Compute the gradient.
Parameters:
y: target lables; an array of shape (N,1). N: Number of datapoints.
tx: datapoint features; an array of shape (N,D+1). N: number of datapoints, D: number of features.
w: current weights.
Returns:
the gradient of the MSE loss function using w as weights.
"""
N = len(y)
e = y-tx.dot(w)
return (tx.T.dot(e))/-N
def compute_stoch_gradient(y, tx, w):
"""Compute a stochastic gradient from just few examples n and their corresponding y_n labels."""
err = y - tx.dot(w)
grad = - tx.T.dot(err) / len(err)
return grad, err
def get_mse_loss(y, tx, w):
"""Calculates the mse loss."""
pred = tx.dot(w)
err = y - pred
return 1/2 * np.mean(err ** 2)
def compute_rmse(y, tx, w):
return np.sqrt(2*get_mse_loss(y, tx, w))
def compute_loss(y, tx, w):
"""compute the rmse loss for regression models (ridge regression and cross validation)"""
pred = tx.dot(w)
pred[np.where(pred>=0)] = 1
pred[np.where(pred<0)] = -1
err = y - pred
loss= 1/2 * np.mean(err ** 2)
return loss
def sigmoid(x):
"""Computes the sigmoid of x."""
return np.exp(-np.logaddexp(0, -x))
def compute_logistic_gradient(y, tx, w) :
"""Gradient of the loss function in logistic regression. """
"""Activation function used here is the sigmoid """
return tx.T.dot(sigmoid(tx.dot(w)) - y)
def compute_logistic_loss(y, tx, w) :
"""Loss is given by the negative log likelihood. """
predictions = tx.dot(w)
return np.sum(np.logaddexp(0, predictions)) - y.T.dot(predictions)
def least_squares_GD(y, tx, initial_w, max_iters, gamma):
"""Gradient descent algorithm.
Parameters:
y: target lables; an array of shape (N,1). N: Number of datapoints.
tx: datapoint features; an array of shape (N,D+1). N: number of datapoints, D: number of features.
initial_w: initial weights.
max_ietrs: number of iterations.
gamma: learning rate.
Returns:
w: optimized weights.
loss: final loss.
"""
w = initial_w
loss = 0
w = initial_w
for n_iter in range(max_iters):
loss = get_mse_loss(y, tx, w)
grad = compute_gradient(y, tx, w)
w = w - gamma * grad
return w, loss
def least_squares_SGD(y, tx, initial_w, max_iters, gamma):
"""Stochastic gradient descent algorithm."""
w = initial_w
batch_size = 1 # default value as indicated in project description
for n_iter in range(max_iters):
for y_batch, tx_batch in batch_iter(y, tx, batch_size, num_batches=1):
grad, _ = compute_stoch_gradient(y_batch, tx_batch, w)
w = w - gamma * grad
loss = get_mse_loss(y, tx, w)
print("loss={l}".format(l=loss))
print("grad={grad}".format(grad=np.linalg.norm(grad)))
print("weight={w}".format(w=np.linalg.norm(w)))
return w, loss
def least_squares(y, tx):
"""
Least squares regression using normal equations
Arguments:
y: target labels
tx: data features
Return:
w: the optimized weights vector for this model
loss: the final MSE loss of the model
"""
matrix = tx.T.dot(tx)
vector = tx.T.dot(y)
w = np.linalg.solve(matrix, vector)
loss = get_mse_loss(y, tx, w)
return w, loss
def ridge_regression(y, tx, lambda_):
"""
Ridge regression using normal equations.
Parameters:
y: target lables; an array of shape (N,1). N: Number of datapoints.
tx: datapoint features; an array of shape (N,D+1). N: number of datapoints, D: number of features.
lambda_: the hyperparametrs used to balance the tradeoff between model complexity and cost.
Returns:
w: optimized weights.
"""
lambda_ = lambda_ * 2 * len(y)
M = tx.T.dot(tx)
w = np.linalg.solve(M + lambda_*np.identity(M.shape[0]), tx.T.dot(y))
loss = compute_loss(y, tx, w)
return w, loss
def logistic_regression(y, tx, initial_w, max_iters, gamma):
"""Logistic regression using stochastic gradient descent """
w = initial_w
for n_iter in range(max_iters) :
grad = compute_logistic_gradient(y, tx, w)
loss = compute_logistic_loss(y, tx, w)
w = w - gamma * grad
return w, loss
def reg_logistic_regression(y, tx, lambda_, initial_w, max_iters, gamma):
"""
Regularized logistic regression using gradient descent
Arguments:
y: target labels
tx: data features
lambda_: regularization parameter
initial_w: w_0, initial weight vector
max_iters: maximum iterations to run
gamma: the learning rate or step size
Returns:
w: the optimized weights vector for this model
loss: the final optimized logistic loss
"""
w = np.zeros(tx.shape[1]) if initial_w == None else initial_w
for _ in range(max_iters):
gradient = compute_logistic_gradient(y, tx, w) + 2 * lambda_ * w # todo
loss = compute_logistic_loss(y, tx, w) + (lambda_ / 2) * w.T.dot(w)
w = w - gamma * gradient
print("loss for reg log ")
print(loss)
return w, loss
|
7d81c86053c60c8a7c3026b4b2c9a6494ecae47c | BlesslinJerishR/PyCrash | /__4__WorkingWithLists__/pizzas.py | 233 | 3.828125 | 4 | #4.1
pizzas = ["cheese","macroni","tomato","pasta","pineapple"]
if __name__ == '__main__':
for pizza in pizzas:
print(f"Have you tasted {pizza.title()} pizza ?\n")
print("How much you like pizza ?")
print("I really love pizza")
|
a15b901df39dcb09e40d280b97ee0d68642fe12e | mamert/pi_mover_thingy | /proof-of-concept/motors/MotorDriver.py | 1,531 | 3.578125 | 4 | from abc import ABC, abstractmethod # AbstractBaseClass
import pigpio
class MotorDriver(ABC): # is NOT aware of PWM range
""" Single motor control, parent class """
def __init__(self, pi, pins):
self.__pi = pi
self.__pins = pins
def setup(self, freq, range):
for pin in (self.__pins.values()):
self.__pi.set_mode(pin, pigpio.OUTPUT)
self.__pi.set_PWM_frequency(pin, freq)
self.__pi.set_PWM_range(pin, range)
self.__pi.set_PWM_dutycycle(pin, 0)
def pi(self):
""" convenience to avoid super in subclasses """
return self.__pi
def pins(self):
""" convenience to avoid super in subclasses """
return self.__pins
@abstractmethod
def move(self, isBackward, pwmDuty): pass
class L298N(MotorDriver):
""" Can use 2 of these per 1 L298 module.
pins: "En", "In0", "In1" """
def move(self, isBackward, pwmDuty):
self.pi().set_PWM_dutycycle(self.pins()["En"], pwmDuty)
self.pi().write(self.pins()["In0"], 0 if (isBackward or pwmDuty == 0) else 1)
self.pi().write(self.pins()["In1"], 0 if (not isBackward or pwmDuty == 0) else 1)
class BTS796(MotorDriver):
""" Pull Enable pins up. No reason to use them, BOTH must be HIGH anyway.
pins: "PWM1", "PWM2" """
def move(self, isBackward, pwmDuty):
self.__pi.set_PWM_dutycycle(pins["PWM1"], pwmDuty if isBackward else 0)
self.__pi.set_PWM_dutycycle(pins["PWM2"], pwmDuty if not isBackward else 0)
|
8a0660166d746ba89597e9668bf9ec1d24d3687e | caiquemarinho/python-course | /Exercises/Module 04/exercise_04.py | 95 | 4.03125 | 4 | """
Print the square of the given number
"""
num = 5
print(f'Square of {num} is {num**2}')
|
c7a69bdb176bd05e8b2d366b9eb2c6909caf555d | JyHu/PYStudy | /PYDayByDay/Tkinter_ST/Dialg_TK/Dialg2.py | 1,376 | 3.78125 | 4 | #coding=utf-8
__author__ = 'JinyouHU'
'''
askinteger:输入一个整数值
askfloat:输入一个浮点数
askstring:输入一个字符串
'''
from Tkinter import *
from tkSimpleDialog import *
root = Tk()
root.geometry('220x120+0+0')
reInt = IntVar
reFloat = FloatType
reString = StringVar
def intFunc():
# 输入一个整数,
# initialvalue指定一个初始值
# prompt提示信息
# title提示框标题
reInt = askinteger(title = 'prompt',prompt = 'input a integer:',initialvalue = 100)
LB1['text']=str(reInt)
def floatFunc():
# 输入一浮点数
# minvalue指定最小值
# maxvalue指定最大值,如果不在二者指定范围内则要求重新输入
reFloat = askfloat(title = 'float',prompt = 'input a float',minvalue = 0,maxvalue = 11)
LB2.set(str(reFloat))
def stringFunc():
# 输入一字符串
reString = askstring(title = 'string',prompt = 'input a string')
LB3['text']=reString
Button(root, text='integer', command=intFunc).place(x=0,y=0)
Button(root, text='float', command=floatFunc).place(x=80,y=0)
Button(root, text='string', command=stringFunc).place(x=140,y=0)
LB1 = Label(root,text='int value here').place(y=40)
LB2 = Label(root,text='float value here').place(y=60)
LB3 = Label(root,text='string value here').place(y=80)
root.mainloop()
# 返回值为各自输入的值。 |
a4be0553d393a20374a2aa20e622cd8dca309459 | killian2k/MyTorch | /mytorch/dropout.py | 686 | 3.5625 | 4 | import numpy as np
class Dropout(object):
def __init__(self, p=0.5):
# Dropout probability
self.p = p
self.mask = np.zeros(None)
def __call__(self, x):
return self.forward(x)
def forward(self, x, train = True):
# 1) Get and apply a mask generated from np.random.binomial
# 2) Scale your output accordingly
# 3) During test time, you should not apply any mask or scaling.
if train:
self.mask = np.random.binomial(1,self.p,x.shape)
#Invert the mask
return np.multiply(x,self.mask)/self.p
return x
def backward(self, delta):
print(delta)
return np.multiply(delta,self.mask)
|
90bc79514216766e260dd5fb3a8549c370d75c69 | amelialin/tuple-mudder | /ex12.py | 534 | 4.125 | 4 | age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
# This accomplishes the same thing as:
# print "How old are you?",
# age = raw_input()
# print "How tall are you?",
# height = raw_input()
# print "How much do you weigh?",
# weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." % (
age, height, weight)
# STUDY DRILLS
# to look up documentation on a python command? function? use:
# python -m pydoc XXXX
# e.g. python -m pydoc raw_input |
2fb50288fe6345afe39a9c8ce321fb3dd1e5a423 | jopemachine-playground/Algorithm-HW | /Assign02/fibonacchi.py | 1,263 | 4.03125 | 4 | def fibonacci_recursive(n):
if n == 0:
return 0
if n == 1:
return 1
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
def fibonacci_bottomup(n):
if n == 0: return 0
prev1 = 0
prev2 = 1
for i in range(2, n + 1, 1):
temp = prev2
prev2 = prev1 + prev2
prev1 = temp
return prev2
def fibonacci_squaring(n):
if n < 2:
return n
matrix = [[1, 1], [1, 0]]
POW.cache = dict()
return POW(matrix, n)[1][0]
def POW(A, n):
if n == 1:
return A
# Apply DP
if n in POW.cache:
return POW.cache[n]
if n % 2 == 0:
POW.cache[n] = MultiplyMatrix(POW(A, n/2), POW(A, n/2))
else:
POW.cache[n] = MultiplyMatrix(MultiplyMatrix(POW(A, (n-1)/2), POW(A, (n-1)/2)), A)
return POW.cache[n]
# assume Matrix A and B are same size
def MultiplyMatrix(Matrix_A, Matrix_B):
ret = [[None]*len(Matrix_A) for i in range(0, len(Matrix_A))]
for i in range(0, len(Matrix_A)):
for j in range(0, len(Matrix_A)):
sum = 0
for k in range(0, len(Matrix_A)):
sum += Matrix_A[i][k] * Matrix_B[k][j]
ret[i][j] = sum
return ret;
if __name__ == "__main__":
pass
|
f3c0f57c750e40488318d88e0ee813d2badf3154 | DanielSacro/coding-projects | /Huffman-Coding/huffman.py | 5,968 | 3.921875 | 4 | class TreeLeaf:
"""
Leaf node of a Huffman tree. Stores the value.
Should store an 8-bit integer to represent a single byte, or None
to indicate the special "end of file" character.
"""
def __init__(self, uncompressed_byte):
self.__value = uncompressed_byte
def getValue(self):
return self.__value
def __str__(self):
return "Leaf storing " + str(self.getValue())
def __repr__(self):
s = "<%d> %s" % (id(self), self.__str__())
return(s)
class TreeBranch:
"""
Simple representation of a subtree/tree of a Huffman tree.
Just stores the two children.
"""
def __init__(self, lchild, rchild):
self.__left = lchild
self.__right = rchild
def getLeft(self):
return self.__left
def getRight(self):
return self.__right
def __str__(self):
s = "(" + str(self.getLeft()) + " <- branch root -> "
s += str(self.getRight()) + ")"
return(s)
def __repr__(self):
s = "<%d> %s" % (id(self), self.__str__())
return(s)
def custom_min(trees):
""" Takes a list of tuples called trees, finds the smallest
item and removes it from the list. Both the smallest item and
new list are returned.
Each item in trees is a tuple of (symbol, frequency)
"""
if len(trees) == 0:
raise ValueError("The list passed as input was empty.")
# default to the first item
min_item = trees[0]
min_index = 0
for i in range(len(trees)):
# if this item has a smaller frequency
if trees[i][1] < min_item[1]:
min_item = trees[i]
min_index = i
del trees[min_index]
return min_item[0], min_item[1], trees
def make_tree(freq_table, inclEOF=True):
"""
Constructs and returns the Huffman tree from the given frequency table.
"""
trees = []
if inclEOF: # Use None to represent EOF
trees.append((TreeLeaf(None), 1))
for (symbol, freq) in freq_table.items():
trees.append((TreeLeaf(symbol), freq))
while len(trees) > 1:
right, rfreq, trees = custom_min(trees)
left, lfreq, trees = custom_min(trees)
trees.append((TreeBranch(left, right), lfreq+rfreq))
return trees[0][0]
def make_encoding_table(huffman_tree):
"""
Given a Huffman tree, will make the encoding table mapping each
byte (leaf node) to its corresponding bit sequence in the tree.
"""
encoding_table = {}
preorder(huffman_tree, encoding_table, ())
return encoding_table
def preorder(tree, table, path):
"""
Traces out all paths in the Huffman tree and adds each
corresponding leaf value and its associated path to the table.
"""
if isinstance(tree, TreeLeaf): # base case
# note, if this is the special end file entry then
# it stores table[None] = path
table[tree.getValue()] = path
elif isinstance(tree, TreeBranch):
# the trailing comma (,) means this is properly interpreted
# as a tuple and not just a single boolean value
preorder(tree.getLeft(), table, path + (False, ))
preorder(tree.getRight(), table, path + (True, ))
else:
raise TypeError('{} is not a tree type'.format(type(tree)))
def make_freq_table(stream):
"""
Given an input stream, will construct a frequency table
(i.e. mapping of each byte to the number of times it occurs in the stream).
The frequency table is actually a dictionary.
"""
freq_dict = {}
bsize = 512 # Use variable, to make FakeStream work
buff = bytearray(bsize)
end_of_stream = False
while not end_of_stream:
# read bytes into a pre-allocated bytes-like object (bytearray)
# and return number of bytes read
count = stream.readinto(buff)
for single_byte in buff:
if single_byte not in freq_dict:
freq_dict[single_byte] = 1
else:
freq_dict[single_byte] += 1
if count < bsize: # end of stream
end_of_stream = True
return freq_dict
# ***************************************************
# Unit testing and support for Huffman
# ***************************************************
class FakeStream:
"""
Creates a fake stream, supplies readinto().
This is a lot easier to do here in Python compared to C++ (where it
it possible, but a lot harder).
Note that this manipulates buff, which might cause issues with the
iterator for buff. Works here, but perhaps not in general.
"""
def __init__(self, theString):
self.__value = theString
def readinto(self, buff):
sbuf = bytearray(self.getValue(), 'utf-8')
ll = len(sbuf)
buff[0:ll] = sbuf[0:ll]
del buff[ll:] # FIXME Careful with real buff's
return ll
def getValue(self):
return self.__value
def __str__(self):
return "Fake stream " + str(self.getValue())
def __repr__(self):
s = "<%d> %s" % (id(self), self.__str__())
return(s)
def testmain():
leafA = TreeLeaf('A')
leafB = TreeLeaf('B')
leafC = TreeLeaf('C')
print(leafA)
print(leafA.getValue())
print(leafB)
branch = TreeBranch(leafA, leafB)
print(branch)
print(branch.getLeft()) # leafA
print(branch.getRight()) # leafB
mytree = TreeBranch(branch, leafC)
print(mytree)
print(make_encoding_table(mytree))
# Test __repr__
rlist = [leafA, leafB, leafC, branch]
print(rlist)
# Create string from workbook
exStr = 'a'*45 + 'b'*13 + 'c'*12 + 'd'*16 + 'e'*9 + 'f'*5
print(exStr)
freqs = make_freq_table(FakeStream(exStr))
print(freqs)
tree = make_tree(freqs, inclEOF=False) # No EOF to match workbook
print(make_encoding_table(tree))
return
if __name__ == "__main__":
testmain()
|
a703af8bed003172ed97bfc91dbd87ee103664a8 | KlimChugunkin/PyBasics-Course | /Perper_Leonid_dz_8/task_8_4.py | 859 | 3.8125 | 4 | """
Задание 4
Написать декоратор с аргументом-функцией (callback), позволяющий валидировать входные значения функции и выбрасывать
исключение ValueError. Замаскировать работу декоратора.
"""
from functools import wraps
def val_checker(arg_check_func):
def _val_checker(func):
@wraps(func)
def wrapper(*args):
if not all([arg_check_func(arg) for arg in args]):
raise ValueError('Wrong_input')
return func(*args)
return wrapper
return _val_checker
@val_checker(lambda x: 0 < x < 1000)
def calc_sum(*args):
result = 0
for num in args:
result += num
return result
print(calc_sum(5, 8, 1, 10, 3), calc_sum.__name__, sep=', ')
|
bc554f261de646882249b178fa479e3ce6a844bb | ankschoubey/Personal-Developer-Notes | /leetcode-lru.py | 1,436 | 3.578125 | 4 | class CacheItem:
def __init__(self, id, value, compValue=1, order = 1) -> None:
self.id = id
self.compValue = compValue
self.value = value
self.order = order
class PriorityQueue:
items = []
def add(self, item: CacheItem):
self.items.append(item)
self.sort()
def sort(self):
self.items.sort(key = lambda x: (x.compValue, x.order))
def pop(self):
return self.items.pop(0)
class LFUCache:
pq = PriorityQueue()
cache = {}
def __init__(self, capacity: int):
self.size = capacity
def get(self, key: int) -> int:
value = self.cache.get(key, -1)
if value == -1:
return value
value.compValue += 1
self.pq.sort()
return value.value
order = 1
def put(self, key: int, value: int) -> None:
if key in self.cache.keys():
item = self.cache[key]
item.value = value
self.pq.sort()
return
item = CacheItem(key, value, 1, self.order)
self.order +=1
if len(self.cache) == self.size:
popped = self.pq.pop()
del self.cache[popped.id]
self.pq.add(item)
self.cache[key] = item
# Your LFUCache object will be instantiated and called as such:
# obj = LFUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value) |
c1c9732df90bcd7ff7fc5eec147053219365a454 | henryxian/leetcode | /reverse_words_in a_string.py | 399 | 3.765625 | 4 | # 151. Reverse Words in a String
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
splitted = s.split()
rev_str = ""
if len(splitted):
rev = splitted[::-1]
for word in rev:
rev_str = rev_str + " " + word
rev_str = rev_str.strip()
return rev_str |
a3d6417c71bd7c3f26514940fe2b84b04b90327a | jacqxu00/SoftDevProject0 | /db.py | 1,451 | 3.546875 | 4 | import sqlite3 #enable control of an sqlite database
import csv #facilitates CSV I/O
import hashlib
f="storytime.db"
db = sqlite3.connect(f) #open if f exists, otherwise create
c = db.cursor() #facilitate db ops
#==========================================================
#INSERT YOUR POPULATE CODE IN THIS ZONE
c.execute("CREATE TABLE users (user TEXT PRIMARY KEY, pass TEXT);")
c.execute("CREATE TABLE edit (id INT, user TEXT, section INT, content TEXT);")
c.execute("CREATE TABLE stories (id INT PRIMARY KEY, title TEXT, numsections INT);")
pw1 = hashlib.md5('crazy').hexdigest()
pw2 = hashlib.md5('pass').hexdigest()
pw3 = hashlib.md5('mashed').hexdigest()
c.execute("INSERT INTO users VALUES('bananas',\"%s\");"%(pw1))
c.execute("INSERT INTO users VALUES('jackie',\"%s\");"%(pw2))
c.execute("INSERT INTO users VALUES('potato',\"%s\");"%(pw3))
c.execute("INSERT INTO stories VALUES(0, 'Pizza Man', 1);")
c.execute("INSERT INTO edit VALUES(0, 'bananas', 1, 'There once was a pizza man who delivered pizzas');")
c.execute("INSERT INTO stories VALUES(1, 'The Dirty Wall', 1);")
c.execute("INSERT INTO edit VALUES(1, 'jackie', 1, 'The wall was dirty.');")
c.execute("INSERT INTO stories VALUES(2, 'Huge Scandal', 1);")
c.execute("INSERT INTO edit VALUES(2, 'potato', 1, 'Huge scaldal is huge scandal but with an l.');")
#==========================================================
db.commit() #save changes
db.close() #close database
|
f0e2ea9dde95edae40c32f1bdd502a3416eab142 | pedrolucas-correa/ies-python-lists | /Lista2/Lista 2 - Q. 10.py | 324 | 3.546875 | 4 | sexo = int(input("Digite 1 para feminino e 2 para masculino: "))
altura = float(input("Digite sua altura: "))
if sexo == 2:
pesoideal = (72.7 * altura) - 58
print("Seu peso ideal é: ", round(pesoideal, 2))
else:
pesoideal = (62.1 * altura) - 44.7
print("Seu peso ideal é: ", round(pesoideal, 2))
|
c7f5f2f650aa525ab013f5559f9d6327981bf6a0 | kmandli/Neural-Networks-Implementations | /Neural_Network.py | 4,109 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 10 11:24:50 2017
@author: kavya
"""
# Neural Networks
from math import exp
from random import seed
import numpy as np
from collections import defaultdict
from sklearn import datasets
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import LeaveOneOut
#forward propagation
def forward_propagation(network, ip):
inputs = ip
for layer in network:
new_ips = []
for n in layer:
a = activate(n['weights'], inputs)
n['output'] = 1.0 / (1.0 + exp(-a))
new_ips.append(n['output'])
inputs = new_ips
return inputs
# back propagation
def backward_propagation(network, ex_output):
for i in reversed(range(len(network))):
layer = network[i]
errors = list()
if i != len(network) - 1:
for j in range(len(layer)):
error = 0.0
for n in network[i + 1]:
error += (n['weights'][j] * n['bias'])
errors.append(error)
else:
for j in range(len(layer)):
n = layer[j]
errors.append(ex_output[j] - n['output'])
for j in range(len(layer)):
n = layer[j]
n['bias'] = errors[j] * (n['output']* (1.0 - n['output']))
#activation function
def activate(weights, ips):
a = weights[-1]
for i in range(len(weights) - 1):
a += weights[i] * ips[i]
return a
# Update weights with error through backpropagation
def update_weights(network, row, learning_rate):
for i in range(len(network)):
inputs = row[:-1]
if i !=0:
inputs = [n['output'] for n in network[i - 1]]
for n in network[i]:
for j in range(len(inputs)):
n['weights'][j] += learning_rate * n['bias'] * inputs[j]
n['weights'][-1] += learning_rate * n['bias']
#preperaing the iris dataset
seed(1)
iris_dataset = datasets.load_iris()
X1 = iris_dataset.data[50:150,:]
X = np.array(X1[:,2:4])
#Normalizing the data using MinMax normalization
scaler = MinMaxScaler()
scaler.fit(X)
X = (scaler.transform(X))
target= np.array(iris_dataset.target[50:150]).reshape(100,1)
#converting 1's to 0's and 2's to 1's
target[target==1]=0
target[target==2]=1
no_inputs = 2
no_outputs = 1
no_iter=10
iter_list = []
e = []
e_1 =[]
weight1_list=[]
weight2_list=[]
wt={}
loo = LeaveOneOut()
for train_index, test_index in loo.split(X1):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
print(X_train, X_test, target)
#initializing weights with random values between 0 and 1
network = list()
hidden_layer = [{'weights': [np.random.uniform(0.0, 1.0) for i in range(no_inputs + 1)]} for i in range(2)]
network.append(hidden_layer)
output_layer = [{'weights': [np.random.uniform(0.0, 1.0) for i in range(3)]} for i in range(no_outputs)]
network.append(output_layer)
newwt=defaultdict(list)
#training the network
for n in range(no_iter):
error = 0
for row in X_train:
outputs = forward_propagation(network, row)
expected_op = [0 for i in range(no_outputs)]
#expected[int(row[-1])] = 1
#cost
error += sum(([np.sum(np.multiply(expected_op[i], np.log(outputs[i])) + np.multiply((1-expected_op[i]), np.log(1-outputs[i]))) for i in range(len(expected_op))]))
error = -(error)
backward_propagation(network, expected_op)
update_weights(network, row, 0.5)
#Appending the weights of individual parameters to the lists
iter_list.append(n)
e.append(error)
error = int((error)*100)
print('>Iteration=%d, error=%.3f' % (n, error))
e_1.append(error)
length = len(e_1)
average = ((sum(e_1))/length)
print("Average error rate for prediction= %.2f %%"%(average))
|
b74826b01ce47894de071df38fc75678fd894467 | akhilakr06/pythonluminar | /oop/Add.py | 119 | 3.5625 | 4 | class Add:
def set(self,a,b):
self.a=a
self.b=b
print(self.a+self.b)
sum=Add()
sum.set(4,5) |
a116bbaa36505cd72877d008880df2f08981a79f | ChuanleiGuo/AlgorithmsPlayground | /LeetCodeSolutions/python/572_Subtree_of_Another_Tree.py | 843 | 3.734375 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def is_same(sub1, sub2):
if sub1 is None and sub2 is None:
return True
if sub1 is None or sub2 is None:
return False
if sub1.val != sub2.val:
return False
return is_same(sub1.left, sub2.left) and \
is_same(sub1.right, sub2.right)
if s is None:
return False
if is_same(s, t):
return True
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
|
dd5712d29de30b8d785bf9420757d2771c548258 | NegruGeorge/LFTC-labs | /lab2.py | 2,037 | 3.625 | 4 | f = open("input.py","r")
# for line in f:
# print(len(line))
# for s in line:
# print(s =="\n")
# print(s==" ")
# break
def cuvantRezervat(cuv):
if(cuv =="**" or cuv == "<=" or cuv ==">=" or cuv =="==" or cuv == "!="):
# print(cuv + "?/////////////////////")
return True
return False
def printAtomi1(file:str):
for line in file:
atom = ""
cuvRez=0
ghilimele = 0
for s in line:
# matcheaza inceput de string
if(s=='"'):
ghilimele+=1
if(ghilimele!=0):
# verifica ce a fost inainte de string si afiseaza
# verifica daca urmatorul caracter e " adica daca incepe un string, daca da atunci afiseaza atomul de inainte
if(s=='"' and ghilimele==1):
print(atom)
atom=""
elif s in " !():,*-+/%**><>=<=\n" :
# in caz ca am un cuvant rezervat (>= != ) imi returneaza true si merge mai departe pentru a l cauta
if cuvantRezervat(atom + s):
cuvRez=1
# in caz ca nu e cuvant rezervat si urmatorul caracter se afla in multimea de mai sus
# afisam atomul ce era inainte gasit (daca acesta e diferit de "")
elif len(atom) !=0:
print(atom)
if cuvRez!=1:
atom=""
cuvRez=0
# aici verificam daca cumva atom ul era cuvant din multimea respectiva sau cuvant rezervat
# daca era atunci il afisam
elif (len(atom)!=0 and atom in " !():,*-+/%**><>=<=\n") or cuvantRezervat(atom):
print(atom)
atom =""
if(s!=" "):
atom+=s
if(s==" " and ghilimele!=0):
atom+=s
if(ghilimele==2):
ghilimele=0
printAtomi1(f)
#paranteza trebuie afisata goala
|
edbdbb39c3503c78cef153d269c89c64626ed1cc | su2me2rain/lethuylinh-fundamental-c4e16 | /Session 1/Circle_area.py | 106 | 4.09375 | 4 | r= float(input("What is your radius? "))
area = 3.14159 * r**2
print("The area of your circle is ", area)
|
f678f32677b1c80188d85ef8092b7d225e11276a | GhostBat101/SomeBasicStuffs | /ClassinClass.py | 406 | 3.625 | 4 | class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
self.lap = self.Laptop()
def showinfo(self):
print(self.name, self.roll)
class Laptop:
def __init__(self):
self.brand = 'hp'
self.ram = 16
self.cpu = 'ryzen 9'
s1 = Student('Jack', 20)
s2 = Student('Rohan', 10)
print(s1.showinfo())
|
551f98ae926c5716d72545a45036aef59558ae13 | kmggh/rajbots | /robots/minmax_bot.py | 375 | 3.71875 | 4 | """
Attempts to win every tile (including negatives) by playing its highest
or lowest card.
"""
from raj import Player
class MinMaxBot(Player):
"""
MinMax will return its smallest or largest card, depending upon the current tile
"""
def play_turn(self):
if self.board.current_tile.value < 0:
return self.cards[0]
else:
return self.cards[-1]
|
dab38f37cd14c53f641ce5a453350c683e97e20a | a1424186319/tutorial | /sheng/tutorial/L3函数/递归练习2.py | 233 | 3.53125 | 4 | # 计算1+2+3 ....+99+100
def f(n):
if n >= 0:
return f(n - 1)+n
else:
return 0
print(f(100))
# 高斯算法公式n*(1+n)/2
def f(n):
if n == 1:
return 1
return f(n - 1)+n
print(f(100))
|
d7e5111382f2368564d228026c1d212c882a5284 | Fatihnalbant/deneme_2 | /sozcukListe.py | 649 | 4.1875 | 4 | """
Bir yazı okuyunuz.
Yazı boşluk karakterleriyle ayrılmış sözcüklerden oluşmuş olsun.
Aynı sözcükleri atarak sözcükleri bir listeye yerleştiriniz.
Örneğin girilen yazı şöyle olsun:
bugün hava evet bugün çok hava güzel güzel
Sonuç olarak şöyle bir liste elde edilmeli:
['bugün', 'hava', 'evet', 'çok', 'güzel']
Elde edilen listedeki sözcüklerin yazıdaki sözcük sırasında olması gerekmektedir.
"""
# s = print('Bir yazı giriniz:')
s = 'bugün hava evet bugün çok hava güzel güzel'
result = []
for word in s.split():
if word not in result:
result.append(word)
print(result)
|
aef77eb30c56e746db93b9eab7767e773550fa19 | mysqlbin/python_note | /2020-03-24-Python-ZST-base/2020-08-28-条件循环控制/2020-04-19-03.py | 736 | 3.734375 | 4 | #!/usr/bin/ptyhon
#coding=gbk
"""
"""
count = 5
while count > 0:
count = count - 1
if count == 3:
continue
print('ݿͱÿһ,count: {}'.format(count))
"""
count = 5 0count143 ݿͱÿһ,count: 4
count = 4 0count13 ѭ
count = 3 0count123 ݿͱÿһ,count: 2
count = 2 0count113 ݿͱÿһ,count: 1
count = 1 0count103 ݿͱÿһ,count: 0
0 0ѭ
"""
|
ac0b55b77fc3b4e7fa117d9c762c94b203959deb | liangyf22/test | /02_面向对象/类实现装饰器.py | 382 | 4.21875 | 4 | # 实现了__call__方法的类,允许一个类的实例像函数一样被调用:x(a, b) 调用 x.__call__(a, b)
class Myclass(object):
def __init__(self,func):
self.func =func
def __call__(self, *args, **kwargs):
print("洗手")
self.func()
print("擦嘴")
@Myclass # func = Myclass()
def func():
print("吃饭了")
func() |
2ed4c0194cd43fe92a101a848673cc78e0bd3504 | lukethink/projecteuler | /problem19.py | 1,772 | 4.3125 | 4 | """
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
#create a year list of lengths of months, leaving out December due to firsts of months list later:
month_days = [31,28,31,30,31,30,31,31,30,31,30]
#second entry (28) will change to 29 during a leap year
#function to produce list of 1st days of month as 'x' day of the year, based on month_days:
def firsts_of_month(month_days):
array = [1]
x = 1
for i in month_days:
x += i
array.append(x)
return (array)
import calendar
count = 0 #count each Sunday == 1st month
y = 6 #1st Jan 1901 was a Tuesday, so Sunday was 6th. 'y' will change for each year.
for year in range(1901,2001):
if calendar.isleap(year) == True:
month_days[1] = 29 #allocate 29 days to Feb
firsts = firsts_of_month(month_days) #calculate list of 1st days based on Feb change
for b in range(y,367,7): #iterate through Sundays
for a in firsts: #iterate through first days
if a == b:
count += 1
if b >= 360:
y = b - 359 #leap year formula to get next year's first Sunday
else:
month_days[1] = 28 #allocate 28 days to Feb
firsts = firsts_of_month(month_days) #calculate list of 1st days based on Feb change
for b in range(y,366,7): #iterate through Sundays
for a in firsts: #iterate through first days
if a == b:
count += 1
if b >= 359:
y = b - 358 #non-leap year formula to get next year's first Sunday
print (count) |
6116801d0904cc21984027d04ce470ae288cbaa1 | sontung/libgeom | /math_utils.py | 1,438 | 3.84375 | 4 | import numpy as np
def cross(a, b):
"""
Calculate cross product of 2 vector a and b. a, b is array has shape (3, 1)
:param a:
:param b:
:return:
"""
a1, a2, a3 = a
b1, b2, b3 = b
ss = [a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1]
return np.array(ss)
def dot(a, b):
"""
Calculate dot product of 2 vector a and b. a, b is array has shape (3, 1)
:param a:
:param b:
:return:
"""
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
def ray_intersects_triangle(ray_origin, ray_vector, triangle):
"""
[optimized]
Möller–Trumbore ray-triangle intersection algorithm
(https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm)
:param ray_origin:
:param ray_vector:
:param triangle:
:return:
"""
epsilon = 0.0000001
vertex0 = triangle[0]
vertex1 = triangle[1]
vertex2 = triangle[2]
edge1 = vertex1 - vertex0
edge2 = vertex2 - vertex0
h = cross(ray_vector, edge2)
a = dot(edge1, h)
if -epsilon < a < epsilon:
return None
f = 1.0 / a
s = ray_origin - vertex0
u = f * dot(s, h)
if u < 0.0 or u > 1.0:
return None
q = cross(s, edge1)
v = f * dot(ray_vector, q)
if v < 0.0 or u+v > 1.0:
return None
t = f * dot(edge2, q)
if t > epsilon:
res = ray_origin + ray_vector * t
return res
else:
return None
|
4ff279b67e4d1c545225312978b72ce5ec7f39fe | iamsamueljohnson/CP1404practicals | /Practical_01/loops.py | 361 | 4.15625 | 4 | for i in range(0, 101, 10):
print(i, end=' ')
print()
for i in range(20, 0, -1):
print(i, end=' ')
print()
for i in range(20, 0, -1):
print(i, end=' ')
print()
number = int(input("Enter number: "))
for i in range(number):
print(end='*')
print()
number = int(input("Enter number: "))
for i in range(1, number + 1):
print(i * '*')
print()
|
40988a3f2f1b700a9b2abeddadf8bd621b8e38a0 | Payiz-2022/python | /study/list.py | 843 | 4.03125 | 4 | # -*- coding: utf-8 -*-
#列表数据类型,有序的集合,可以随时添加和删除其中的元素[]
classmate = ['A','B','C']
print(classmate)
print(len(classmate))#获取list元素个数
print(classmate[0])
print(classmate[-1])
classmate.append('D')#末尾添加元素
print(classmate)
classmate.insert(1,'AB')#把元素插入到指定位置
print(classmate)
classmate.pop()
print(classmate)
classmate.pop(1)#删除指定位置元素
print(classmate)
L = [
['Apple','Google','Microsoft'],
['Java','Python','Ruby','PHP'],
['Adam','Bart','Lisa']
]
#打印Apple
print(L[0][0])
#打印python
print(L[1][1])
#打印Lisa
print(L[2][2])
url = 'https://www.autohome.com.cn/grade/carhtml/'
letters = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
for letter in letters:
letter = url+letter+'.html'
print(letter+'123') |
c6b70100c057566516457c6c40dd254c018400c6 | kuohan95/Virtual-Machine | /log_analysis.py | 2,736 | 4.03125 | 4 | #!/usr/bin/env python2
import psycopg2
DBNAME = "news"
def db_connect():
""" Creates and returns a connection to the database defined by DBNAME,
as well as a cursor for the database.
Returns:
db, c - a tuple. The first element is a connection to the database.
The second element is a cursor for the database.
"""
# Your code here
# Connect to databse
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
return c, db
def execute_query(query):
"""execute_query takes an SQL query as a parameter.
Executes the query and returns the results as a list of tuples.
args:
query - an SQL query statement to be executed.
returns:
A list of tuples containing the results of the query.
"""
# Your code here
c, db = db_connect()
c.execute(query)
result = c.fetchall()
return result
db.commit()
db.close()
def print_top_articles():
"""Prints out the top 3 articles of all time."""
query = """
SELECT title, views
FROM articles
INNER JOIN
(SELECT path, count(path) AS views
FROM log
GROUP BY log.path) AS log
ON log.path = '/article/' || articles.slug
ORDER BY views DESC
LIMIT 3;
"""
results = execute_query(query)
# add code to print results
print("What are the most popular three articles of all time?")
for title, views in results:
print('\n\t{} - {} views'.format(title, views))
def print_top_authors():
"""Prints a list of authors ranked by article views."""
query = """
SELECT authors.name, COUNT(*) AS num
FROM authors, articles, log
WHERE log.path = '/article/' || articles.slug
AND authors.id = articles.author
GROUP BY authors.name
ORDER BY num DESC;
"""
results = execute_query(query)
# add code to print results
print("\nWho are the most popular article authors of all time?")
for title, views in results:
print('\n\t{} - {} views'.format(title, views))
def print_errors_over_one():
"""Prints out the days where more than 1% of logged
access requests were errors."""
query = """
SELECT date, percentage
FROM rate
WHERE rate.percentage > 1
GROUP BY date, percentage
ORDER by date;
"""
results = execute_query(query)
# add code to print results
print("\nOn which days did more than 1% of requests lead to errors")
for date, error_percent in results:
print(
'\n\t{0:%B %d, %Y} - {1:.1f}% errors'.format(date, error_percent))
if __name__ == '__main__':
print_top_articles()
print_top_authors()
print_errors_over_one()
|
fe74aba99649b2cd6ed6f409b9b6db880844866e | CiaranGruber/CP1404practicals | /prac_03/gopher_population_simulator.py | 918 | 3.9375 | 4 | """
A simulator that simulates a gopher population in a library
11/08/18 - Created by Ciaran Gruber
"""
import random
REPEATS = 9
STARTING_POPULATION = 1000
MIN_INCREASE = 10
MAX_INCREASE = 20
MIN_DECREASE = 5
MAX_DECREASE = 25
def main():
population = STARTING_POPULATION
year = 1
print('Welcome to the Gopher Population Simulator')
print('Starting population {}'.format(STARTING_POPULATION))
print('Year {}'.format(year))
for x in range(REPEATS):
increase = round(population * (random.uniform(MIN_INCREASE / 100, MAX_INCREASE / 100)))
decrease = round(population * (random.uniform(MIN_DECREASE / 100, MAX_DECREASE / 100)))
population += round(increase - decrease)
year += 1
print()
print('{} gophers were born. {} died'.format(increase, decrease))
print('Population: {}'.format(population))
print('Year {}'.format(year))
main()
|
91edf62554f1736a4c982c0e11d1c4694e62be9c | candyer/exercises | /pixel.py | 4,757 | 4.71875 | 5 | from PIL import Image
def make_shape(func, width=300, height=100):
'''
take a function and use it to draw a shape :D
the function will receive the arguments:
- pixels: a 2d list
- width: the width of the image
- height: the eight of the image
- black_pixel: a black pixel that can be put inside "pixels"
'''
img = Image.new('RGB', (width, height), "white") # create a new black image
pixels = img.load() # create the pixel map
black_pixel = (0, 0, 0)
func(pixels, width, height, black_pixel)
img.show()
def example_random_pixels(pixels, width, height, black_pixel):
''' example drawing function that put 2000 points at random '''
from random import randint
for i in range(2000):
pixels[randint(0, width - 1), randint(0, height - 1)] = black_pixel
# we run it with example_random_pixels
make_shape(example_random_pixels)
#1 make it run with an horizontal line
def horizontal_line(pixels, width, height, black_pixel):
"""
this function will show you a horizontal line
"""
for w in range(0, width):
pixels[w, height / 2] = black_pixel # "height / 2" -> keep the line in the middle
make_shape(horizontal_line)
#2 make it run with a vertical line
def vertical_line(pixels, width, height, black_pixel):
"""
this function will show you a vertical line
"""
for h in range(0, height):
pixels[width / 2, h] = black_pixel # "width / 2" -> keep the line in the middle
make_shape(vertical_line)
#3 make it run with a cross
def cross(pixels, width, height, black_pixel):
"""
this function will show you a cross
it only works if the image is a square
"""
w = 0
h = 0
while w < width and h < height:
pixels[w, h] = black_pixel
w = w + 1
h = h + 1
w = 0
h = height
while w < width and h >= 0:
pixels[w, h-1] = black_pixel
w = w + 1
h = h - 1
make_shape(cross, width=300, height=300)
#4 make a UK flag
def uk_flag(pixels, width, height, black_pixel):
horizontal_line(pixels, width, height, black_pixel)
vertical_line(pixels, width, height, black_pixel)
cross(pixels, width, height, black_pixel)
make_shape(uk_flag, width=300, height=300)
#5 make it run with stripes
def stripes(pixels, width, height, black_pixel):
""" this function will show you stripes """
for h in range(0, height, 10): # "10" -> the distance between the stripes
for w in range(0, width):
pixels[w, h] = black_pixel
make_shape(stripes)
#6 make fat stripes
def fat_stripes(pixels, width, height, black_pixel):
"""" this function will show you fat stripes """
stripe_size = 25
for h in range(0, height, stripe_size):
for i in range(h, h + stripe_size / 2 + 1):
if i < height:
for w in range(0, width):
pixels[w, i] = black_pixel
make_shape(fat_stripes)
#7 make it run with a chess board
def chess_board(pixels, width, height, black_pixel, white_pixel=(255,255,255)):
""" this funtion will show you a chess board """
horizontal_stripe_size = 35
for h in range(0, height, horizontal_stripe_size):
for i in range(h, h + horizontal_stripe_size / 2 + 1):
if i < height:
for w in range(0, width):
pixels[w, i] = black_pixel
vertical_stripe_size = 35
for w in range(0, width, vertical_stripe_size):
for j in range(w, w + vertical_stripe_size / 2 + 1):
if j < width:
for h in range(0, height):
pixels[j, h] = black_pixel
for n in range(0, height, horizontal_stripe_size):
for m in range(n, n + horizontal_stripe_size / 2 + 1):
if m < height:
pixels[j, m] = white_pixel
make_shape(chess_board)
#7-1 better solution
def example_chess(pixels, width, height, black_pixel):
thick_w = width / 8.0
thick_h = height / 8.0
for w in range(width):
for h in range(height):
if (w // thick_w) % 2 == (h // thick_h) % 2:
pixels[w, h] = black_pixel
make_shape(example_chess)
#8 make it run with a black circle:)
def black_circle(pixels, width, height, black_pixel):
""" this function will show you a circle """
import math
if height < width:
radius = height / 2
else:
radius = width / 2
# or radius = min(width, height) / 2
for h in range(height):
for w in range(width):
distance = math.sqrt((w - width / 2)**2 + (h - height / 2)**2)
if distance <= radius:
pixels[w , h] = black_pixel
make_shape(black_circle)
#9 make it run with an empty circle:)
def empty_circle(pixels, width, height, black_pixel):
""" this function will show you a circle """
import math
if height < width:
radius = height / 2
else:
radius = width / 2
# or radius = min(width, height) / 2
for h in range(height):
for w in range(width):
distance = math.sqrt((w - width / 2)**2 + (h - height / 2)**2)
if abs(distance - radius) <= 1:
pixels[w , h] = black_pixel
make_shape(empty_circle) |
5e3f6830ca212425f909c9c837a97e2f81bd3a53 | adam-weiler/GA-Reinforcing-Exercises-Programming-Fundamentals-Project | /exercise.py | 882 | 4.125 | 4 | from project import project
# print(project) # The entire dictionary
# print(project.keys()) # dict_keys(['committee', 'title', 'due_date', 'id', 'steps'])
# print(project['committee']) # ['Stella', 'Salma', 'Kai']
# print(project['title']) # "Very Important Project"
# print(project['due_date']) # "December 14, 2019"
# print(project['id']) # 3284
print(f"The original project: {project['steps']}\n") # A list of 9 steps
# print(len(project['steps'])) # 9
number_of_people = len(project['committee']) # 3
# number_of_tasks = len(project['steps']) # 9
for index, step in enumerate(project['steps']): # For each step in steps.
# print(value)
# print(index % 3)
project['steps'][index]['person'] = project['committee'][index % number_of_people] # The current project is assigned to one of 3 committee members.
print(f"The new project: {project['steps']}")
|
73a38a437db32df09b4b97593012410960f41a68 | Gttz/Python-03-Curso-em-Video | /Curso de Python 3 - Guanabara/Mundo 03 - Estruturas Compostas/Aula 17 - Listas (Parte 1)/080 - Lista_ordenada_BubbleSort.py | 588 | 4.25 | 4 | # Exercício Python 080: Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma
# lista, já na posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela.
lista = list()
for i in range(1, 6):
lista.append(int(input(f"Digite o valor para a {i}º posição:")))
for i in range(0, len(lista)):
for j in range(i + 1, len(lista)):
if lista[i] > lista[j]:
temp = lista[j]
lista[j] = lista[i]
lista[i] = temp
print(f"A lista ordenada é: {lista}")
|
09d19a8da7f2af72d3b7129a0155cde9780c6041 | nanihari/python_lst-tple | /clone_tuple.py | 203 | 3.953125 | 4 | ##program to create the clone of a tuple.
from copy import deepcopy
tuple_1=("hari", 123, [], False)
tuplex_clone=deepcopy(tuple_1)
tuplex_clone[2].append(56)
print(tuplex_clone)
print(tuple_1)
|
b184c919d0d4dc2ea2fef0a8a1965624511760dc | darthsteedious/adventofcode | /2018/day_2/__init__.py | 474 | 3.5625 | 4 | def run():
freqs = set()
with open('./input', 'r') as fp:
current = 0
while True:
line = fp.readline()
if line == '':
fp.seek(0)
continue
value = int(line, 10)
current = current + value
if current in freqs:
return current
else:
freqs.add(current)
if __name__ == '__main__':
result = run()
print(result)
|
eeb0111a5ca104370396802a48b1df9a100321ff | michelledeng30/meso | /astar.py | 6,001 | 3.796875 | 4 | from cmu_112_graphics import *
import basic_graphics, time, random
import objects, frames, message, play
from dataclasses import make_dataclass
# astar runs the search algorithm for the humans by taking in a start and end position
# and generating a path. it also sets up the grid with the obstacles
# CITATION: for lines 13-24 and 76-171 the a* algorithm was adapted from
# https://medium.com/@nicholas.w.swift/easy-a-star-pathfinding-7e6689c7f7b2
class Node():
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
class AStar(object):
def distance(x0, y0, x1, y1):
return ((x1-x0)**2 + (y1-y0)**2) ** 0.5
def obstacles(self):
# establish lake as obstacle
lakeX, lakeY = objects.Lake.lake
lakeRow, lakeCol = play.Play.getCell(self, lakeX, lakeY)
lakeCellRX = int(self.lakeRX / self.cellSize)
lakeCellRY = int(self.lakeRY / self.cellSize)
for row in range(lakeRow - lakeCellRY, lakeRow + lakeCellRY):
for col in range(lakeCol - lakeCellRX, lakeCol + lakeCellRX):
self.grid[row][col] = 1
# establish mountain as obstacle
for x, y in objects.Mountain.mountains:
(midRow, midCol) = play.Play.getCell(self, x, y)
# first section
for row in range(midRow-13, midRow-6):
for col in range(midCol-4, midCol+4):
self.grid[row][col] = 1
# second section
for row in range(midRow-6, midRow):
for col in range(midCol-7, midCol+7):
self.grid[row][col] = 1
# third section
for row in range(midRow, midRow+6):
for col in range(midCol-10, midCol+10):
self.grid[row][col] = 1
# fourth section
for row in range(midRow+6, midRow+12):
for col in range(midCol-15, midCol+16):
if (row < self.rows) and (col < self.cols):
self.grid[row][col] = 1
# fifth section
for row in range(midRow+12, midRow+15):
for col in range(midCol-17, midCol+18):
if (row < self.rows) and (col < self.cols):
self.grid[row][col] = 1
return self.grid
def findPath(self, grid, start, end):
# create start and end node
startNode = Node(None, start)
startNode.g = startNode.h = startNode.f = 0
endNode = Node(None, end)
endNode.g = endNode.h = endNode.f = 0
# create the target list and the visited list
newList = []
visitedList = []
# add start node to target list
newList.append(startNode)
# loop until a path is found
while len(newList) > 0:
# Get the current node
currentNode = newList[0]
currentIndex = 0
for index, item in enumerate(newList):
if item.f < currentNode.f:
currentNode = item
currentIndex = index
# we don't want this node, pop off new list, add to visited list
newList.pop(currentIndex)
visitedList.append(currentNode)
# found the end and path
if currentNode == endNode:
path = []
current = currentNode
while current is not None:
path.append(current.position)
current = current.parent
return path[::-1] # return reversed path
# generate children -> possible directions
children = []
dirs = [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]
for newPosition in dirs:
# get node position
nodePosition = (currentNode.position[0] + newPosition[0],
currentNode.position[1] + newPosition[1])
# make sure node is on the board
if ((nodePosition[0] > (self.rows - 1)) or
(nodePosition[0] < 0) or
(nodePosition[1] > (self.cols - 1)) or
(nodePosition[1] < 0)):
continue
# make sure the cell is valid (0, not 1)
if grid[nodePosition[0]][nodePosition[1]] != 0:
continue
# create new node
newNode = Node(currentNode, nodePosition)
# add to children list
children.append(newNode)
# loop through children
for child in children:
# CITATION: lines 148-154 and 162-168 for checking if we have already tried the child from
# https://gist.github.com/MageWang/48a2626c8280a6b59c89cc4bff6b0e37
check1 = False
for visitedChild in visitedList:
if child == visitedChild:
check1 = True
continue
if check1:
continue
# Create the f, g, and h values
child.g = currentNode.g + 1
child.h = ((child.position[0] - endNode.position[0]) ** 2) + ((child.position[1] - endNode.position[1]) ** 2)
child.f = child.g + child.h
# child is already in the new list
check2 = False
for newNode in newList:
if child == newNode and child.g > newNode.g:
check2 = True
continue
if check2:
continue
# child is valid, add the child to the new list
newList.append(child)
|
0f5a2e36e626c2d8dab9158a93a12538ede1f642 | kamil-fijalski/python-reborn | /8 - Zgaduj-Zgadula.py | 908 | 4.03125 | 4 | import random
continues = 'T'
print('Play a game... Guess my secret number.')
while continues == 'T' or continues == 't' or continues == 'Y' or continues == 'y':
secretNum = random.randint(0, 10)
print('How do you think... What number did I choose?')
try:
ans = int(input())
except ValueError:
print('Unappropriated value!')
break
while int(ans) != secretNum:
if int(ans) > secretNum:
print('So close! Your number is too high!')
else:
print('So close! Your number is too low!')
print('Try again!')
try:
ans = int(input())
except ValueError:
print('Unappropriated value')
break
if int(ans) == secretNum:
print('Congratulations! Secret number was: ' + str(secretNum) + '.')
print('Would you like play once again? [T/N]')
continues = input()
|
879c952b4df7ea3799445ae4a02ddc29dae61564 | harry-martins/greater | /greater.py | 101 | 3.71875 | 4 | x,y,z=map(int,input().split())
if x>y and x>z:
print(x)
elif y>x and y>z:
print(y)
else:
print(z)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.