blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9591f0da88d535004da3f46a2eaf7c46c7c9574d | fletchto99/CSI4133 | /labs/lab 4/lab4a.py | 716 | 3.53125 | 4 | # Matthew Langlois
# Student # 7731813
#!/usr/local/bin/python3
import numpy as np
import cv2
img = cv2.imread('./images/hand.png')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# We don't need to do anything on change
def change(value):
#read the image as grayscale
threshold = cv2.inRange(hsv, np.array([value,180,0]), np.array([value+10,255,255]))
res = cv2.bitwise_and(img,img, mask=threshold)
# Show and return the image
cv2.imshow('Part A', res)
print(value)
cv2.namedWindow('Part A - HSV')
cv2.imshow('Part A - HSV', hsv)
cv2.namedWindow('Part A')
cv2.imshow('Part A', img)
cv2.createTrackbar('Threshold', 'Part A', 0, 180, change);
# Press any key to refresh the windows
cv2.waitKey(0)
|
832eadede1e668bf593246b2a5364b2037c933b2 | regnart-tech-club/programming-concepts | /course-2:combining-building-blocks/subject-2:functions/topic-5:Higher-Order Functions/lesson-6.0:product puzzle.py | 459 | 4.125 | 4 | # Write a function or lambda using the implementation of fold below that will
# return the product of the elements of a list.
def or_else(lhs, rhs):
if lhs != None:
return lhs
else:
return rhs
def fold(function, arguments, initializer, accumulator = None):
if len(arguments) == 0:
return accumulator
else:
return fold(
function,
arguments[1:],
initializer,
function(
or_else(accumulator, initializer),
arguments[0]))
|
48d4d93c7c17b66a095f81ff9c9c825a7b7742d4 | hearecho/pycommon | /MapStudy.py | 931 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/28 18:58
# @Author : hearecho
# @Site :
# @File : MapStudy.py
# @Software: PyCharm
'''
Map会将⼀个函数映射到⼀个输⼊列表的所有元素上
list元素可以是一组函数
map(func,list) type--><class 'map'>
'''
class MapStudy():
def __map(self):
items = [1,2,3,4,5,6,7]
print(type(map(lambda x:x**2,items)))
sq = list(map(lambda x:x**2,items))
print(sq)
def __multiply(self,x):
return x*x
def __add(self,x):
return x+x
# list 为一组函数
def __maptest2(self):
funcs =[self.__multiply,self.__add]
for i in range(5):
value = list(map(lambda x:x(i),funcs))
print(value)
def test(self):
# self.__map()
self.__maptest2()
pass
if __name__ == '__main__':
map1 = MapStudy()
map1.test() |
c4b9bcc397c9f56a3a5f04f0941b7cf4b797a8ac | matiasconde/Courses | /37_Building a data pipeline/Multiple Dependency Pipeline-266.py | 5,005 | 3.609375 | 4 | ## 2. Intro to DAGs ##
cycle = [4,6,7]
## 3. The DAG Class ##
class DAG:
def __init__(self):
self.graph = {}
def add(self, node, to=None):
if node not in self.graph:
if to:
self.graph[node] = [to]
if to not in self.graph:
self.graph[to] = []
else:
self.graph[node] = []
else:
if to:
self.graph[node].append(to)
if to not in self.graph:
self.graph[to] = []
dag = DAG()
dag.add(1)
dag.add(1, 2)
dag.add(1, 3)
dag.add(1, 4)
dag.add(3, 5)
dag.add(2, 6)
dag.add(4, 7)
dag.add(5, 7)
dag.add(6, 7)
print(dag.graph)
## 5. Finding Number of In Degrees ##
class DAG(BaseDAG):
def in_degrees(self):
pass
dag = DAG()
dag.add(1)
dag.add(1, 2)
dag.add(1, 3)
dag.add(1, 4)
dag.add(3, 5)
dag.add(2, 6)
dag.add(4, 7)
dag.add(5, 7)
dag.add(6, 7)
in_degrees = dag.in_degrees()
class DAG(BaseDAG):
def in_degrees(self):
in_degrees = {}
for node in self.graph:
if node not in in_degrees:
in_degrees[node] = 0
for pointed in self.graph[node]:
if pointed not in in_degrees:
in_degrees[pointed] = 0
in_degrees[pointed] += 1
return in_degrees
dag = DAG()
dag.add(1)
dag.add(1, 2)
dag.add(1, 3)
dag.add(1, 4)
dag.add(3, 5)
dag.add(2, 6)
dag.add(4, 7)
dag.add(5, 7)
dag.add(6, 7)
in_degrees = dag.in_degrees()
## 6. Challenge: Sorting Dependencies ##
from collections import deque
class DAG(BaseDAG):
def sort(self):
in_degrees = self.in_degrees()
searched = []
to_visit = deque()
for node in in_degrees:
if in_degrees[node] == 0:
to_visit.append(node)
while to_visit:
node = to_visit.popleft()
for pointed in self.graph[node]:
in_degrees[pointed] -= 1
if in_degrees[pointed] == 0:
to_visit.append(pointed)
searched.append(node)
return searched
dag = DAG()
dag.add(1)
dag.add(1, 2)
dag.add(1, 3)
dag.add(1, 4)
dag.add(3, 5)
dag.add(2, 6)
dag.add(4, 7)
dag.add(5, 7)
dag.add(4,5)
dag.add(6, 7)
dependencies = dag.sort()
print(dependencies)
## 7. Enhance the Add Method ##
class DAG(BaseDAG):
def add(self, node, to=None):
if not node in self.graph:
self.graph[node] = []
if to:
if not to in self.graph:
self.graph[to] = []
self.graph[node].append(to)
if len(self.sort()) != len(self.graph):
raise Exception("new cycle created")
dag = DAG()
dag.add(1)
dag.add(1, 2)
dag.add(1, 3)
dag.add(1, 4)
dag.add(3, 5)
dag.add(2, 6)
dag.add(4, 7)
dag.add(5, 7)
dag.add(6, 7)
#Add a pointer from 7 to 4, causing a cycle.
dag.add(7, 4)
## 8. Adding DAG to the Pipeline ##
class Pipeline:
def __init__(self):
self.tasks = DAG()
def task(self, depends_on=None):
def inner(f):
pass
return inner
pipeline = Pipeline()
def first():
return 20
def second(x):
return x * 2
def third(x):
return x // 3
def fourth(x):
return x // 4
class Pipeline:
def __init__(self):
self.tasks = DAG()
def task(self, depends_on=None):
def inner(f):
self.tasks.add(f)
if depends_on:
self.tasks.add(depends_on, f)
return f
return inner
pipeline = Pipeline()
@pipeline.task()
def first():
return 20
@pipeline.task(depends_on=first)
def second(x):
return x * 2
@pipeline.task(depends_on=second)
def third(x):
return x // 3
@pipeline.task(depends_on=second)
def fourth(x):
return x // 4
print(pipeline.tasks.graph)
## 9. Challenge: Running the Pipeline ##
class Pipeline:
def __init__(self):
self.tasks = DAG()
def task(self, depends_on=None):
def inner(f):
self.tasks.add(f)
if depends_on:
self.tasks.add(depends_on, f)
return f
return inner
def run(self):
completed = {}
sorted_tasks = self.tasks.sort()
for task in sorted_tasks:
for node in self.tasks.graph:
if task in self.tasks.graph[node]:
input_ = completed[node]
output = task(input_)
completed[task] = output
if task not in completed:
completed[task] = task()
return completed
pipeline = Pipeline()
@pipeline.task()
def first():
return 20
@pipeline.task(depends_on=first)
def second(x):
return x * 2
@pipeline.task(depends_on=second)
def third(x):
return x // 3
@pipeline.task(depends_on=second)
def fourth(x):
return x // 4
outputs = pipeline.run() |
0555d22fb21face14e7190ad098672e415e35507 | alephist/edabit-coding-challenges | /python/sum_of_vowels.py | 436 | 3.875 | 4 | """
Sum of v0w3ls
Create a function that takes a string and returns the sum of vowels, where some vowels are considered numbers.
Vowel Number
A 4
E 3
I 1
O 0
U 0
https://edabit.com/challenge/6NoaFGKJgRW6oXhLC
"""
def sum_of_vowels(sentence: str) -> int:
vowel_dict = {
'a': 4,
'e': 3,
'i': 1,
'o': 0,
'u': 0
}
return sum(vowel_dict.get(letter, 0) for letter in sentence.lower())
|
3dfe7bc5cfdd6ff9178ea70b73b0242f484a855d | paladino3/AulasPythnoPOO | /DevMediaPythonCompleto65Horas/Aula49.03.py | 210 | 3.828125 | 4 | import re
inputEmail = input(str("Digite seu email: "))
myDomain = re.search("@[\w.]+", inputEmail)
if myDomain:
print("Seu email dominio é: ",myDomain.group())
else:
print("Email whitout domain") |
9575fc41deb68face924541421bcb2ef4859eaf9 | mandarmakhi/DataScience-R-code | /1. Practice/basic statistics1/Datatypes.py | 6,129 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 26 07:44:04 2019
@author: Mukesh
"""
#######Strings###############
#syntax for string is " string or text " or ' text '
#Accesing Value in Strings or slicing the values
Name = "excelr" #positive and negative formats
# e x c e l r
# 0 1 2 3 4 5
# -5 -4 -3 -2 -1
Name
print(Name)
print(Name[-6])
Name[3]
print(Name[1:4]) #1,2,3
print(Name[2:-5]) # do npot use
print(Name[-1])
print(Name[-3:-1]) #-3,-2
# Name[-3:]
#Update Strings
var1 = "Hello World!"
out = var1 + ' Python'
print ("Updated ", var1 + ' Python')
# String Formating
#%s - String (or any object with a string representation, like numbers)
#%d - Integers
#%f - Floating point numbers
# %. <number of frations we want>f
#%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
print("My name is %s and weight is %.3f kgs! my father name is %s " % ('Anil', 70,'Ramu'))
number = 10 #hardcoding
number = input("enter num: ")
number_1 = eval(input("enter number: "))
#Ex :1
Name = input("Enter your name: ") # string - just input
Weight = eval(input("Enter your Weight: ")) # int or float
(Name,Weight)
#Triple Quotes
# my name is 'nikhil' and my age is '25'
Statement = """my name is "nikhil" and my age is "25" new"""
Name = "excelr excelr"
Name.lower() #upper case
Name.center(50)
Name.count("excelr") # to count
#count() method returns the number of occurrences of the substring in the given string.
string = "excelr is an training institute"
substring = "n"
string.count(substring)
count = string.count(substring) # assignment operators
# print count
("The count is:", count)
##Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
Num = "f1234"; # No space in this string
print(Num.isalnum())
Num = "this is string example"
Num.isalnum() # or .isdigit()
#This method returns true if all characters in the string are alphabetic and there is at least one character, false otherwise.
Num = "this"; # No space & digit in this string
Num.isalpha()
Num = "this is string example0909090!!!";
Num.isalpha()
#This method returns true if all characters in the string are digits and there is at least one character, false otherwise.
Num = "123456"; # Only digit in this string
Num.isdigit()
Num = "this is string example!!!"
Num.isdigit()
#his method returns a copy of the string in which all case-based characters have been lowercased.
Num = "THIS IS STRING EXAMPLE!!!";
Num.lower()
#his method returns a copy of the string in which all case-based characters have been Uppercase.
Num = "this is string example!!!";
alpha = Num.upper()
#The following example shows the usage of replace() method.
reply = "it is string example!!! is really a string"
print(reply.replace("is", "was")) #.replace # DF or list or string
reply.replace("is", "was", 1)
#The following example shows the usage of split() method.
split1 = "Line1-abcdef,nLine2-abc,nLine4-abcd"
split1.split(",")
############################### List ################################
#collection of elements or items
list1 = ['Nikhil', 'Excelr', 2013, 2018]
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
list_n = [list1,list2,list3]
python_class = ["Nikhil", "Aditya", "Divya"]
list1 = ['Nikhil', 'Excelr', 2013, 2018];
list1[0]
list2 = [1, 2, 3, 4, 5, 6, 7 ];
list2[1:5]
saranya199991@gmail.com
smita.gavandi@gmail.com
list1 = ['Nikhil', 'Excelr', 2013, 2018];
print(list1[2])
list1[2] = 8055; #updating the list
print(list1)
list1[0] = "Divya";
list1 = ['Nikhil', 'Excelr', 2013, 2018];
list1
del(list1[2]) #deleting any item/element by using index number
del(list1)
print(list1)
# Append
aList = [123, 'xyz', 'zara', 'abc']
aList.append( 2009 ); # adding from last
print(aList)
#Pop
print (aList.pop()) # removing items from the last
print (aList.pop(2))
#Insert
aList.insert( 1, 2008)
print (aList)
aList.insert(2,"excelr")
#Extend
aList = [123, 'xyz', 'tommy', 'abc', 123];
bList = [2009, 'beneli'];
aList.extend(bList) # adding two list
print(aList)
#Reverse
aList.reverse();
print(aList)
#Sort
blist = [8,99,45,33]
blist.sort();
print(blist)
#count
aList = [123, 'xyz', 'zara', 'abc', 123, "zara"];
print(aList.count("zara"))
##################################### Tuples ####################################
## Create a tuple dataset
tup1 = ('Street triple','Detona','Beneli', 8055);
tup2 = (1, 2, 3, 4, 5 );
tup3 = ("a", "b", "c", "d");
### Create a empty tuple
tup1 = ()
#Create a single tuple
tup1 = (50,)
#Accessing Values in Tuples
tup1 = ('Street triple','Detona','Beneli', 8055);
print(tup1[0]);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print(tup2[1:5]);
#Updating Tuples
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# So,create a new tuple as follows
tup1 = tup1 + tup2;
print(tup1);
#Delete Tuple Elements
tup = ('Street triple','Detona','Beneli', 8055)
print (tup)
del(tup)
print ("After deleting tup : ")
print(tup)
#Basic Tuples Operations
#To know length of the tuple
tup = (1,2,3,'Nikhil','Python')
len(tup)
#To add two elements
tup2 =(4,5,6)
tup3 = tup+tup2
tup3 = ('Hi!',)
tup3*3
# Membership operator
3 in (1, 2, 3)
# Max and min in tuple
tuple1 = (456, 700, 200)
print(max(tuple1))
print(min(tuple1))
############################## Dictionary #################################
# Used Unordered colloection of items
#Accessing Values in Dictionary #keys:values
dict1 = {'Name': 'Nikhil', 'Age': 25, 'bike': 'Beneli'}
print(dict1)
dict1['Name']
print(dict1['Age'])
print(dict1['bike'])
##Updating Dictionary
dict1 = {'Name': 'Nikhil', 'Age': 25, 'bike': 'Beneli'}
dict1['Age'] = 8; # update existing entry
dict1['School'] = "DPS School"; # Add new entry
dict1['Sal'] = 50000;
print(dict1['Age'])
print(dict1['School'])
#Delete Dictionary Elements
dict1 = {'Name': 'Nikhil', 'Age': 25, 'bike': 'Beneli'}
del(dict1['Name']); # remove entry with key 'Name'
dict1.clear(); # remove all entries in dict
del(dict1) ; # delete entire dictionary
print(dict1['Age'])
print(dict1['School']) |
799a959779f1d4accab8e71de00a132f57a487bb | calanoue/GFIN_Data_Work | /get_numpy_dtype.py | 3,067 | 3.546875 | 4 | """
Functions to help with data formatting and analysis.
"""
from re import search
def format_creates(sql_statements):
"""
Format DDL Create Statements
"""
create_strs = []
for i in sql_statements:
i = i.replace("]", "")
i = i.replace("[", "")
create_str = ""
for j in i.split('\r\n'):
create_str += j.strip()
create_strs.append(create_str)
return create_strs
def format_indexes(sql_statements):
"""
Format DDL index statements
"""
index_strs = []
for row in sql_statements:
tbl, index_statement = row
index_statement = index_statement.replace("[", "")
index_statement = index_statement.replace("]", "")
match = search("[(].*[)]", index_statement).group().replace("(", "").replace(")", "")
index_strs.append("CREATE INDEX %s_index ON %s (%s)"%(tbl, tbl, match))
return index_strs
def get_dtype(connection, table, nameReturn=False, remove_id=False):
"""
Get numpy data type from a database table
"""
(names, typestr) = zip(*(_[1:3] for _ in connection.execute("PRAGMA TABLE_INFO(%s)"%table).fetchall()))
# Get the data type for the specified table
ndtype = []
for n, t in zip(names, typestr):
if t =='INTEGER':
ndtype.append((n, float))
elif t[:4]=='TEXT':
ndtype.append((n, object)) # to handle large string values
else:
ndtype.append((n, float))
# Remove field named id if requested
if remove_id:
names = [name.strip() for name in names if name!='id']
ndtype = ndtype[1:]
# Return names if requested
if nameReturn:
return ndtype, names
else:
return ndtype
def mask_none_values(xs):
"""
Mask None values that are actually <null> values in the database.
"""
descr_names = xs.dtype.names # column names in the masked array
for descr_name in descr_names:
mask_idx = [enum for enum, j in enumerate(xs[descr_name]) if j==None] # index of None values
xs[descr_name].mask[mask_idx] = True
return xs
def add_to_element():
"""
New elements for the Element table
"""
new_elements = {
52:"Production Quantity Per Capita", 101:"Consumption Quantity Per Capita", 102:"Consumption Elasticity",
611:"Total Population - Both Sexes Net Change", 612:"Total Population - Male Net Change",
613:"Total Population - Female Net Change", 651:"Rural population Net Change",
661:"Urban population Net Change", 671:"Agricultural population Net Change",
681:"Non-agricultural population Net Change", 691:"Total economically active population Net Change",
692:"Male economically active population Net Change",
693:"Female economically active population Net Change",
701:"Total economically active population in Agr Net Change",
702:"Male economically active population in Agr Net Change",
703:"Female economically active population in Agr"
}
return new_elements
|
56b3f4d90c4306dfb5dcf696f58cfe17eadd533d | driellevvieira/ProgISD20202 | /Dayana Vieira/Atividade 5 e 6/Aula 5/aula 5.py | 794 | 3.8125 | 4 | lista = []
print(lista)
lista = ["Ó carro", "peixe", 123, 111]
print (lista)
lista = ["Ó carro", "peixe", 123, 111]
nova_lista = ["pedra", lista]
print (nova_lista)
lista = ["O carro", "peixe", 123, 111]
nova_lista = ["pedra", lista
print (lista [0])
print (lista [2])
print (nova_lista [1])
print (nova_lista [1][2])
lista = ["O carro", "peixe", 123, 111]
print(lista [-1])
print (lista [-2])
print{lista [-3]
print (lista [-4])
lista=["O carro" "peixe", 123, 111]
nova_lista = ["pedra", lista]
print (lista+nova_lista)
print (lista*3)
lista = ["O carro" "peixe", 123, 111]
print ("peixe" in lista)
numeros = [14,55,67,89,88,10,21,5]
print (min(numeros))
print (max (numeros))
print (sum(numero)
livros = ["Java", "Sqlserver", "Delphi", "Pyton"]
livros.append("android")
print(livros)
|
0c607f6a8b20a1287a300d08b2a9ca4163cdcbe4 | Frensis7153/python | /1_6.py | 204 | 3.5625 | 4 | a = int(input("a = "))
b = int(input("b = "))
i = 1
while a < b:
i += 1
a += a / 10
print(f"На {i}-й день спортсмен достиг результата - не менее {b} км")
|
6506268d9c4e92f0c9fa9c4ca01806fdfab96b8e | pratikshas8080/PYTHON_Daily_Code_2021 | /functions.py | 195 | 3.6875 | 4 | #functions
def greet():
print("Gm Sir")
greet()
#function2
a=int(input("Enter First Number"))
b=int(input("Enter Second Number"))
def sum(a, b):
c=a+b
return c
d=sum(a,b)
print(d)
|
4e7a35cd157b7a83c0f1617d1acd77f844bdc045 | KuptsovYa/Face-Detecter | /camera.py | 885 | 3.546875 | 4 | """Камера без создания отдельного процесса."""
import cv2
import numpy as np
class CameraError(IOError):
pass
class Camera:
filter = lambda x: x
def __init__(self, cam_num=0, cam_wh=(320, 240)):
self.cam_num = cam_num
self.cam_wh = cam_wh
self.cam = cv2.VideoCapture(self.cam_num)
if not self.cam.isOpened():
raise CameraError("Problem 1 with camera {}".format(self.cam_num))
self.cam.set(cv2.CAP_PROP_FRAME_WIDTH, self.cam_wh[0])
self.cam.set(cv2.CAP_PROP_FRAME_HEIGHT, self.cam_wh[1])
def __del__(self):
self.cam.release()
def get_frame(self):
ret, img = self.cam.read()
if not ret:
raise CameraError("Problem 2 with camera {}".format(self.cam_num))
#img = np.hstack([img, __class__.filter(img)])
return img
|
7e05341635851a93944090bd1fdba22d5fe9dac6 | wai030/Python-project | /3Missionaries 3Cannibal.py | 4,957 | 3.84375 | 4 | import copy
#Missionaries and Cannibals (Missionaries and Cannibals)
#######################
## Data Structures ####
#######################
# The following is how the state is represented during a search.
# A dictionary format is chosen for the convenience and quick access
LEFT=0; RIGHT=1; BOAT_POSITION=2
Missionaries=0;Cannibal=1
#[[num_Missionaries_left, num_Cannibal_left], [num_Missionaries_right, num_Cannibal_right], boat_position (0=left, 1=right)]
initial_state = [[0,0],[3,3], RIGHT]
goal_state = [[3,3],[0,0], LEFT]
###################################################
## Functions related to the game
###################################################
# Verifies if the state is safe.
def is_safe(state):
return (not (0 < state[LEFT][Missionaries] < state[LEFT][Cannibal] or
0 < state[RIGHT][Missionaries] < state[RIGHT][Cannibal] )
)
def opposite_side(side):
if side == LEFT:
return RIGHT
else:
return LEFT
##############################################
## Functions for recording the path #########
##############################################
#
# A path is the states from the root to a certain goal node
# It is represented as a List of states from the root
# The create_path function create a new path by add one more node to an old path
#
def create_path(old_path, state):
new_path = old_path.copy()
new_path.append(state)
return new_path
##########################
## Functions for Searching
##########################
def move(state, Missionariess, Cannibals):
side = state[BOAT_POSITION]
opposite = opposite_side(side)
if state[side][Missionaries] >= Missionariess and state[side][Cannibal] >=Cannibals:
new_state= copy.deepcopy(state)
new_state[side][Missionaries]-= Missionariess
new_state[opposite][Missionaries] += Missionariess
new_state[side][Cannibal] -= Cannibals
new_state[opposite][Cannibal] += Cannibals
new_state[BOAT_POSITION] = opposite
return new_state
# Find out the possible moves, and return them as a list
def find_children(old_state):
children = []
side = old_state[BOAT_POSITION]
# Try to move one Missionary
if old_state[side][Missionaries] > 0:
new_state= move(old_state, Missionariess=1, Cannibals=0)
if is_safe(new_state):
children.append(new_state)
# Try to move one Cannibal
if old_state[side][Cannibal] > 0:
new_state= move(old_state, Missionariess=0, Cannibals=1)
if is_safe(new_state):
children.append(new_state)
# Try to move one Missionaries and one Cannibal
if old_state[side][Cannibal] > 0 and old_state[side][Missionaries] > 0:
new_state= move(old_state, Missionariess=1, Cannibals=1)
if is_safe(new_state):
children.append(new_state)
# Try to move two Missionariess
if old_state[side][Missionaries] > 1:
new_state= move(old_state, Missionariess=2, Cannibals=0)
if is_safe(new_state):
children.append(new_state)
# Try to move two Cannibals
if old_state[side][Cannibal] > 1:
new_state= move(old_state, Missionariess=0, Cannibals=2)
if is_safe(new_state):
children.append(new_state)
return children
# ---------------------------
# Search routine ####
# ---------------------------
def bfs_search(start_state):
visited = []
to_visit = []
path = create_path([], start_state)
next_node =[start_state, path]
end = False
while not end:
next_state, path = next_node
if not next_state in visited:
visited.append(next_state)
if next_state == goal_state:
return path
else:
for child_state in find_children(next_state):
child_path = create_path(path, child_state)
to_visit.append([child_state, child_path])
if to_visit:
next_node=to_visit.pop(0)
else:
print("Failed to find a goal state")
end=True
return ()
################
## Main ######
################
# Search for a solution
path = bfs_search(initial_state)
if path:
print ("Path from start to goal:")
for p in path:
left,right,side = p
t_left, b_left=left
t_right, b_right=right
if side==LEFT:
boat_l = "#BOAT#";boat_r = " "
else:
boat_l = " ";boat_r = "#BOAT#"
print(" Missionaries {} Cannibal {} {} |~~~~~| {} Missionaries {} Cannibal {}" .format(t_left, b_left, boat_l, boat_r, t_right, b_right))
input()
|
f7783b2f9f5bb16757983369a7018c423f1cb9e1 | naru380/AtCoder | /ABC/149/C/source.py | 794 | 3.515625 | 4 | import math
# エラストテネスの篩
def eratosthenes(limit):
A = [i for i in range(2, limit+1)]
P = []
time = 0
while True:
prime = min(A)
if prime > math.sqrt(limit):
break
P.append(prime)
i = 0
while i < len(A):
if A[i] % prime == 0:
A.pop(i)
continue
i += 1
for a in A:
P.append(a)
return P
def main():
X = int(input())
# ルジャンドル予想(未証明だが、、)
# -> n^2 と (n+1)^2 の間に必ず素数が存在する
# 10^(5/2) = 316.2277...
# 317^2 = 100489
P = eratosthenes(10**5+489)
i = 0
while True:
if P[i] >= X:
break
i += 1
print(P[i])
if __name__ == '__main__':
main()
|
b155eebedbd982a904ceecc83921369107909199 | ericmuzz/itc110 | /ITC110/pumpkincanon.py | 846 | 4.125 | 4 | import math
def main():
angle = float(input("Enter the launch angle(in degrees): "))
speed = float(input("Enter the initial velocity (in m/s): "))
initial_height = float(input("Enter the initial height(in m): "))
time = 0.1
#pumkin start position
pumpkin_x = 0
pumpkin_y = initial_height
#pumpkin firing velocity
theta = math.radians(angle)
x_velocity = speed * math.cos(theta)
y_velocity = speed * math.sin(theta)
while pumpkin_y >= 0:
pumpkin_x = pumpkin_x + (x_velocity * time)
new_y_velocity = y_velocity - time * 9.8 #m/s^2
pumpkin_y = pumpkin_y + time * (y_velocity + new_y_velocity) / 2.0
y_velocity = new_y_velocity
print("The pumpkin is at {0}, {1}".format(pumpkin_x, pumpkin_y))
print("The pumpkin traveled {0} meters".format(pumpkin_x))
main()
|
1ffdc7c130c40f1f1f51c83b8131fde5214e4bad | xNiallC/DQSCoursework2 | /Archive/GuiTest.py | 2,240 | 3.546875 | 4 | from Tkinter import *
import ttk
import csv
def returnSurname(*args):
with open('MOCK_DATA.csv') as csvfile:
reader = csv.reader(csvfile)
nameinput = str(name.get()).lower()
for row in reader:
if nameinput == row[0].lower():
answer1.set("--> " + row[1])
break
else:
answer1.set("--> " + "Name not found.")
def returnNumber(*args):
with open('MOCK_DATA.csv') as csvfile:
reader = csv.reader(csvfile)
nameinput = str(name.get())
if not nameinput.isdigit():
for row in reader:
if nameinput.lower() == row[0].lower():
answer2.set("--> " + row[2])
break
else:
answer2.set("--> " + "Name not found.")
else:
for row in reader:
if nameinput == row[2]:
answer2.set("--> " + row[0])
break
else:
answer2.set("--> " + "Number not found.")
root = Tk()
root.title("Get Surname")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
name = StringVar()
answer1 = StringVar()
answer2 = StringVar()
name_entry = ttk.Entry(mainframe, width=10, textvariable=name)
name_entry.grid(column=2, row=1, sticky=(W, E))
ttk.Label(mainframe, textvariable=answer1).grid(column=2, row=2)
ttk.Button(mainframe, text="Calculate Surname", command=returnSurname).grid(column=1, row=2, sticky=W)
ttk.Label(mainframe, text="Please Input Information: ").grid(column=1, row=1, sticky=W)
ttk.Label(mainframe, text="Find a Surname from a Forename.").grid(column=1, row=3, sticky=W)
ttk.Label(mainframe, textvariable=answer2).grid(column=2, row=4)
ttk.Button(mainframe, text="Calculate Number/Name", command=returnNumber).grid(column=1, row=4, sticky=W)
ttk.Label(mainframe, text="Find a Number from Forename, or vice versa.").grid(column=1, row=5, sticky=W)
for child in mainframe.winfo_children():
child.grid_configure(padx=5, pady=5)
name_entry.focus()
root.bind('<Return>', returnSurname)
root.mainloop() |
b1aee0cd2e3ecb9b562fea554810eed112b29152 | Aasthaengg/IBMdataset | /Python_codes/p03079/s358392293.py | 204 | 3.78125 | 4 | import sys
# 標準入力を読み込み,float型へ変換
s = input().split()
f = [ float(x) for x in s]
# 正三角形の条件
if (f[0]==f[1] and f[1]==f[2]):
print('Yes')
else:
print('No') |
bf854aeba6852a13cfbcb4d78f326fb5f64c86eb | NiklasMelton/research_code | /Unified SL-RL/PreGitCopies/newTrack.py | 1,955 | 3.5 | 4 | #ready! set! race!
import pygame, math
pygame.init()
size = width, height = 1000, 600
screen = pygame.display.set_mode(size)
white = 255,255,255
black = 0, 0, 0
color = 255,255,0
font = pygame.font.SysFont("Comic Sans MS", 12)
track = []
print('StartLine!')
xa = int(input('x1'))
xb = int(input('x2'))
ya = int(input('y1'))
yb = int(input('y2'))
startLine = [xa,xb,ya,yb]
prevLine = startLine
screen.fill(white)
pygame.draw.line(screen, color, (startLine[0],startLine[2]), (startLine[1], startLine[3]), 2)
pygame.display.flip()
while(1):
for event in pygame.event.get():
if event.type == pygame.QUIT: sys. exit()
print('NewLine! previousend value was:', prevLine[1],prevLine[3])
cont = input('continue side?')
if cont == 'y':
xa = prevLine[1]
xb = int(input('newX'))
ya = prevLine[3]
yb = int(input('newY'))
else:
xa = input('x1')
if xa == 'n':
break
else: xa = int(xa)
xb = int(input('x2'))
ya = int(input('y1'))
yb = int(input('y2'))
line = [xa,xb,ya,yb]
pygame.draw.line(screen, black, (line[0],line[2]), (line[1], line[3]), 2)
pygame.display.flip()
approve = input('keep? (y/n)')
if approve == 'y':
track.append(line)
prevLine = line
coord = font.render((str(line[1])+','+str(line[3])), 2, color)
screen.blit(coord, (line[1],line[3]))
else:
pygame.draw.line(screen, white, (line[0],line[2]), (line[1], line[3]), 2)
save = input('save? (y/n)')
if save == 'y':
fileName = input('file name? ')
file = open(fileName, 'w')
segmentString = str()
for p in startLine:
segmentString += str(p)
segmentString += '\n'
file.write(segmentString)
for seg in track:
segmentString = str()
for p in seg:
segmentString += str(p)
segmentString += '\n'
file.write(segmentString)
file.close()
|
2a2d71c618ff4e64910fb4a8f05b9db136701471 | IliaLiash/python_start | /lists/google_search_1.py | 268 | 4.0625 | 4 | #Displays all entered lines in which search word occurs
n = int(input())
my_list1 = []
for i in range(n):
s = input()
my_list1.append(s)
keyword = input().lower()
for element in my_list1:
if keyword in element.lower():
print(element, end='\n')
|
320d5930f8b313c71ff297ae6d354e791cdb712d | 593413198/DataStructure | /Python/queue.py | 635 | 4.125 | 4 | #!/usr/bin/python3
# @brief: 队列的python实现
# @date: 2019,5,5
# @author: luhao
class Queue(object):
def __init__(self):
self.Q = []
def isEmpty(self):
return True if self.Q==[] else False
def size(self):
return len(self.Q)
def push(self,x):
self.Q.append(x)
def first(self):
return self.Q[0]
def pop(self):
return self.Q.pop(0)
def show(self):
# 打印队列中所有元素
print (self.Q)
if __name__ == "__main__":
Q = Queue()
Q.push(1)
Q.push(2)
Q.push(3)
Q.pop()
print (Q.first())
Q.show()
|
71851fc9eaa33460e31ddafe4f06a6ed5ae0dd19 | Poornaprasad/ProtoThon01 | /text formatter.py | 408 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print("Enter the Sentence")
a=input()
n=len(a)
print("1.all caps")
print("2.small caps")
print("3.title case ")
print("4.start case")
choice=int(input("type 1/2/3/4: "));
if(choice==1):
print(a.upper())
if(choice==2):
print(a.lower())
if(choice==3):
print(a.title())
if(choice==4):
print(a[0].upper(),end='')
print(a[1::])
# In[ ]:
|
504944745a63384d263acd94e8949ef029a73b99 | anilreddy2896/hard | /Python/Advanced_python/multi_threading/multi15.py | 295 | 3.53125 | 4 | # why synchronization
from threading import *
import time
def wish(name):
for i in range(10):
print("good morning: ",end='')
time.sleep(3)
print(name)
t1=Thread(target=wish,args=('dhoni',))
t2=Thread(target=wish,args=('anil',))
t1.start()
t1.join()
t2.start()
|
6d8c1c68cd2aa67c1f996080c92314cae10aaa94 | ayanchyaziz123/AI-Assignment | /AI_LabAssign_03_DLS_181-115-086.py | 1,462 | 3.734375 | 4 | from collections import defaultdict
import sys
mx = []
def dfs(node, parent, height, vis, tree, dest):
# calculate the level of every node
# if node is not equal to parent
if node != parent:
height[node] = 1 + height[parent]
parent = node
print("Explored", node ,"at depth ", height[node] - 1)
c = height[node] - 1
mx.append(c)
# mark every node as visited
if height[node] - 1 == dest:
return
vis[node] = 1
# iterate in the subtree
for it in tree[node]:
# if the node is not visited
if not vis[it]:
# call the dfs function
dfs(it, node, height, vis, tree, dest)
if __name__ == "__main__":
sys.stdin = open("input.txt", "r")
#define dictionary as a name tree
tree = defaultdict(list)
#to get user input vertex and edges
v, e = map(int, input().split())
height = [None] * (v + 1)
vis = [None] * (v + 1)
for i in range(e):
n1, n2 = map(int, input().split())
tree[n1].append(n2)
tree[n2].append(n1)
source = int(input())
dest = int(input())
height[source] = 1
mx.append(height[source] - 1)
print("Explored", source ,"at depth ", height[source] - 1)
#call dfs function
dfs(source, source, height, vis, tree, dest)
m = max(mx)
print()
print("Maximum Depth reached: ", m)
|
665e5a725407a4c355c79d428c80e1556ba53a79 | anwarch0wdhury/SoftwareTesting | /test.py | 7,292 | 3.984375 | 4 | import unittest
from itertools import *
import numpy as np
from decimal import Decimal
from fractions import Fraction
import operator
def lzip(*args):
return list(zip(*args))
class Test_itertools(unittest.TestCase):
'''
Make an iterator that returns evenly spaced values starting with number start. Often used as an argument to map() to generate consecutive data points. Also, used with zip() to add sequence numbers.
'''
def test_count(self):
#self.assertEqual(itertools.count(0))
self.assertEqual(lzip('abc', count()), [('a', 0), ('b', 1), ('c', 2)])
self.assertEqual(lzip('abc', count(4)), [('a', 4), ('b', 5), ('c', 6)])
self.assertEqual(lzip('abc', count(4,2)), [('a', 4), ('b', 6), ('c', 8)])
self.assertEqual(lzip('abc', count(4,0)), [('a', 4), ('b', 4), ('c', 4)])
self.assertEqual(lzip('abc', count(4,-1)), [('a', 4), ('b', 3), ('c', 2)])
self.assertEqual(lzip('abc', count(1.5,0.25)), [('a', 1.5), ('b', 1.75), ('c', 2)])
self.assertEqual(lzip('abc', count(-10)), [('a', -10), ('b', -9), ('c', -8)])
self.assertEqual(lzip('abc', count(-1)), [('a', -1), ('b', 0), ('c', 1)])
self.assertEqual(list( islice( count(100), 10)), list(range(100, 100+10)))
self.assertEqual(list( islice( count(100,2), 5)), (list(islice(range(100, 200, 2),5))))
### Type Errors
self.assertRaises(TypeError, count, 2,3,4)
self.assertRaises(TypeError, count, 'a', 'b', 'c')
self.assertRaises(TypeError, count, 'a')
self.assertRaises(TypeError, count, 2, 'c')
#typeerror, overflowerror, stopiteration error
#empty lists, floats,
'''
Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.
'''
def test_zip_longest(self):
#test for different number of entries, different values and different length of iterables
for args in [
['abc'],
[range(9), 'abc'],
['abc', range(4)],
[range(789), range(1987,2100), range(100,150)],
[range(1000), range(0), range(-100,150), range(120), range(420)],
[range(1000), range(0), range(100,150), range(-120,120), range(420), range(0)],
]:
#generate test result to check for Equal
target = [tuple([arg[i] if i < len(arg) else None for arg in args])
for i in range(max(map(len, args)))]
self.assertEqual(list(zip_longest(*args)), target)
self.assertEqual(list(zip_longest(*args, **{})), target)
#generate test result with fillvalue to check for Equal
target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
self.assertEqual(list(zip_longest(*args, **dict(fillvalue='X'))), target)
#check for empty input, check for empty lists as Input.
self.assertEqual(list(zip_longest()), list(zip()))
self.assertEqual(list(zip_longest([])), list(zip([])))
### Type Errors
#check for inadequate entries aka non iterables.
self.assertRaises(TypeError, zip_longest, (1,2,3,4), 'a', 2)
self.assertRaises(TypeError, zip_longest, '12345678', 'abcdefghijkl', 45)
self.assertRaises(TypeError, zip_longest, 3,4)
self.assertRaises(TypeError, zip_longest, None)
'''
Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument).
If func is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func. (For example, with the default operation of addition, elements may be any addable type including Decimal or Fraction.)
Usually, the number of elements output matches the input iterable. However, if the keyword argument initial is provided, the accumulation leads off with the initial value so that the output has one more element than the input iterable.
'''
def test_accumulate(self):
self.assertEqual(list(accumulate('abcd')),['a', 'ab', 'abc','abcd']) #strings
self.assertEqual(list(accumulate([1, 2, 3], initial=None)), [1, 3, 6]) #initial keyword set to None (default)
init = 100
#############
# test numbers
# test initial keyword
# test different operators
#############
for args in [
[], #empty lists
[7], #only one entry
np.arange(10), #integer
np.arange(-10,0), #negative integers
np.arange(0.0, 1.0, 0.1) # floats
]:
#generate test result to check for Equal
target = []
target_offset = [init]
current = 0
current_offset = init
for i in args:
current += i
current_offset += i
target.append(current)
target_offset.append(current_offset)
self.assertEqual(list(accumulate([*args])), target)
self.assertEqual(list(accumulate([*args], initial=init)), target_offset)
######################
### with func operator
######################
target = []
target_offset = [init]
current = 1
current_offset = init
for i in args:
current *= i
current_offset *= i
target.append(current)
target_offset.append(current_offset)
self.assertEqual(list(accumulate([*args], operator.mul)), target) # check multiplication
self.assertEqual(list(accumulate([*args], operator.mul, initial=init)), target_offset) #check multi with offset
target = []
target_offset = [init]
current = -10000000
current_offset = init
for i in args:
if i > current: current = i
if i > current_offset: current_offset = i
target.append(current)
target_offset.append(current_offset)
self.assertEqual(list(accumulate([*args], max)), target) # check max operator
self.assertEqual(list(accumulate([*args], max, initial=init)), target_offset) #check max with offset
current = 10000000
target = []
current_offset = init
target_offset = [init]
for i in args:
if i < current: current = i
if i < current_offset: current_offset = i
target.append(current)
target_offset.append(current_offset)
self.assertEqual(list(accumulate([*args], min)), target) #check min operator
self.assertEqual(list(accumulate([*args], min, initial=init)), target_offset) #check min with offset
#test for more different types:
for typ in int, complex, Decimal, Fraction:
self.assertEqual(
list(accumulate(map(typ, range(10)))),
list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])))
######################
### Raises Errors
######################
self.assertRaises(TypeError, accumulate) #too little args
self.assertRaises(TypeError, accumulate, [1,2,3,], operator.mul, 2) # too many args
# self.assertRaises(TypeError, accumulate, ([1],'a'))
# self.assertRaises(TypeError, accumulate, ['a',1, 'b']) #different types
# self.assertRaises(TypeError, accumulate, [1,2,3], 12345) # wrong kwd arg
self.assertRaises(TypeError, list, accumulate([1, []])) # args that are not combinable
self.assertRaises(TypeError, list, accumulate([1, 'a'])) # different type of args
|
24c1b7e242fa4dc5474cdca2c4c61e2caac41cde | ThomasZumsteg/project-euler | /problem_0042.py | 1,534 | 4.03125 | 4 | #!/usr/bin/env python3
"""
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?
"""
from re import sub
from math import sqrt
import logging
import sys
import time
logging.basicConfig(
stream=sys.stderr,
level=logging.INFO,
format='%(levelname)s: %(message)s')
def main():
f_handle = open("problem_0042.txt")
text = f_handle.read()
f_handle.close()
words = text.split(',')
count = 0
for word in words:
logging.debug(word)
word = sub("[^A-Z]",'',word)
logging.debug(word)
word_num = [ord(c)-64 for c in word]
logging.debug(word)
word_sum = sqrt(2*sum(word_num)+0.25) - 0.5
logging.debug(word_sum)
if word_sum == int(word_sum):
logging.info("{} is triangle word".format(word))
count += 1
print('Answer: {}'.format(count))
if __name__ == "__main__":
start = time.time()
main()
logging.info('That took {:4.2f} seconds'.format(time.time() - start))
|
a10655a6d5f299819028f220765000db0a73d673 | danielgu88/coffee-machine | /stage5.py | 3,922 | 3.96875 | 4 | water = 400
milk = 540
beans = 120
cups = 9
money = 550
ESPRESSO_WATER = 250
ESPRESSO_BEANS = 16
ESPRESSO_MONEY = 4
LATTE_WATER = 350
LATTE_MILK = 75
LATTE_BEANS = 20
LATTE_MONEY = 7
CAPPUCCINO_WATER = 200
CAPPUCCINO_MILK = 100
CAPPUCCINO_BEANS = 12
CAPPUCCINO_MONEY = 6
DRINK_CUPS = 1
def coffee_machine_state():
print("The coffee machine has:")
print("{} of water".format(water))
print("{} of milk".format(milk))
print("{} of coffee beans".format(beans))
print("{} of disposable cups".format(cups))
print("${} of money".format(money))
def check_resources(option):
if option == "1":
check_espresso()
elif option == "2":
check_latte()
else:
check_cappuccino()
def check_espresso():
if water - ESPRESSO_WATER >= 0 and beans - ESPRESSO_BEANS >= 0 and cups - DRINK_CUPS >= 0:
print("I have enough resources, making you a coffee!\n")
sell_one_espresso()
else:
if water < ESPRESSO_WATER:
print("Sorry, not enough water!\n")
if beans < ESPRESSO_BEANS:
print("Sorry, not enough beans!\n")
if cups < DRINK_CUPS:
print("Sorry, not enough cups!\n")
def check_latte():
if water - LATTE_WATER >= 0 and milk - LATTE_MILK >= 0 \
and beans - LATTE_BEANS >= 0 and cups - DRINK_CUPS >= 0:
print("I have enough resources, making you a coffee!\n")
sell_one_latte()
else:
if water < LATTE_WATER:
print("Sorry, not enough water!\n")
if milk < LATTE_MILK:
print("Sorry, not enough milk!\n")
if beans < LATTE_BEANS:
print("Sorry, not enough beans!\n")
if cups < DRINK_CUPS:
print("Sorry, not enough cups!\n")
def check_cappuccino():
if water - CAPPUCCINO_WATER >= 0 and milk - CAPPUCCINO_MILK >= 0 \
and beans - CAPPUCCINO_BEANS >= 0 \
and cups - DRINK_CUPS >= 0:
print("I have enough resources, making you a coffee!\n")
sell_one_cappuccino()
else:
if water < CAPPUCCINO_WATER:
print("Sorry, not enough water!\n")
if milk < CAPPUCCINO_MILK:
print("Sorry, not enough milk!\n")
if beans < CAPPUCCINO_BEANS:
print("Sorry, not enough beans!\n")
if cups < DRINK_CUPS:
print("Sorry, not enough cups!\n")
def sell_one_espresso():
global water, beans, cups, money
water -= ESPRESSO_WATER
beans -= ESPRESSO_BEANS
cups -= DRINK_CUPS
money += ESPRESSO_MONEY
def sell_one_latte():
global water, milk, beans, cups, money
water -= LATTE_WATER
milk -= LATTE_MILK
beans -= LATTE_BEANS
cups -= DRINK_CUPS
money += LATTE_MONEY
def sell_one_cappuccino():
global water, milk, beans, cups, money
water -= CAPPUCCINO_WATER
milk -= CAPPUCCINO_MILK
beans -= CAPPUCCINO_BEANS
cups -= DRINK_CUPS
money += CAPPUCCINO_MONEY
action = ""
while action != "exit":
action = input("Write action (buy, fill, take, remaining, exit):\n")
if action == "buy":
option = input("\nWhat do you want to buy? 1 - espresso,"
" 2 - latte, 3 - cappuccino, back - to main menu:\n")
if option in ["1", "2", "3"]:
check_resources(option)
else:
print()
elif action == "fill":
water += int(input("\nWrite how many ml of water do you want to add:\n"))
milk += int(input("Write how many ml of milk do you want to add:\n"))
beans += int(input("Write how many grams of coffee beans do you want to add:\n"))
cups += int(input("Write how many disposable cups of coffee do you want to add:\n"))
print()
elif action == "take":
print("\nI gave you ${}\n".format(money))
money -= money
elif action == "remaining":
print()
coffee_machine_state()
print()
|
ac0fedf2a9dfe237b8669b9e536ca75957214711 | coderman9/AdventOfCode | /1/soln_2.py | 184 | 3.609375 | 4 | with open("input", "r") as f:
input = f.readlines()
def f(x):
q = x//3 - 2
if q > 0:
q += f(q)
return max(q, 0)
r = sum([f(int(x)) for x in input])
print(r)
|
aae210462db52ebc63d1157df9ff253c067e622a | melo4/jianzhioffer | /礼物的最大价值.py | 695 | 3.625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/4/15 下午8:29
# @Author : Meng Xiao
class Solution:
def getMaxValue(self, values, rows, cols):
if not values or rows <= 0 or cols <= 0:
return 0
max_value = [0] * cols
for i in range(rows):
for j in range(cols):
left, up = 0, 0
if i > 0:
up = max_value[j]
if j > 0:
left = max_value[j-1]
max_value[j] = max(left, up) + values[i * cols + j]
maxValue = max_value[cols-1]
return maxValue
s = Solution()
matrix = [1,10,3,8,12,2,9,6,5,7,4,11,3,7,16,5]
print(s.getMaxValue(matrix, 4,4)) |
fb5db037b4e1858a44a78f58bfa8b9fd6621af21 | BlackPokers/Black_Poker | /Python_Server/bp/Deck.py | 1,883 | 3.609375 | 4 | import random
import Card
class Deck:
def __init__(self, card_list: list):
"""
デッキ
:param card_list: カードのリスト
"""
self.card_list = card_list
def first_step(self):
"""
ターンの最初のドロー
:return: ドローしたカード
"""
return self.get_top()
def get_top(self) ->Card:
"""
デッキの一番上を取得
:return: 取得したカード
"""
return self.card_list.pop(len(self.card_list) - 1)
def draw(self):
"""
ドロー!
:return: ドローしたカード
"""
return self.get_top()
def damage(self) ->Card:
"""
ダメージを受けたときにデッキを減らす
:return: デッキの一番上のカード
"""
return self.get_top()
def get(self, length: int) ->Card:
"""
デッキからカードを一枚取得
:param length: 何番目のカードか
:return: 取得したカード
"""
card = self.card_list[length]
self.card_list.pop(length)
return card
def shuffle(self):
"""
デッキのシャッフル
"""
random.seed()
random.shuffle(self.card_list)
# デッキからカードサーチ
def search(self, number: int, mark: str) -> Card:
"""
指定したカードのサーチ
:param number: 指定するカードの数字
:param mark: 指定するカードのマーク
:return: 指定したカードが存在するならそのカードをなければNone
"""
for i in range(0, len(self.card_list)):
if self.card_list[i].number == number and self.card_list[i].mark == mark:
return self.get(i)
return None
|
a86fb238467352e382900f729e7e6e5335155390 | ArtemFrantsiian/algorithms | /trees/traversals/Binary Tree Postorder Traversal/python/solution.py | 1,088 | 3.859375 | 4 | import unittest
from typing import List
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postorder(root: Node) -> List[int]:
if not root:
return []
result = []
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if not node:
continue
if not visited:
stack.extend([
(node, True),
(node.right, False),
(node.left, False)
])
else:
result.append(node.val)
return result
class Test(unittest.TestCase):
def test1(self):
node = Node(1, right=Node(2, left=Node(3)))
self.assertEqual(postorder(node), [3, 2, 1])
def test2(self):
node = Node(1, left=Node(2), right=Node(3, left=Node(4)))
self.assertEqual(postorder(node), [2, 4, 3, 1])
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(Test)
unittest.TextTestRunner(verbosity=2).run(suite)
|
fd090b4e4b659a74dcfd0c1fb837e35be5ae5230 | anirudhbandi96/Project-Euler-Solutions | /10001st_prime_number.py | 687 | 3.921875 | 4 | import math
import time
def is_prime(integer):
"""Returns True if input is a prime number"""
if integer < 2: # remove long if using Python 3
return False
if integer == 2:
return True
if integer % 2 == 0: # which can also be written as -> if not integer & 1:
return False
for divisor in range(3, int(math.sqrt(integer)) + 1, 2):
if integer % divisor == 0:
return False
return True
def nth_prime_number(n):
count = 0
num = 0
while(count<n):
num += 1
if is_prime(num):
count += 1
return num
start = time.time()
print(nth_prime_number(10001))
end = time.time()
print(end-start)
|
f500f7e69fa4287b3a20a2af6b4c0cdf4ab99fb1 | possibleit/LintCode-Algorithm-question | /maximumSwap.py | 1,749 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@Author : possibleit
@Date : 17:10 2019/3/29
@Description : 给定一个非负整数,你可以交换两个数位至多一次来获得最大的合法的数。
返回最大的合法的你能够获得的数。
1.给定的数字在 [0, 10^8] 内。
@Example :
样例1:
输入: 2736
输出: 7236
解释: 交换数字2和数字7.
样例2:
输入: 9973
输出: 9973
解释: 不用交换.
@Solution :
思路是将所给的'num'(10^8)转化成一个list,例如2736,转化成[6,3,7,2]
之后从list中取出最后一个数字,即所给'num'的第一个数字,并用余下的list与
此数字比较,若存在比它大的,则交换位置,并将交换过程中较大的数字加到list末尾;
若不存在,则将取出最后一个数字的list当作新的list,递归进行上述操作后,将取出
的数字加到list末尾;最终将list转化位数字返回即可。
'''
def maximumSwap(num):
if num <= 10:
return num
list = []
pre = num
i = 10
while pre >= 1:
bot = pre % i;
pre = pre / i;
bot = int(bot)
list.append(bot)
list = set(list)
x = len(list) - 1
s = list[x]
while x > 0:
s = s * 10 + list[x - 1]
x = x - 1
return s
def set(list):
#list[6,3,7,2]
if len(list) < 1:
return list
x = len(list) - 1
xs = list[x]
xx = xs
del list[x]#list[6,3,7]
for i in list:
if i > xs:
xs = i
if xs == xx:
set(list)
else:
index = list.index(xs)
list[index] = xx#list[6,3,2]
list.append(xs)#list[6,3,2,7]
return list
print (maximumSwap(2736)) |
c912d8a378c4a08b1f119ee17017a7f792742e6b | arnika13/Fun_With_Python_Graphics | /rainbow.py | 358 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 3 13:44:40 2018
@author: LocalUser
"""
import turtle
turtle.bgcolor("black")
colors=["yellow","blue","red","green","orange","purple","pink"]
t = turtle.Turtle()
t.speed(20)
for x in range(360):
t.pencolor(colors[x%len(colors)])
t.width(x/150+1)
t.forward(x)
t.left(60)
turtle.done()
|
02bf55e56b9948cd7d5151a44070d7713a4878e7 | programhung/learn-python | /PythonCode/Maths/ex3.py | 623 | 3.59375 | 4 | # Calculate function
def ecal(enumber):
money = 0
if enumber < 0:
print("The electrical number cannot be negative!")
return 0
if enumber <= 50:
money = enumber * 4
return money
if enumber <= 100:
money = 50 * 4 + (enumber - 50) * 3
return money
else:
money = 50 * 4 + 50 * 3 + (enumber - 100) * 2
return money
print("Enter the electric number of first family:")
ef1 = float(input())
mf1 = ecal(ef1)
print("Enter the electric number of second family:")
ef2 = float(input())
mf2 = ecal(ef2)
print("Family \t| F1 \t\t| F2")
print("enumber | %f \t| %f"%(ef1,ef2))
print("money \t| %f \t| %f"%(mf1,mf2))
|
7902f291a8dc1fac5dc0c5549e79c8a3717a1c2f | theMkrv/Deses | /Sam_rab_5.py | 409 | 3.609375 | 4 | class Value:
def __init__(self, val=0):
self.val = val
def __get__(self, obj, obj_type):
return int(self.val)
def __set__(self, obj, value):
self.val = value - value * obj.commission
class Account:
amount = Value()
def __init__(self, commission):
self.commission = commission
new_account = Account(0.1)
new_account.amount = 100
print(new_account.amount) |
be891202c9ed8d469ba9cb58ad15d01a09656f1c | RancyChepchirchir/AI-1 | /week3/__init__.py | 16,736 | 4.09375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def calc_posterior_p():
# GRADED
# Given the values in the tables above, calculate the posterior for:
# "If you know a user watches Youtube every day,
# what is the probability that they are under 35?"
# Assign float (posterior probability between 0 and 1) to ans1
# YOUR ANSWER BELOW
# Comments added by Rushikesh
# posterior = ( likelihood * prior )/norm_marginal
# Exa P(E/H) =( P(H/E) * P(H) ) /P(E)
# In THis case P(B/A) = P(A/B) * P(B) /P(A)
# Likelihood = P(A=1/P(B<35)
# Prior P(B<35)
# Marginal P(A=1 )
# How to calculate norm_marginal
# P(A=1) = P(A=1/B<=35) * P(B<=35) +
# P(A=1/35 < B < 65 ) * P(35 < B < 65 ) +
# P(A=1/B >= 65 ) * P(B >= 65 )
_likelihood = 0.9
_prior = 0.25
norm_marginal = (.9 * .25) + (.5 * .45) + (.1 * .3)
return (_likelihood * _prior) / norm_marginal
# GRADED
# Code a function called `calc_posterior`
# ACCEPT three inputs
# Two floats: the likelihood and the prior
# One list of tuples, where each tuple has two values corresponding to:
# # ( P(Bn) , P(A|Bn) )
# # # Assume the list of tuples accounts for all potential values of B
# # # And that those values of B are all mutually exclusive.
# The list of tuples allows for the calculation of normalization constant.
# RETURN a float corresponding to the posterior probability
# YOUR ANSWER BELOW
def calc_posterior(likelihood, prior, norm_list̥):
"""
Calculate the posterior probability given likelihood,
prior, and normalization
Positional Arguments:
likelihood -- float, between 0 and 1
prior -- float, between 0 and 1
norm_list -- list of tuples, each tuple has two values
the first value corresponding to the probability of a value of "b"
the second value corresponding to the probability of
a value of "a" given that value of "b"
Example:
likelihood = .8
prior = .3
norm_list = [(.25 , .9), (.5, .5), (.25,.2)]
print(calc_posterior(likelihood, prior, norm_list))
̥ # --> 0.45714285714285713
"""
marginal_norm = sum([event[0] * event[1] for event in norm_list])
return (likelihood * prior) / marginal_norm
# GRADED
# Build a function called "x_preprocess"
# ACCEPT one input, a numpy array
# Array may be one or two dimensions
# If input is two dimensional, make sure there are more rows than columns
# Then prepend a column of ones for intercept term
# If input is one-dimensional, prepend a one
# RETURN a numpy array, prepared as described above,
# which is now ready for matrix multiplication with regression weights
def x_preprocess(input_x):
"""
Reshape the input (if needed), and prepend a "1" to every observation
Positional Argument:
input_x -- a numpy array, one- or two-dimensional
Example:
input1 = np.array([[2,3,6,9],[4,5,7,10]])
input2 = np.array([2,3,6])
input3 = np.array([[2,4],[3,5],[6,7],[9,10]])
for i in [input1, input2, input3]:
print(x_preprocess(i), "\n")
# -->[[ 1. 2. 4.]
[ 1. 3. 5.]
[ 1. 6. 7.]
[ 1. 9. 10.]]
[1 2 3 6]
[[ 1. 2. 4.]
[ 1. 3. 5.]
[ 1. 6. 7.]
[ 1. 9. 10.]]
Assumptions:
Assume that if the input is two dimensional, that the observations are more numerous
than the features, and thus, the observations should be the rows, and features the columns
"""
if input_x.ndim == 1:
return np.insert(input_x, 0, 1, axis=0)
elif input_x.ndim == 2:
rows = len(input_x[:, 0])
col = len(input_x[0, :])
if rows < col:
input_x = np.transpose(input_x)
ones_col = np.ones(len(input_x[:, 0]))
return np.insert(input_x, 0, ones_col, axis=1)
# alternate ways
# ndim = input_x.ndim
# if ndim == 2:
# rows = len(input_x[:, 0])
# col = len(input_x[0, :])
# if rows < col:
# input_x = np.transpose(input_x)
# ones_col = np.ones(len(input_x[:, 0]))
# input_x = np.insert(input_x, 0, ones_col, axis=1)
# if ndim == 1:
# input_x = np.insert(input_x, 0, 1, axis=0)
# return input_x
# GRADED
# Build a function called `calculate_map_coefficients`
# ACCEPT four inputs:
# Two numpy arrays; an X-matrix and y-vector
# Two positive numbers, a lambda parameter, and value for sigma^2
# RETURN a 1-d numpy vector of weights.
# ASSUME your x-matrix has been preprocessed:
# observations are in rows, features in columns, and a column of 1's prepended.
# Use the above equation to calculate the MAP weights.
# # This will involve creating the lambda matrix.
# # The MAP weights are equal to the Ridge Regression weights
# NB: `.shape`, `np.matmul`, `np.linalg.inv`,
# `np.ones`, `np.identity` and `np.transpose` will be valuable.
# If either the "sigma_squared" or "lambda_param" are equal to 0, the return will be
# equivalent to ordinary least squares.
# YOUR ANSWER BELOW
def calculate_map_coefficients(aug_x, output_y, lambda_param, sigma_squared):
"""
Calculate the maximum a posteriori LR parameters
Positional arguments:
aug_x -- x-matrix of training input data, augmented with column of 1's
output_y -- vector of training output values
lambda_param -- positive number; lambda parameter that
controls how heavily to penalize large coefficient values
sigma_squared -- data noise estimate
Example:
output_y = np.array([208500, 181500, 223500,
140000, 250000, 143000,
307000, 200000, 129900,
118000])
aug_x = np. array([[ 1., 1710., 2003.],
[ 1., 1262., 1976.],
[ 1., 1786., 2001.],
[ 1., 1717., 1915.],
[ 1., 2198., 2000.],
[ 1., 1362., 1993.],
[ 1., 1694., 2004.],
[ 1., 2090., 1973.],
[ 1., 1774., 1931.],
[ 1., 1077., 1939.]])
lambda_param = 0.01
sigma_squared = 1000
map_coef = calculate_map_coefficients(aug_x, output_y,
lambda_param, sigma_squared)
ml_coef = calculate_map_coefficients(aug_x, output_y, 0,0)
print(map_coef)
# --> np.array([-576.67947107 77.45913349 31.50189177])
print(ml_coef)
#--> np.array([-2.29223802e+06 5.92536529e+01 1.20780450e+03])
Assumptions:
-- output_y is a vector whose length is the same as the
number of rows in input_x
-- input_x has more observations than it does features.
-- lambda_param has a value greater than 0
"""
xT = np.transpose(aug_x)
lambda_mul_singma = lambda_param * sigma_squared;
fist_inv = np.linalg.inv(lambda_mul_singma + np.matmul(xT, aug_x))
coefs = np.matmul(np.matmul(fist_inv, xT), output_y)
return coefs
# GRADED
# Code a function called `estimate_data_noise`
# ACCEPT three inputs, all numpy arrays
# One matrix corresponding to the augmented x-matrix
# Two vectors, one of the y-target, and one of ML weights.
# RETURN the empirical data noise estimate: sigma^2. Calculated with equation given above.
# NB: "n" is the number of observations in X (rows)
# "d" is the number of features in aug_x (columns)
# YOUR ANSWER BELOW
def estimate_data_noise(aug_x, output_y, weights):
"""Return empirical data noise estimate \sigma^2
Use the LR weights in the equation supplied above
Positional arguments:
aug_x -- matrix of training input data
output_y -- vector of training output values
weights -- vector of LR weights calculated from output_y and aug_x
Example:
output_y = np.array([208500, 181500, 223500,
140000, 250000, 143000,
307000, 200000, 129900,
118000])
aug_x = np. array([[ 1., 1710., 2003.],
[ 1., 1262., 1976.],
[ 1., 1786., 2001.],
[ 1., 1717., 1915.],
[ 1., 2198., 2000.],
[ 1., 1362., 1993.],
[ 1., 1694., 2004.],
[ 1., 2090., 1973.],
[ 1., 1774., 1931.],
[ 1., 1077., 1939.]])
ml_weights = calculate_map_coefficients(aug_x, output_y, 0, 0)
print(ml_weights)
# --> [-2.29223802e+06 5.92536529e+01 1.20780450e+03]
sig2 = estimate_data_noise(aug_x, output_y, ml_weights)
print(sig2)
#--> 1471223687.1593
Assumptions:
-- training_input_y is a vector whose length is the same as the
number of rows in training_x
-- input x has more observations than it does features.
-- lambda_param has a value greater than 0
"""
n = len(aug_x[:, 0])
d = len(aug_x[0, :])
diff = []
for element in range(len(output_y)):
print(element)
diff.append((output_y[element] - aug_x[element] @ weights) ** 2)
return sum(diff) / (n - d)
# GRADED
# Code a function called "calc_post_cov_mtx"
# ACCEPT three inputs:
# One numpy array for the augmented x-matrix
# Two floats for sigma-squared and a lambda_param
# Calculate the covariance matrix of the posterior (capital sigma), via equation given above.
# RETURN that matrix.
# YOUR ANSWER BELOW
def calc_post_cov_mtx(aug_x, sigma_squared, lambda_param):
"""
Calculate the covariance of the posterior for Bayesian parameters
Positional arguments:
aug_x -- matrix of training input data; preprocessed
sigma_squared -- estimation of sigma^2
lambda_param -- lambda parameter that controls how heavily
to penalize large weight values
Example:
output_y = np.array([208500, 181500, 223500,
140000, 250000, 143000,
307000, 200000, 129900,
118000])
aug_x = np. array([[ 1., 1710., 2003.],
[ 1., 1262., 1976.],
[ 1., 1786., 2001.],
[ 1., 1717., 1915.],
[ 1., 2198., 2000.],
[ 1., 1362., 1993.],
[ 1., 1694., 2004.],
[ 1., 2090., 1973.],
[ 1., 1774., 1931.],
[ 1., 1077., 1939.]])
lambda_param = 0.01
ml_weights = calculate_map_coefficients(aug_x, output_y,0,0)
sigma_squared = estimate_data_noise(aug_x, output_y, ml_weights)
print(calc_post_cov_mtx(aug_x, sigma_squared, lambda_param))
# --> [[ 9.99999874e+01 -1.95016334e-02 -2.48082095e-02]
[-1.95016334e-02 6.28700339e+01 -3.85675510e+01]
[-2.48082095e-02 -3.85675510e+01 5.10719826e+01]]
Assumptions:
-- training_input_y is a vector whose length is the same as the
number of rows in training_x
-- lambda_param has a value greater than 0
"""
return np.linalg.inv(lambda_param * np.identity(aug_x.shape[1]) + (1 / sigma_squared * (aug_x.T @ aug_x)))
# GRADED
# Code a function called "predict"
# ACCEPT four inputs, three numpy arrays, and one number:
# A 1-dimensional array corresponding to an augmented_x vector.
# A vector corresponding to the MAP weights, or "mu"
# A square matrix for the "big_sigma" term
# A positive number for the "sigma_squared" term
# Using the above equations
# RETURN mu_0 and sigma_squared_0 - a point estimate and variance
# for the prediction for x.
# YOUR ANSWER BELOW
def predict(aug_x, weights, big_sig, sigma_squared):
"""
Calculate point estimates and uncertainty for new values of x
Positional Arguments:
aug_x -- augmented matrix of observations for predictions
weights -- MAP weights calculated from Bayesian LR
big_sig -- The posterior covarience matrix, from Bayesian LR
sigma_squared -- The observed uncertainty in Bayesian LR
Example:
output_y = np.array([208500, 181500, 223500,
140000, 250000, 143000,
307000, 200000, 129900,
118000])
aug_x = np. array([[ 1., 1710., 2003.],
[ 1., 1262., 1976.],
[ 1., 1786., 2001.],
[ 1., 1717., 1915.],
[ 1., 2198., 2000.],
[ 1., 1362., 1993.],
[ 1., 1694., 2004.],
[ 1., 2090., 1973.],
[ 1., 1774., 1931.],
[ 1., 1077., 1939.]])
lambda_param = 0.01
ml_weights = calculate_map_coefficients(aug_x, output_y,0,0)
sigma_squared = estimate_data_noise(aug_x, output_y, ml_weights)
map_weights = calculate_map_coefficients(aug_x, output_y, lambda_param, sigma_squared)
big_sig = calc_post_cov_mtx(aug_x, sigma_squared, lambda_param)
to_pred2 = np.array([1,1700,1980])
print(predict(to_pred2, map_weights, big_sig, sigma_squared))
#-->(158741.6306608729, 1593503867.9060116)
"""
mu_0 = aug_x.T@weights
sigma_squared_0 = sigma_squared+(aug_x.T@big_sig)@aug_x
return mu_0, sigma_squared_0
if __name__ == '__main__':
calc_posterior_p()
likelihood = .8
prior = .3
norm_list = [(.25, .9), (.5, .5), (.25, .2)]
# print(calc_posterior(likelihood, prior, norm_list))
input1 = np.array([[2, 3, 6, 9], [4, 5, 7, 10]])
# input2 = np.array([2, 3, 6])
# input3 = np.array([[2, 4], [3, 5], [6, 7], [9, 10]])
# print(x_preprocess(input1))
output_y = np.array([208500, 181500, 223500,
140000, 250000, 143000,
307000, 200000, 129900,
118000])
aug_x = np.array([[1., 1710., 2003.],
[1., 1262., 1976.],
[1., 1786., 2001.],
[1., 1717., 1915.],
[1., 2198., 2000.],
[1., 1362., 1993.],
[1., 1694., 2004.],
[1., 2090., 1973.],
[1., 1774., 1931.],
[1., 1077., 1939.]])
lambda_param = 0.01
sigma_squared = 1000
# print(calculate_map_coefficients(aug_x, output_y, lambda_param, sigma_squared))
# print(calculate_map_coefficients(aug_x, output_y, 0, 0))
output_y = np.array([208500, 181500, 223500,
140000, 250000, 143000,
307000, 200000, 129900,
118000])
aug_x = np.array([[1., 1710., 2003.],
[1., 1262., 1976.],
[1., 1786., 2001.],
[1., 1717., 1915.],
[1., 2198., 2000.],
[1., 1362., 1993.],
[1., 1694., 2004.],
[1., 2090., 1973.],
[1., 1774., 1931.],
[1., 1077., 1939.]])
ml_weights = calculate_map_coefficients(aug_x, output_y, 0, 0)
# sig2 = estimate_data_noise(aug_x, output_y, ml_weights)
output_y = np.array([208500, 181500, 223500,
140000, 250000, 143000,
307000, 200000, 129900,
118000])
aug_x = np.array([[1., 1710., 2003.],
[1., 1262., 1976.],
[1., 1786., 2001.],
[1., 1717., 1915.],
[1., 2198., 2000.],
[1., 1362., 1993.],
[1., 1694., 2004.],
[1., 2090., 1973.],
[1., 1774., 1931.],
[1., 1077., 1939.]])
lambda_param = 0.01
ml_weights = calculate_map_coefficients(aug_x, output_y, 0, 0)
sigma_squared = estimate_data_noise(aug_x, output_y, ml_weights)
print(calc_post_cov_mtx(aug_x, sigma_squared, lambda_param))
|
f40bf6c35a51536c365f49519e516e955baa423a | CorCobLex/UniumWork | /RectangleAndCircles.py | 857 | 4.15625 | 4 | while(True):
print("Введите длину прямоугольника:")
lenght=int(input())
print("Введите ширину прямоугольника:")
height=int(input())
print("Введите радиус 1 окружности:")
radius1=int(input())
print("Введите радиус 2 окружности:")
radius2=int(input())
SRec=height*lenght
Sokr1 = radius1*radius1*4
Sokr2 = radius2*radius2*4
if(Sokr1+Sokr2<SRec):
print("Окружности поместяться в прямогуольник точно")
elif(Sokr1+Sokr2==SRec):
print("Окружности поместяться в прямогуольник и займут его полностью")
else:
print("Окружности не поместились :(\n")
|
39e852db11760733c076461841c6b9c9c9cce06a | Charleina/cs_362 | /hw3/leapyear.py | 857 | 4.09375 | 4 | #to run the file please type: python charlene_wang_hw1.py
#it should print out the values
#years for user input
y = input("Enter year: ")
#checking the values in the array to see if they match the criteria for leap years, if they do i will print true and their value if not i will print false and their value (ex. true 2000)
if (y % 4) == 0:
if((y % 100)==0):
#if it is divisible by 4 and 100 then we must check if it is or is not divisible by 400 because we will get different answers for each
if(y% 400) == 0:
print("True %d" % y)
else:
print("False %d" % y)
#if it is not divisible by 100 but is divisible by 4 then it is true for sure.
else:
print("True %d" % y)
#if it is not divisible by 4 then it is for sure not a leap year
else:
print("False %d" % y)
|
32a37585aeb9d5f357074d190436dab4c29cccdc | leomarkcastro/Arithmetic-Progression-Project | /yield.py | 128 | 3.703125 | 4 | def fun():
x = 0
while True:
x += 1
yield x
x = fun()
for i in range(30):
print next(x)
|
32b5d863b1fcf585f6b90b9c22d9c941978c7f71 | akimi-yano/algorithm-practice | /lc/581.ShortestUnsortedContinuousSuba.py | 1,691 | 4.03125 | 4 | # 581. Shortest Unsorted Continuous Subarray
# Medium
# 3431
# 165
# Add to List
# Share
# Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.
# Return the shortest such subarray and output its length.
# Example 1:
# Input: nums = [2,6,4,8,10,9,15]
# Output: 5
# Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
# Example 2:
# Input: nums = [1,2,3,4]
# Output: 0
# Example 3:
# Input: nums = [1]
# Output: 0
# Constraints:
# 1 <= nums.length <= 104
# -105 <= nums[i] <= 105
# Follow up: Can you solve it in O(n) time complexity?
# This solution works:
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
targets = list(sorted(nums))
start = len(nums)-1
end = 0
for i in range(len(nums)):
if nums[i] != targets[i]:
start = min(start, i)
end = max(end,i)
if start >= end:
return 0
return end - start +1
# This solution works - optimization:
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
left, right = len(nums), len(nums)-1
prev = float('-inf')
for i, num in enumerate(nums):
if num < prev:
left = min(left, i)
while left - 1 >= 0 and nums[left-1] > num:
left -= 1
right = i
prev = max(prev, num)
return right - left + 1 |
a8f2e7f5ed2d4c5c2742497c77a8105ece6353e4 | WeaselE/Small-Programs | /List Squared.py | 281 | 3.96875 | 4 | def num_squared(num):
return int(num ** 2)
lst = [int(i) for i in input("Enter numbers to square them (spaces between numbers): ").split()]
if lst:
sqr_lst = [num_squared(i) for i in lst]
else:
lst = range(11)
sqr_lst = [num_squared(i) for i in lst]
print(sqr_lst) |
02e46c01a9a647d2563f1a507c709046f2c37fe0 | khalid-hussain/python-workbook | /01-Introduction-to-Programming/031-units-of-pressure.py | 364 | 3.921875 | 4 | pressure = float(input('Input pressure (kilo-pascals): '))
poundsPerInchSquare = pressure * 0.145
mmHg = pressure / 0.1333223684
atm = pressure / 101.325
print('Pressure in pounds per square inch is {:.2f}.'.format(
poundsPerInchSquare))
print('Pressure in millimeter mercury is {:.2f}.'.format(mmHg))
print('Pressure in atmospheres is {:.2f}.'.format(atm))
|
069eb2c5c87376609c6befae31676ca0122670b3 | vijulondhe/Weather_Data_Storage_Retrieval | /database.py | 1,578 | 3.53125 | 4 | # Imports MongoClient for base level access to the local MongoDB
from pymongo import MongoClient
class Database:
# Class static variables used for database host ip and port information, database name
# Static variables are referred to by using <class_name>.<variable_name>
HOST = '127.0.0.1'
PORT = '27017'
DB_NAME = 'weather_db'
def __init__(self):
self._db_conn = MongoClient(f'mongodb://{Database.HOST}:{Database.PORT}')
self._db = self._db_conn[Database.DB_NAME]
# This method finds a single document using field information provided in the key parameter
# It assumes that the key returns a unique document. It returns None if no document is found
def get_single_data(self, collection, key):
db_collection = self._db[collection]
document = db_collection.find_one(key)
return document
# This method inserts the data in a new document. It assumes that any uniqueness check is done by the caller
def insert_single_data(self, collection, data):
db_collection = self._db[collection]
document = db_collection.insert_one(data)
return document.inserted_id
# This method finds all document using field information provided in the key parameter
# Created to retrive more than one record
def get_all_data(self, collection, key):
db_collection = self._db[collection]
document=[]
for x in db_collection.find(key):
document.append(x)
return document |
e420142492b65b26ee0cb1e9c13ba610e8e9ecc0 | tejas-rane/pyground | /Lambda-Map-Filter/2_check_even.py | 118 | 3.515625 | 4 | def check_even(num):
return num % 2 == 0
my_nums = [0, 1, 2, 3, 4, 5, 6]
print(list(filter(check_even,my_nums))) |
5a0976a84a8d17e6d1735b99e3cee311a91aa8bc | inishchith/GithubTools | /GithubIssues.py | 1,139 | 3.640625 | 4 | import requests
import sys
#getting url response using requests API
def get_responses(url):
r = requests.get(url)
response = r.json()
return response['total_count']
#main function
if __name__ == '__main__':
statistics = {}
username = (input("\nEnter github username\n"))
url = "https://api.github.com/search/issues?q=author:" + username + "+type:"
url1 = url + "issue"
url2 = url + "issue+is:closed"
url3 = url + "issue+is:open"
url4 = url + "pr"
url5 = url + "pr+is:open"
url6 = url + "pr+is:closed+is:unmerged"
url7 = url + "pr+is:closed+is:merged"
try:
statistics['Total Issues'] = get_responses(url1)
statistics['Closed Issues'] = get_responses(url2)
statistics['Open Issues'] = get_responses(url3)
statistics['Open PRs'] = get_responses(url5)
statistics['Unmerged PRs'] = get_responses(url6)
statistics['Merged PRs'] = get_responses(url7)
statistics['Total PRs'] = get_responses(url4)
except:
print("Check if username is valid/internet connection")
sys.exit()
print("Statistics for user " + str(username))
for key,value in statistics.items():
print(str(key) + " : " + str(value))
print()
|
ba0760b5ed1310de8fbe4d5ad924c7d0e21a0bf2 | ikki2530/holberton-system_engineering-devops | /0x16-api_advanced/2-recurse.py | 1,098 | 3.625 | 4 | #!/usr/bin/python3
"""
queries the Reddit API and prints the titles of the first 10 hot posts
listed for a given subreddit.
"""
import requests
def new_recurse(subreddit, hot_list=[], page=''):
"""Adding new recursion"""
titles = []
if page is None:
return hot_list
if subreddit:
try:
heads = {'User-agent': 'dagomez2530'}
url = "https://www.reddit.com/r/{}/hot.json?after={}".format(
subreddit, page)
response = requests.get(url, headers=heads)
data_reddit = response.json()
i = 0
lista_hot = data_reddit['data']['children']
lg = len(lista_hot)
for i in range(lg):
hot_list.append(lista_hot[i]['data']['title'])
after = data_reddit['data']['after']
titles = new_recurse(subreddit, hot_list, after)
return titles
except:
return None
def recurse(subreddit, hot_list=[]):
"""top ten subreddits titles"""
titles = new_recurse(subreddit, hot_list, '')
return titles
|
a402a8172f68c5f238bb6c0b2eb98f58a60f0169 | Moelf/S19-129L | /Zach/hw2/ex2.py | 727 | 4.125 | 4 | #!/usr/bin/env python3
sent=input("Please input a sentence: ")
list1=[len(x) for x in sent.split()] #Count all characters excluding only spaces; includes punctuation in 'characters'
sent=sent.replace(',',' ') #separates words by commas, etc
sent=sent.replace(';',' ') #Francesco said this was the punctuation that mattered; don't need to account for every possible one
sent=sent.replace(':',' ')
sent=sent.replace('.',' ')
sent=sent.replace('/',' ')
sent=sent.replace('\\',' ')
sent=sent.replace('-',' ')
sent=sent.replace('(',' ')
sent=sent.replace(')',' ')
sent=sent.replace('&',' ')
list2=[len(x) for x in sent.split()]
print("The number of words is ", len(list2))
print("The number of characters is ", sum(list1))
|
4be6438b7bffe1276a9570756eab4912019814fa | srijaniintm/Code-Combat | /Python/01-Alan's-Number-Game.py | 353 | 4.125 | 4 | # function to reverse the number.
def reverse(n):
temp,rev,rem = n, 0, 0
while temp != 0:
rem = temp % 10
if temp < 0:
rem = rem - 10
rev = rev*10 + rem
temp = int(temp/10)
return rev
n = int(input()) # taking input.
print(n+reverse(n)) # printing the addition of the number and its reverse.
|
5e9f3b87b96f468e7bb28b32dbd49c6494b0841a | Garen-Wang/ai-learning | /ch02/02-2.py | 1,252 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def forward(x):
a = x ** 2
b = np.log(a)
c = np.sqrt(b)
return a, b, c
def backward(x, a, b, c, y):
loss = c - y
delta_c = c - y
delta_b = 2 * np.sqrt(b) * delta_c
delta_a = a * delta_b
delta_x = delta_a * 0.5 / x
return loss, delta_x, delta_a, delta_b, delta_c
def update(x, delta_x):
x = x - delta_x
if x < 1:
x = 1.1
return x
def draw_function(X, Y):
x = np.linspace(1.2, 10)
a = x * x
b = np.log(a)
c = np.sqrt(b)
plt.plot(x, c)
plt.plot(X, Y, 'x')
d = 1 / (np.sqrt(np.log(x * x)))
plt.plot(x, d)
plt.show()
X, Y = [], []
if __name__ == '__main__':
x = 1.3
y = 1.8
eps = 1e-4
for i in range(20):
a, b, c = forward(x)
print('a={}, b={}, c={}'.format(a, b, c))
X.append(x)
Y.append(c)
loss, delta_x, delta_a, delta_b, delta_c = backward(x, a, b, c, y)
if abs(loss) < eps:
print('done!')
break
x = update(x, delta_x)
print('delta_c={}, delta_b={}, delta_a={}, delta_x={}'.format(delta_c, delta_b, delta_a, delta_x))
draw_function(X, Y) |
a4cdf390f0df7bb95e5a5e979d5c2f84fa465720 | YulanJS/Advanced_Programming_With_Python | /HW5.py | 4,986 | 4.125 | 4 | # ----------------------------------------------------------------------
# Name: HW5
# Purpose: Practice lambda, decorator, and generator
#
# Date: Spring 2019
# ----------------------------------------------------------------------
"""
Five questions to practice lambda, decorator, and generator.
For specific functionality of each function, please see each function's
document.
"""
import string
def most_e(*args):
"""
From arbitrary number of strings, pick up the string with the most
occurrences of letter 'e' (case insensitive).
:param args: (string) arbitrary number of strings
:return: (string ) string with the most occurrences of the letter
'e' (upper or lower)
"""
if not args:
return None
return max(args, key=lambda string: string.lower().count('e'))
def top_midterm(grades, n=4):
"""
Get a list of names of n students with highest midterm grades
sorted from highest grade to lowest grade.
:param grades: (dictionary) Keys are students' names. Values are
lists of grades: [homework grade, question of the week grade,
midterm grade]. Three types of grades must be in that order.
:param n: (number) top n students
:return: (list) A list of names of the top n students with highest
midterm grade. The student with the highest midterm grade should
be put in the first one in the list.
"""
return sorted(grades, key=lambda student: grades[student][2],
reverse=True)[:n]
def shout(function):
"""
decorate function: change all letters in strings returned from
function into uppercase, and add !!! to the end.
:param function: the function to be decorated, it returns strings.
:return: decorated function.
"""
def wrapper(*args):
return function(*args).upper() + "!!!"
return wrapper
@shout
def greet(name):
"""
Return a personalized hello message.
:param name: (string)
:return: (string)
"""
return f'Hello {name}'
@shout
def repeat(phrase, n):
"""
Repeat the specified string n times
with a space character in between.
:param phrase: (string)
:param n: number of times the phrase will be repeated
:return:
"""
words = phrase.split()
return ' '.join(n * words)
def repeat_character(string, n):
"""
Generate string of length n, one for each character in the string
specified.
:param string: (string)
:param n: (number) repeat each character in the given string n times
:return: (string) generates string of length n, one for each
character in the string specified
"""
for letter in string:
yield letter * n
def alpha_labels(start_label='A'):
"""
Generates labels alphabetically, starting with the star_label, then
increasing the length after reaching Z.
:param start_label:(string) a string of repeated uppercase letters,
default value is 'A'
:return: (strings) Generates labels alphabetically,
starting with the star_label, then increasing the length after
reaching Z.
"""
alphabet = string.ascii_uppercase
curr_length = len(start_label)
yield from repeat_character(alphabet[ord(start_label[0]) - ord('A'):],
curr_length)
while True:
curr_length += 1
yield from repeat_character(alphabet, curr_length)
def main():
print("question 1: ")
print(most_e())
print(most_e('Go', 'Spartans', 'Take', 'Selfies', 'eat',
'APPLES'))
print(most_e('Go', 'Spartans', 'APPLES'))
print(most_e('Go', 'Spartans', 'Eat'))
print(most_e('Go', 'Spartans', 'Take', 'Selfies', 'degree'))
print(most_e('Spartans'))
print()
print("question 2: ")
empty_class = {}
cs122 = {'Zoe': [90, 100, 75], 'Alex': [86, 90, 96],
'Dan': [90, 60, 70], 'Anna': [60, 80, 100],
'Ryan': [100, 95, 80], 'Bella': [79, 70, 99]}
print(top_midterm(cs122, 2))
print(top_midterm(cs122))
print(top_midterm(cs122, 10))
print(top_midterm(empty_class, 6))
print(cs122)
print()
print("question 3: ")
print(greet('Rula'))
print(repeat('Python is fun!', 3))
print(repeat('Go Spartans!', 5))
print()
print("question 4: ")
vocabulary = repeat_character('ACGT', 3)
print(next(vocabulary)) # AAA
print(next(vocabulary)) # CCC
print(next(vocabulary)) # GGG
print(next(vocabulary)) # TTT
# print(next(vocabulary)) # StopIteration
import string
labels = repeat_character(string.ascii_uppercase, 2)
for each_label in labels:
print(each_label) # AA through ZZ is printed.
print()
print("question 5: ")
infinite_generator = alpha_labels("XXX")
print(next(infinite_generator))
print(next(infinite_generator))
print(next(infinite_generator))
print(next(infinite_generator))
print(next(infinite_generator))
if __name__ == "__main__":
main()
|
504017f5fdd51c17701331aab358d5cea2a22e69 | sjindal22/python-programming | /csv-parse-condition.py | 336 | 4.03125 | 4 | import csv
def csvParser(file):
with open(file, 'r') as f:
csvFile = csv.reader(f, delimiter=",")
header = next(csvFile)
print(header)
for people in csvFile:
if(int(people[1]) >= 30):
print("Name: {name}, City: {city}".format(name=people[0], city=people[2]))
csvParser("sample_input.csv")
|
9e6cb1cb56799eb64a080227a71d1db17941f1f2 | Kingcitaldo125/Python-Files | /src/colors.py | 1,550 | 3.90625 | 4 | #Color Library
class ColorLibrary(object):
def __init__(self):
""" """
self.colors = {"red":(255,0,0),"green":(0,255,0),
"blue":(0,0,255),"cyan":(0,225,255),"yellow":(236,236,17),
"orange":(234,122,7),"purple":(228,29,212),"white":(255,255,255),
"black":(0,0,0)}
def returncolor(self,stn):
""" """
red = self.colors["red"]
blue = self.colors["blue"]
black = self.colors["black"]
cyan = self.colors["cyan"]
green = self.colors["green"]
orange = self.colors["orange"]
purple = self.colors["purple"]
white = self.colors["white"]
yellow = self.colors["yellow"]
if(stn == "blue"):
return blue
elif(stn == yellow):
return yellow
elif(stn == "black"):
return black
elif(stn == "red"):
return red
elif(stn == "purple" or stn == "violet"):
return purple
elif(stn == "white"):
return white
elif(stn == "cyan" or stn == "turquoise"):
return cyan
elif(stn == "green"):
return green
elif(stn == "orange"):
return orange
#TEST
cl = ColorLibrary()
cyan = cl.returncolor("cyan")
red = cl.returncolor("red")
green = cl.returncolor("green")
blue = cl.returncolor("blue")
orange = cl.returncolor("orange")
purple = cl.returncolor("purple")
black = cl.returncolor("black")
yellow = cl.returncolor("yellow")
white = cl.returncolor("white")
#print(ttuple)
|
cb902c25e21843a6be43beff67a2cb12aca4a3a4 | Aasthaengg/IBMdataset | /Python_codes/p02263/s885602482.py | 385 | 3.640625 | 4 | rp = [ele for ele in input().split()]
op = ['+','-','*']
stack = []
for ele in rp:
if ele not in op:
# ele is number
stack.append(eval(ele))
else:
# ele is operator
num_2 = stack.pop()
num_1 = stack.pop()
if ele == '+':
stack.append(num_1 + num_2)
elif ele == '-':
stack.append(num_1 - num_2)
else:
# ele == '*'
stack.append(num_1 * num_2)
print(stack[0]) |
7d7573627f9bd7b1362daa634996fe8847098398 | jeffreyegan/DataScience | /Unit2_Pandas/lambda.py | 2,896 | 4.125 | 4 | '''Create a lambda function named contains_a that takes an input word and returns True if the input contains the letter 'a'. Otherwise, return False.'''
#Write your lambda function here
contains_a = lambda word : 'a' in word
print(contains_a("banana"))
print(contains_a("apple"))
print(contains_a("cherry"))
#Write your lambda function here
long_string = lambda str : len(str)>12
print(long_string("short"))
print(long_string("photosynthesis"))
#Write your lambda function here
ends_in_a = lambda str : 'a' == str[-1]
print(ends_in_a("data"))
print(ends_in_a("aardvark"))
#Write your lambda function here
double_or_zero = lambda num : num*2 if num > 10 else 0
print(double_or_zero(15))
print(double_or_zero(5))
#Write your lambda function here
even_or_odd = lambda num : 'even' if num%2 == 0 else 'odd'
print(even_or_odd(10))
print(even_or_odd(5))
#Write your lambda function here
multiple_of_three = lambda num : 'multiple of three' if num%3 == 0 else 'not a multiple'
print(multiple_of_three(9))
print(multiple_of_three(10))
#Write your lambda function here
rate_movie = lambda rating : "I liked this movie" if rating > 8.5 else "This movie was not very good"
print(rate_movie(9.2))
print(rate_movie(7.2))
#Write your lambda function here
ones_place = lambda num : num%10
print(ones_place(123))
print(ones_place(4))
#Write your lambda function here
double_square = lambda num : 2*num**2
print(double_square(5))
print(double_square(3))
import random
#Write your lambda function here
add_random = lambda num : random.randint(1,10)+num
print(add_random(5))
print(add_random(100))
# More Lambda
mylambda = lambda string : string[0]+string[-1]
print(mylambda('This is a string'))
# should print 'Tg'
mylambda = lambda age : "Welcome to BattleCity!" if age > 12 else "You must be over 13"
print(mylambda(11))
print(mylambda(22))
## Pandas with Lambda Functions
import pandas as pd
df = pd.read_csv('employees.csv')
get_last_name = lambda name : name.split(' ')[-1]
# Add columns here
df['last_name'] = df.name.apply(lambda name : name.split(' ')[-1])
print(df)
## Applying Lambda to a Row
import pandas as pd
df = pd.read_csv('employees.csv')
total_earned = lambda row : (row.hours_worked-40)*(1.5*row.hourly_wage) + 40 * row.hourly_wage if row.hours_worked > 40 else row.hours_worked * row.hourly_wage
df['total_earned'] = df.apply(lambda row : (row.hours_worked-40)*(1.5*row.hourly_wage) + 40 * row.hourly_wage if row.hours_worked > 40 else row.hours_worked * row.hourly_wage, axis=1)
print(df.head())
# Review Pandas
import pandas as pd
orders = pd.read_csv('shoefly.csv')
orders['shoe_source'] = orders.shoe_material.apply(lambda shoe_material : 'animal' if shoe_material == 'leather' else 'vegan')
orders['salutation'] = 'Dear '+ orders.gender.apply(lambda gender : 'Mr. ' if gender == 'male' else 'Ms. ') + orders.last_name
print(orders.head(5)) |
ca98172abbc4eb2435cd53c558d0a529ea8dfeba | padymkoclab/python-utils | /utils/number.py | 9,067 | 4.3125 | 4 | """Utils for numbers."""
import math
def get_count_digits(number: int):
"""Return number of digits in a number."""
if number == 0:
return 1
number = abs(number)
if number <= 999999999999997:
return math.floor(math.log10(number)) + 1
count = 0
while number:
count += 1
number //= 10
return count
def get_digits_from_right_to_left(number):
"""Return digits of an integer excluding the sign."""
number = abs(number)
if number < 10:
return (number, )
lst = list()
while number:
number, digit = divmod(number, 10)
lst.insert(0, digit)
return tuple(lst)
def get_digits_from_left_to_right(number, lst=None):
"""Return digits of an integer excluding the sign."""
if lst is None:
lst = list()
number = abs(number)
if number < 10:
lst.append(number)
return tuple(lst)
get_digits_from_left_to_right(number // 10, lst)
lst.append(number % 10)
return tuple(lst)
def sum_digits(number):
"""Return sum digits of number."""
return sum(get_digits_from_right_to_left(number))
assert get_digits_from_right_to_left(-64517643246567536423) == (6, 4, 5, 1, 7, 6, 4, 3, 2, 4, 6, 5, 6, 7, 5, 3, 6, 4, 2, 3)
assert get_digits_from_right_to_left(-3245214012321021213) == (3, 2, 4, 5, 2, 1, 4, 0, 1, 2, 3, 2, 1, 0, 2, 1, 2, 1, 3)
assert get_digits_from_right_to_left(-40932403024902304) == (4, 0, 9, 3, 2, 4, 0, 3, 0, 2, 4, 9, 0, 2, 3, 0, 4)
assert get_digits_from_right_to_left(-1302132101032132) == (1, 3, 0, 2, 1, 3, 2, 1, 0, 1, 0, 3, 2, 1, 3, 2)
assert get_digits_from_right_to_left(-9999999999999) == (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
assert get_digits_from_right_to_left(-100000000000) == (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
assert get_digits_from_right_to_left(-123456789) == (1, 2, 3, 4, 5, 6, 7, 8, 9)
assert get_digits_from_right_to_left(-9651454) == (9, 6, 5, 1, 4, 5, 4)
assert get_digits_from_right_to_left(-1000) == (1, 0, 0, 0)
assert get_digits_from_right_to_left(-129) == (1, 2, 9)
assert get_digits_from_right_to_left(-10) == (1, 0)
assert get_digits_from_right_to_left(-9) == (9, )
assert get_digits_from_right_to_left(0) == (0, )
assert get_digits_from_right_to_left(9) == (9, )
assert get_digits_from_right_to_left(10) == (1, 0)
assert get_digits_from_right_to_left(129) == (1, 2, 9)
assert get_digits_from_right_to_left(100) == (1, 0, 0)
assert get_digits_from_right_to_left(10101) == (1, 0, 1, 0, 1)
assert get_digits_from_right_to_left(54678904) == (5, 4, 6, 7, 8, 9, 0, 4)
assert get_digits_from_right_to_left(9651454) == (9, 6, 5, 1, 4, 5, 4)
assert get_digits_from_right_to_left(123456789) == (1, 2, 3, 4, 5, 6, 7, 8, 9)
assert get_digits_from_right_to_left(2394928349) == (2, 3, 9, 4, 9, 2, 8, 3, 4, 9)
assert get_digits_from_right_to_left(100000000000000) == (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
assert get_digits_from_right_to_left(9999999999999999) == (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
assert get_digits_from_right_to_left(123012312312321312312312) == (1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 1, 2, 3, 1, 2)
assert get_digits_from_left_to_right(-64517643246567536423) == (6, 4, 5, 1, 7, 6, 4, 3, 2, 4, 6, 5, 6, 7, 5, 3, 6, 4, 2, 3)
assert get_digits_from_left_to_right(-3245214012321021213) == (3, 2, 4, 5, 2, 1, 4, 0, 1, 2, 3, 2, 1, 0, 2, 1, 2, 1, 3)
assert get_digits_from_left_to_right(-40932403024902304) == (4, 0, 9, 3, 2, 4, 0, 3, 0, 2, 4, 9, 0, 2, 3, 0, 4)
assert get_digits_from_left_to_right(-1302132101032132) == (1, 3, 0, 2, 1, 3, 2, 1, 0, 1, 0, 3, 2, 1, 3, 2)
assert get_digits_from_left_to_right(-9999999999999) == (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
assert get_digits_from_left_to_right(-100000000000) == (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
assert get_digits_from_left_to_right(-123456789) == (1, 2, 3, 4, 5, 6, 7, 8, 9)
assert get_digits_from_left_to_right(-9651454) == (9, 6, 5, 1, 4, 5, 4)
assert get_digits_from_left_to_right(-1000) == (1, 0, 0, 0)
assert get_digits_from_left_to_right(-129) == (1, 2, 9)
assert get_digits_from_left_to_right(-10) == (1, 0)
assert get_digits_from_left_to_right(-9) == (9, )
assert get_digits_from_left_to_right(0) == (0, )
assert get_digits_from_left_to_right(9) == (9, )
assert get_digits_from_left_to_right(10) == (1, 0)
assert get_digits_from_left_to_right(129) == (1, 2, 9)
assert get_digits_from_left_to_right(100) == (1, 0, 0)
assert get_digits_from_left_to_right(10101) == (1, 0, 1, 0, 1)
assert get_digits_from_left_to_right(54678904) == (5, 4, 6, 7, 8, 9, 0, 4)
assert get_digits_from_left_to_right(9651454) == (9, 6, 5, 1, 4, 5, 4)
assert get_digits_from_left_to_right(123456789) == (1, 2, 3, 4, 5, 6, 7, 8, 9)
assert get_digits_from_left_to_right(2394928349) == (2, 3, 9, 4, 9, 2, 8, 3, 4, 9)
assert get_digits_from_left_to_right(100000000000000) == (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
assert get_digits_from_left_to_right(9999999999999999) == (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
assert get_digits_from_left_to_right(123012312312321312312312) == (1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 1, 2, 3, 1, 2)
assert 0 == sum_digits(0)
assert 1 == sum_digits(1)
assert 1 == sum_digits(-1)
assert 9 == sum_digits(9)
assert 9 == sum_digits(-9)
assert 1 == sum_digits(10)
assert 1 == sum_digits(-10)
assert 1 == sum_digits(100000)
assert 1 == sum_digits(-100000)
assert 28 == sum_digits(1234567)
assert 28 == sum_digits(-1234567)
assert 28 == sum_digits(100200304056700)
assert 28 == sum_digits(-100200304056700)
assert 45 == sum_digits(-123456789)
assert 45 == sum_digits(123456789)
assert get_count_digits(-99999999999999999999) == 20
assert get_count_digits(-10000000000000000000) == 20
assert get_count_digits(-9999999999999999999) == 19
assert get_count_digits(-1000000000000000000) == 19
assert get_count_digits(-999999999999999999) == 18
assert get_count_digits(-100000000000000000) == 18
assert get_count_digits(-99999999999999999) == 17
assert get_count_digits(-10000000000000000) == 17
assert get_count_digits(-9999999999999999) == 16
assert get_count_digits(-1000000000000000) == 16
assert get_count_digits(-999999999999999) == 15
assert get_count_digits(-100000000000000) == 15
assert get_count_digits(-99999999999999) == 14
assert get_count_digits(-10000000000000) == 14
assert get_count_digits(-9999999999999) == 13
assert get_count_digits(-1000000000000) == 13
assert get_count_digits(-999999999999) == 12
assert get_count_digits(-100000000000) == 12
assert get_count_digits(-99999999999) == 11
assert get_count_digits(-10000000000) == 11
assert get_count_digits(-9999999999) == 10
assert get_count_digits(-1000000000) == 10
assert get_count_digits(-999999999) == 9
assert get_count_digits(-100000000) == 9
assert get_count_digits(-99999999) == 8
assert get_count_digits(-10000000) == 8
assert get_count_digits(-9999999) == 7
assert get_count_digits(-1000000) == 7
assert get_count_digits(-999999) == 6
assert get_count_digits(-100000) == 6
assert get_count_digits(-99999) == 5
assert get_count_digits(-10000) == 5
assert get_count_digits(-9999) == 4
assert get_count_digits(-1000) == 4
assert get_count_digits(-999) == 3
assert get_count_digits(-100) == 3
assert get_count_digits(-99) == 2
assert get_count_digits(-10) == 2
assert get_count_digits(-9) == 1
assert get_count_digits(-1) == 1
assert get_count_digits(0) == 1
assert get_count_digits(1) == 1
assert get_count_digits(9) == 1
assert get_count_digits(10) == 2
assert get_count_digits(99) == 2
assert get_count_digits(100) == 3
assert get_count_digits(999) == 3
assert get_count_digits(1000) == 4
assert get_count_digits(9999) == 4
assert get_count_digits(10000) == 5
assert get_count_digits(99999) == 5
assert get_count_digits(100000) == 6
assert get_count_digits(999999) == 6
assert get_count_digits(1000000) == 7
assert get_count_digits(9999999) == 7
assert get_count_digits(10000000) == 8
assert get_count_digits(99999999) == 8
assert get_count_digits(100000000) == 9
assert get_count_digits(999999999) == 9
assert get_count_digits(1000000000) == 10
assert get_count_digits(9999999999) == 10
assert get_count_digits(10000000000) == 11
assert get_count_digits(99999999999) == 11
assert get_count_digits(100000000000) == 12
assert get_count_digits(999999999999) == 12
assert get_count_digits(1000000000000) == 13
assert get_count_digits(9999999999999) == 13
assert get_count_digits(10000000000000) == 14
assert get_count_digits(99999999999999) == 14
assert get_count_digits(100000000000000) == 15
assert get_count_digits(999999999999999) == 15
assert get_count_digits(1000000000000000) == 16
assert get_count_digits(9999999999999999) == 16
assert get_count_digits(10000000000000000) == 17
assert get_count_digits(99999999999999999) == 17
assert get_count_digits(100000000000000000) == 18
assert get_count_digits(999999999999999999) == 18
assert get_count_digits(1000000000000000000) == 19
assert get_count_digits(9999999999999999999) == 19
assert get_count_digits(10000000000000000000) == 20
assert get_count_digits(99999999999999999999) == 20
|
0a8d9e158e118d952a535ba6bc4a2cdc37defbd3 | aish2028/labquestion | /q12.py | 235 | 3.875 | 4 | str=input("enter the sentense:")
lst=['does','do','is','are']
res=filter(lambda x:x.startswith(lst),str)
if res:
print("interogative")
else:
print("assertive")
question=input("enter the question:")
if question.endswith |
12343fc4e83a7b97baa9ad33b00d44ac4a388d6d | LazyDog1997/LazyDog-Belajar | /ifelse.py | 406 | 3.890625 | 4 | print("Latihan If Elif Else")
print(15*"-")
nilai = float(input("Masukkan Nilai :"))
if nilai >= 80:
print ("Nilai", nilai, "Adalah A")
elif 68 <= nilai < 80:
print ("Nilai", nilai, "Adalah B")
elif 55 <= nilai < 68:
print ("Nilai", nilai, "Adalah C")
elif 40 <= nilai < 55:
print ("Nilai", nilai, "Adalah D")
else:
print(nilai, "Anda Harus Mengulang Mata Kuliah Ini") |
a64ad2f57ab0bd1bced210f6b3597fcec1c6c0b4 | offbr/Python | /pybasic/pack2/func7.py | 276 | 3.671875 | 4 | '''
Created on 2016. 10. 25.
재귀함수 : 함수가 자신을 호출 - 반복처리
'''
def Countdown(n):
if n == 0:
print('처리완료')
else:
print(n, end= ' ')
Countdown(n - 1) #이게 재귀
Countdown(5)
print()
print('다음 작업') |
f84cc3a059957b556c09890da4146edc8ffcf735 | RogerMCL/PythonExercises | /Ex091.py | 683 | 3.609375 | 4 | # EXERCÍCIO 091:
from random import randint
from time import sleep
from operator import itemgetter
dic_jog = dict()
for c in range(0, 4):
dic_jog[f'Jogador {c + 1}'] = randint(1, 6)
for k, v in dic_jog.items():
print(f'{k} tirou {v} no dado!')
sleep(1)
print('\n\t', '=' * 10, 'RANKING', '=' * 10, '\n')
ranking = sorted(dic_jog.items(), key=itemgetter(1), reverse=True)
# faz uma lista e ordena de forma crescente os valores de determinado item do dict,
# nesse caso o item 1 que é a pontuação, usa-se o reverse para termos uma ordem decrescente
for i, v in enumerate(ranking):
print(f'{i + 1}º Lugar: {v[0]} que tirou {v[1]} no dado!')
|
24c62a0bcb513fe71da3bb33cb01c7822fb40f93 | liuyanhui/leetcode-py | /leetcode/total-hamming-distance/total-hamming-distance.py | 2,164 | 3.9375 | 4 | class Solution:
"""
https://leetcode.com/problems/total-hamming-distance/
477. Total Hamming Distance
Medium
"""
def totalHammingDistance(self, nums):
return self.totalHammingDistance_2(nums)
def totalHammingDistance_1(self, nums):
"""
暴力法,必然会导致超时
:param nums:
:return:
"""
ret = 0
for i in range(len(nums)):
for j in range(i, len(nums)):
ret += self.hammingDistance(nums[i], nums[j])
return ret
def hammingDistance(self, x, y):
ret = 0
xor = x ^ y
while xor > 0:
ret += xor & 1
xor >>= 1
return ret
def totalHammingDistance_2(self, nums):
"""
参考思路:
https://leetcode.com/problems/total-hamming-distance/discuss/96243/Share-my-O(n)-C%2B%2B-bitwise-solution-with-thinking-process-and-explanation
解释如下:
一般来说整数有32bit.数组中所有整数的二进制表示的第i位,非0即1.所以我们可以记录如下:
0位 M0 N0
1位 M1 N1
...
31位 M31 N31
其中Mi表示第i位是1的数字的个数,Ni表示第i位是0的数字的个数,且满足Ni+Mi=len(nums).
Mi*Ni就是第i位的Hamming distance总和,那么sum(Ni*Mi)就是所求,即sum(Ni*(len(nums)-Ni))就是所求.
注:
各个位的total Hamming distance是独立的,所以可以以位为单位分别计算后再求和
:param nums:
:return:
"""
if nums is None or len(nums) == 0:
return 0
ret = 0
for i in range(32):
x = 0
for n in nums:
x += (n >> i) & 1
ret += x * (len(nums) - x)
return ret
def main():
nums = [4, 14, 2]
ret = Solution().totalHammingDistance(nums)
print(ret)
print("----------")
nums = [i + 1000000 for i in range(10 ** 4)]
# print(len(nums))
ret = Solution().totalHammingDistance(nums)
print(ret)
print("----------")
if __name__ == "__main__":
main()
|
9ccb5f46a8dd38443d3193f4bd634d31f471fd30 | wenziyue1984/python_100_examples | /016输出日期.py | 617 | 4.0625 | 4 | # -*- coding:utf-8 -*-
__author__ = 'wenziyue'
'''
输出指定格式的日期
'''
from datetime import datetime
def print_date(date_str):
try:
date = datetime.strptime(date_str, '%Y-%m-%d')
print(date.strftime('%Y--%m--%d'))
print('{}年{}月{}日'.format(date.year, date.month, date.day))
except ValueError as e:
print(e)
if __name__=='__main__':
# date = input('请输入日期(yyyy-mm-dd):')
print_date('2000-01-01')
'''
主要练习了使用datetime模块,
字符串转datetime:datetime.strptime
datetime转字符串:datetime.strftime 注意:strftime('xxx')里不能有汉字
''' |
2d7fdd490841744f6f41618a8645284d73204807 | whitegreyblack/Spaceship | /spaceship/classes/point.py | 1,546 | 3.765625 | 4 | import math
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"{self.__class__.__name__}: ({self.x}, {self.y})"
def __iter__(self):
return iter(tuple(getattr(self, var) for var in self.__slots__))
def __add__(self, other):
try:
x, y = self.x + other.x, self.y + other.y
except AttributeError:
x, y = self.x + other[0], self.y + other[1]
finally:
return Point(x, y)
def __sub__(self, other):
try:
x, y = self.x - other.x, self.y - other.y
except:
x, y = self.x - other[0], self.y - other[1]
finally:
return Point(x, y)
def __eq__(self, other):
return (self.x, self.y) == other
def __hash__(self):
return hash((self.x, self.y))
def move(self, other):
self.x, self.y = self + other
def distance(self, other):
if isinstance(other, tuple):
other = Point(*other)
midpoint = other - self
return math.sqrt(math.pow(midpoint.x, 2) + math.pow(midpoint.y, 2))
def spaces(point, exclusive=True):
'''Returns a list of spaces in a 8 space grid with the center (pos 5)
returned if exclusive is set as false or excluded if set as true.
'''
for dy in range(-1, 2):
for dx in range(-1, 2):
if (dx, dy) == (0, 0) and exclusive:
continue
else:
yield point + Point(dx, dy) |
11563165481f331051f21fee2ec1e9e0e1a46d12 | rhenderson2/python1-class | /chapter08/hw_8-8.py | 702 | 4.25 | 4 | # homework assignment section 8-8
def make_album(artist_name, album_title):
"""Return an artist and album neatly formatted."""
album = {'name': artist_name, 'title': album_title}
return album
while True:
print("\nPlease tell me an artist's name and album title: ")
print("(enter 'q' at any time to quit)")
a_name = input("Artist's name: ")
if a_name == 'q':
break
a_title = input("Album title: ")
if a_title == 'q':
break
artist_album = make_album(a_name, a_title)
print(artist_album)
#album01 = make_album('madona', 'immaculate concpetion')
#print(album01)
#album02 = make_album('newsboys', 'step up to the microphone')
#print(album02)
|
93d91b404b260563f6acd5aec5265a7e3778241b | Regulator13/Blackjack | /Milestone_Project2.py | 5,281 | 3.828125 | 4 | '''
Blackjack Game
By Isaiah Frey
Allows the user to play a one-on-one blackjack game vs. a dealer
The player will place bets on their initial hand and then hit or stay
The dealer will then hit until it beats the player or busts
Finally the player will recieve compensation for his bets
'''
#-----------------Libraries------------------------#
import random
import time
#------------------Classes-------------------------#
class Card:
def __init__(self, rank, value, suit):
self.rank = rank
self.value = value
self.suit = suit
def __str__(self):
return f"{self.rank} of {self.suit}"
class Deck:
def __init__(self):
'''
Initialize the deck to contain 52 different cards
'''
self.deck = []
for rank in RANK:
for suit in SUIT:
self.deck.append(Card(rank, VALUE[rank], suit))
def __str__(self):
deck_str = ""
for card in self.deck:
deck_str += '\n' + card.__str__()
return deck_str
def shuffle(self):
'''
Shuffle the deck
'''
random.shuffle(self.deck)
def deal(self):
'''
Deal a single card
'''
return self.deck.pop()
class Hand:
def __init__(self):
self.cards = []
self.aces = 0
self.total = 0
def find_total(self):
for card in self.cards:
self.total += card.value
while self.total > 21 and self.aces > 0:
self.total -= 10
self.aces -= 1
return self.total
def __str__(self):
hand_str = ""
for card in self.cards:
hand_str += '\n' + card.__str__()
return hand_str
class Money:
def __init__(self):
self.money = 1000
def bet(self, bet):
print(f"You placed a bet for ${bet}.")
self.money -= bet
print(f"You have ${self.money} left.\n")
#---------------Global Variables--------------------#
RANK = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
VALUE = {'Ace': 11, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10}
SUIT = ['Spades', 'Clubs', 'Diamonds', 'Hearts']
#----------------Main-------------------------------#
account = Money()
print("Welcome to Blackjack!")
#Game loop
while True:
#Print a few empty lines to seperate games
print("\n\n\n")
#Initialize the player's and dealer's hands and player's account
player_hand = Hand()
dealer_hand = Hand()
bust = False
#To begin the game, make a deck and shuffle it
deck = Deck()
deck.shuffle()
#Ask the player for a bet
while True:
try:
bet = int(input("Please place a bet: "))
except ValueError:
print("Please input a value")
continue
if bet > account.money:
print(f"You don't have ${bet}! You have ${account.money} remaining.")
continue
else:
account.bet(bet)
break
#Deal the player two cards
for i in range(2):
player_hand.cards.append(deck.deal())
print(f"Your hand is: {player_hand}\n")
#Deal two cards to the dealer, showing the player the first one
dealer_hand.cards.append(deck.deal())
print(f"The dealer's face up card is: {dealer_hand}\n")
dealer_hand.cards.append(deck.deal())
#Ask the player if they would like another card
while True:
hit = input("Would you like another card? Enter y for yes or n for no: ")
if hit.lower() == 'y':
player_hand.cards.append(deck.deal())
print(f"\nYour hand is: {player_hand}")
#Count the number of aces in the hand
player_hand.aces = 0
#Add up the aces in the player's hand
for card in player_hand.cards:
if card.rank == 'Ace':
player_hand.aces += 1
#Check for bust
if player_hand.find_total() > 21:
print("You busted!")
bust = True
break
else:
break
#If the player busted, end the round
if bust:
play_again = input("Would you like to play again? Enter a y for yes or n for no: ")
if play_again.lower() == 'y':
continue
else:
break
#Otherwise give the dealer a chance to beat the player
print()
print("Dealer's turn.")
print(f"The dealer's hand is {dealer_hand}")
player_total = player_hand.find_total()
while (dealer_hand.find_total() < player_total or dealer_hand.find_total() < 17) and not bust:
#Wait for a short while before playing to give the player a chance to see what's happening
time.sleep(2)
#Print a blank line
print()
#Deal the dealer a card
dealer_hand.cards.append(deck.deal())
print(f"The dealer's hand is {dealer_hand}")
#Add up the aces
for card in dealer_hand.cards:
if card.rank == 'Ace':
dealer_hand.aces += 1
#Check for busts
if dealer_hand.find_total() > 21:
print("Dealer busted!\n")
bust = True
break
#If the computer bust double the player's bet
if bust:
print(f"Congratulations you won ${bet*2}!")
account.money += bet*2
print(f"You now have ${account.money} in your account.")
#Otherwise the computer won
else:
print(f"The dealer won. You now have ${account.money} in your account.")
#Ask the player if they would like to play again
play_again = input("Would you like to play again? Enter a y for yes or n for no: ")
if play_again.lower() == 'y':
continue
else:
break
|
a18dfdafd706cb68d82d45b4529e6335eaeb486d | isennkubilay/pythontricks | /tr1.py | 193 | 4 | 4 | #Write a Python program to calculate number of days between two dates.
from datetime import date
f_date = date(2019, 5, 29)
l_date = date(2019, 6, 1)
delta = l_date - f_date
print(delta.days)
|
d9930672ea07b91ed61695a45cb0478470532d7f | LundAtGH/Reva_Proj_0_Bank_API | /daos/bank_acct_dao.py | 873 | 3.546875 | 4 | # Data Access Object (Bank Account)
from abc import abstractmethod, ABC
class BankAcctDAO(ABC):
@abstractmethod
def create_bank_acct(self, bank_acct):
pass
@abstractmethod
def get_bank_acct(self, bank_acct_id):
pass
@abstractmethod
def all_bank_accts(self):
pass
@abstractmethod
def some_bank_accts(self, client_id, conditions):
pass
@abstractmethod
def update_bank_acct(self, new):
pass
@abstractmethod
def delete_bank_acct(self, bank_acct_id):
pass
@abstractmethod
def deposit_funds(self, client_id, bank_acct_id, amount):
pass
@abstractmethod
def withdraw_funds(self, client_id, bank_acct_id, amount):
pass
@abstractmethod
def transfer_funds(self, client_id, id_of_BA_taken_from, id_of_BA_depos_into, amount):
pass
|
d24d2dd097d3be88b22f0b337ba3b5a162e29622 | roottor38/Algorithm | /programmers/python/최대공약수와회소공배수/solution.py | 611 | 3.609375 | 4 | # def solution(n, m):
# answer = []
# for i in range(n, 0, -1):
# if m%i == 0 and n%i == 0:
# answer.append(i)
# break
# a= (n*m)//answer[0]
# answer.append(a)
# return answer
def solution(n, m):
answer = []
test = []
for i in range(n, 0, -1):
if m%i == 0 and n%i == 0:
answer.append(i)
break
for i in range(1 , m+1):
test.append(i*n)
for i in test:
if i%m == 0:
answer.append(i)
break
print(test)
return answer
print(solution(18, 12)) |
70db5f481e6d4684426e1d6ab4c55e01e1374a0e | aleksandromelo/Exercicios | /ex062.py | 273 | 3.8125 | 4 | n = int(input('Quantos termos você quer ver? '))
c = 2
anterior = 0
proximo = 1
print(f'{anterior} -> {proximo} ->', end='')
while c < n:
atual = anterior + proximo
print(f'{atual} -> ', end='')
anterior = proximo
proximo = atual
c += 1
print(' FIM') |
1ddc59d0b368a2f50097560e20fcb55da15ab06f | federicodc05/Calculator | /__dependencies__/__graphs__/custom_graph.py | 940 | 3.859375 | 4 | import numpy as np
import matplotlib.pyplot as plt
from tkinter import *
def poly_graph(poly, x_range):
x = np.array(x_range)
y = eval(poly)
plt.plot(x, y)
plt.title("y="+poly)
plt.grid(True)
plt.axhline(linewidth=2, color='gray')
plt.axvline(linewidth=2, color='gray')
plt.show()
def polynomial():
global e, e1, cus_screen
e = e1.get()
cus_screen.destroy()
poly_graph(e, range(-50, 50))
def cus_screen():
global cus_screen, e, e1
cus_screen = Tk()
l1 = Label(cus_screen, text="Insert polynomial function P(x)")
l2 = Label(cus_screen, text="power expressed as a**b, \n product as a*b, \n division as a/b", font=("Calibri", 10))
e = StringVar()
e1 = Entry(cus_screen, textvariable=e)
ok = Button(cus_screen, text="Ok", command=polynomial)
l1.pack()
l2.pack()
e1.pack()
ok.pack()
cus_screen.mainloop() |
0c84219a48617e8a862ae4eeff99678b70a8fdf8 | rafaelperazzo/programacao-web | /moodledata/vpl_data/8/usersdata/88/3801/submittedfiles/imc.py | 354 | 3.53125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
peso= input('informe seu peso em kilos: ')
alt= input('informe sua altura em metros: ')
IMC=(peso)/(alt)**2
if IMC<20:
print ('ABAIXO')
if 20<=IMC<=25:
print ('NORMAL')
if 25<IMC<=30:
print ('SOBREPESO')
if 30<IMC<=40:
print ('OBESIDADE')
if IMC>40:
print ('OBESIDADE GRAVE')
|
0de44f6636e43693b52a876fa6f527be6b8e24d5 | SeattleTestbed/clearinghouse | /common/util/decorators.py | 8,846 | 3.65625 | 4 | """
<Program>
decorators.py
<Started>
6 July 2009
<Author>
Justin Samuel
<Purpose>
These define the decorators used in clearinghouse code. Decorators are something
we try to avoid using, so they should only be used if absolutely necessary.
Currently we only use them for logging function calls (such as the public
api functions).
The simple_decorator approach here is borrowed from:
http://wiki.python.org/moin/PythonDecoratorLibrary
The general idea is that we have one simple_decorator that does magic python
stuff (_simple_decorator), and we write our actual decorators that are more
sane and are themselves decorated with the _simple_decorator.
"""
import datetime
from clearinghouse.common.util import log
from django.http import HttpRequest
def _simple_decorator(decorator):
"""
This is not for use outside of this module.
This decorator can be used to turn simple functions into well-behaved
decorators, so long as the decorators are fairly simple. If a decorator
expects a function and returns a function (no descriptors), and if it doesn't
modify function attributes or docstring, then it is eligible to use this.
Simply apply @simple_decorator to your decorator and it will automatically
preserve the docstring and function attributes of functions to which it is
applied.
"""
def new_decorator(f):
g = decorator(f)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
g.__dict__.update(f.__dict__)
return g
# Now a few lines needed to make simple_decorator itself
# be a well-behaved decorator.
new_decorator.__name__ = decorator.__name__
new_decorator.__doc__ = decorator.__doc__
new_decorator.__dict__.update(decorator.__dict__)
return new_decorator
def _get_timedelta_str(starttime):
return str(datetime.datetime.now() - starttime)
@_simple_decorator
def log_function_call(func):
"""
<Purpose>
Logs when the function is called, along with the arguments, and logs when
the function returns, along with the return value. Will also log any
exception that is raised.
Be careful when using this to log functions that take sensitive values
(e.g. passwords) as arguments or that return sensitive values (e.g.
private keys).
"""
# The name "do_logging_func_call" is never seen anywhere but here.
def do_logging_func_call(*args, **kwargs):
_log_call_info(func, args, kwargs)
starttime = datetime.datetime.now()
try:
result = func(*args, **kwargs)
log.debug('Returning from %s (module %s) (time %s): %s' % (func.__name__, func.__module__, _get_timedelta_str(starttime), str(result)))
return result
except Exception, e:
log.debug('Exception from %s (module %s): %s %s' % (func.__name__, func.__module__, type(e), str(e)))
raise
return do_logging_func_call
@_simple_decorator
def log_function_call_without_return(func):
"""
<Purpose>
Logs when the function is called, along with the arguments, and logs when
the function returns, but doesn't log the return value. Will also log any
exception that is raised.
Be careful when using this to log functions that take sensitive values
(e.g. passwords) as arguments.
"""
# The name "do_logging_func_call" is never seen anywhere but here.
def do_logging_func_call(*args, **kwargs):
_log_call_info(func, args, kwargs)
starttime = datetime.datetime.now()
try:
result = func(*args, **kwargs)
log.debug('Returning from %s (module %s) (time %s): [Not logging return value]' % (func.__name__, func.__module__, _get_timedelta_str(starttime)))
return result
except Exception, e:
log.debug('Exception from %s (module %s): %s %s' % (func.__name__, func.__module__, type(e), str(e)))
raise
return do_logging_func_call
@_simple_decorator
def log_function_call_without_arguments(func):
"""
<Purpose>
Logs when the function is called, without the arguments, and logs when
the function returns, including the return value. Will also log any
exception that is raised.
Be careful when using this to log functions that return sensitive values
(e.g. private keys).
"""
# The name "do_logging_func_call" is never seen anywhere but here.
def do_logging_func_call(*args, **kwargs):
log.debug('Calling: %s (module %s), args: [Not logging], kwargs: [Not logging].' %
(func.__name__, func.__module__))
starttime = datetime.datetime.now()
try:
result = func(*args, **kwargs)
log.debug('Returning from %s (module %s) (time %s): %s' % (func.__name__, func.__module__, _get_timedelta_str(starttime), str(result)))
return result
except Exception, e:
log.debug('Exception from %s (module %s): %s %s' % (func.__name__, func.__module__, type(e), str(e)))
raise
return do_logging_func_call
@_simple_decorator
def log_function_call_and_only_first_argument(func):
"""
<Purpose>
Logs when the function is called, with only the first, and logs when
the function returns, including the return value. Will also log any
exception that is raised.
Be careful when using this to log functions that return sensitive values
(e.g. private keys).
The reason this decorator exists is that there are a handful of functions
that take sensitive data as arguments (like passwords) but they are
not the first argument, and logging the first argument could be useful.
This could probably be accomplished by making a decorator that itself
took arguments about which arguments to log, but that crosses well over
the line of maintainability by people who didn't write the initial code.
"""
# The name "do_logging_func_call" is never seen anywhere but here.
def do_logging_func_call(*args, **kwargs):
log.debug('Calling: %s (module %s), 1st arg: %s, other args: [Not logging].' %
(func.__name__, func.__module__, str(_get_cleaned_args(args)[0])))
starttime = datetime.datetime.now()
try:
result = func(*args, **kwargs)
log.debug('Returning from %s (module %s) (time %s): %s' % (func.__name__, func.__module__, _get_timedelta_str(starttime), str(result)))
return result
except Exception, e:
log.debug('Exception from %s (module %s): %s %s' % (func.__name__, func.__module__, type(e), str(e)))
raise
return do_logging_func_call
@_simple_decorator
def log_function_call_without_first_argument(func):
"""
<Purpose>
Logs the function called without the first argument (unless it's a kwarg),
and logs when the function returns including the return value. Will also log
any exception that is raised.
Be careful when using this to log functions that return sensitive values
(e.g. private keys).
The reason this decorator exists is that there are functions that take
a sensitive value (such as the backend authcode) as the first argument,
and we don't want that ending up in the logs.
"""
# The name "do_logging_func_call" is never seen anywhere but here.
def do_logging_func_call(*args, **kwargs):
log.debug('Calling: %s (module %s), 1st arg: [Not logging], other args: %s, kwargs: %s.' %
(func.__name__, func.__module__, str(_get_cleaned_args(args)[1:]), str(_get_cleaned_args(kwargs))))
starttime = datetime.datetime.now()
try:
result = func(*args, **kwargs)
log.debug('Returning from %s (module %s) (time %s): %s' % (func.__name__, func.__module__, _get_timedelta_str(starttime), str(result)))
return result
except Exception, e:
log.debug('Exception from %s (module %s): %s %s' % (func.__name__, func.__module__, type(e), str(e)))
raise
return do_logging_func_call
def _log_call_info(func, args, kwargs):
# This is a separate function because I didn't want to repeat it the code in
# both log_function_call and log_function_call_without_return.
# TODO: clean up this line
log.debug('Calling: %s (module %s), args: %s, kwargs: %s.' %
(func.__name__, func.__module__, str(_get_cleaned_args(args)), str(_get_cleaned_args(kwargs))))
def _get_cleaned_args(args):
cleanedargslist = []
for item in args:
if isinstance(item, HttpRequest):
cleanedargslist.append("<HttpRequest>")
else:
cleanedargslist.append(item)
return tuple(cleanedargslist)
def _get_cleaned_kwargs(kwargs):
cleanedkwargs = {}
for key in kwargs:
if isinstance(kwargs[key], HttpRequest):
cleanedkwargs[key] = "<HttpRequest>"
elif key == "password":
cleanedkwargs[key] = "***"
else:
cleanedkwargs[key] = kwargs[key]
return cleanedkwargs
|
0d712a00e7b061b45cc7b9f9a0307b0e01568beb | jikka/pythong | /div2.py | 129 | 3.703125 | 4 | a=int(input("Enter a number "))
d=[]
e=0
while(a>0):
print(a)
d.insert(e,a)
e=e+1
a=a/2
print(list(reversed(d)))
|
f5e4df78f54156f8dc32449b46fe14bb71ee0023 | SKREFI/p | /sandbox/python/twitter.py | 2,074 | 4.09375 | 4 | def combinations(list_get_comb, length_combination):
""" Generator to get all the combinations of some length of the elements of a list.
:param list_get_comb: (list) List from which it is wanted to get the combination of its elements.
:param length_combination: (int) Length of the combinations of the elements of list_get_comb.
:return:
* :generator: Generator with the combinations of this list.
"""
# Generator to get the combinations of the indices of the list
def get_indices_combinations(sub_list_indices, max_index):
""" Generator that returns the combinations of the indices
:param sub_list_indices: (list) Sub-list from which to generate ALL the possible combinations.
:param max_index: (int) Maximum index.
:return:
"""
if len(sub_list_indices) == 1: # Last index of the list of indices
for index in range(sub_list_indices[0], max_index + 1):
yield [index]
elif all([sub_list_indices[-i - 1] == max_index - i for i in
range(len(sub_list_indices))]): # The current sublist has reached the end
yield sub_list_indices
else:
for comb in get_indices_combinations(sub_list_indices[1:],
max_index): # Get all the possible combinations of the sublist sub_list_indices[1:]
yield [sub_list_indices[0]] + comb
# Advance one position and check all possible combinations
new_sub_list = []
new_sub_list.extend([sub_list_indices[0] + i + 1 for i in range(len(sub_list_indices))])
for new_comb in get_indices_combinations(new_sub_list, max_index):
yield new_comb # Return all the possible combinations of the new list
# Start the algorithm:
sub_list_indices = list(range(length_combination))
for list_indices in get_indices_combinations(sub_list_indices, len(list_get_comb) - 1):
yield [list_get_comb[i] for i in list_indices]
comb = combinations([]) |
75002e26b132a696e99a7aa0f718267236564c4c | fiqhyb/Trajectory-Assignment | /traject.py | 924 | 3.671875 | 4 | import matplotlib.pyplot as plt
import random
if __name__ == '__main__':
#Coordinates and Equations
numx = list(range(0,26))#range is 26 for display purpose
numy = [((x**2)-(3*x)+4) for x in numx]
ranx = list(random.randint(0,25) for p in range(4000))
rany = list(random.randint(0,600) for q in range(4000))
poin = []
#create point and count as one below the curve
for i in range(4000):
if rany[i] <= numy[ranx[i]]:
poin.append(1)
cal = 25*600*(sum(poin)/4000)#Calculate the area
#sets the graph's axis
plt.axis([-1,26,-30,630])#given offsides to axis for display purpose
#Title and Axis' name
plt.title("Area Calculator\nArea ={0}".format(cal))
plt.xlabel("X-Coordinate")
plt.ylabel("Y-Coordinate")
#Draws and displays graph
plt.scatter(ranx,rany,c=rany)
plt.scatter(numx,numy,c="red")
plt.show() |
443192c3d7ae69182c83c19b171fd1e4d2c5ec7d | namhee33/doublylinkedlist | /doublyLL.py | 2,478 | 4.03125 | 4 | class Node(object):
def __init__(self, value=0, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
class DoublyLinkiedList(object):
def __init__(self, first=None, last=None):
self.first = first
self.last = last
def traverse_forward(self):
node = self.first
while node is not None:
print node.value,
node = node.next
print
return self
def traverse_backward(self):
node = self.last
while node is not None:
print node.value,
node = node.prev
print
return self
def insertAfter(self, node, newNode):
newNode.next = node.next
newNode.prev = node
if node.next is None:
self.last = newNode
else:
node.next.prev = newNode
node.next = newNode
def insertBefore(self, node, newNode):
newNode.prev = node.prev
newNode.next = node
if node.prev is None:
self.first = newNode
else:
node.prev.next = newNode
node.prev = newNode
return self
def insertBeginning(self, newNode):
if self.first is None:
self.first = newNode
print 'set first: (beginning)', newNode.value
self.last = newNode
newNode.prev = None
newNode.next = None
else:
self.insertBefore(first, newNode)
return self
def insertEnd(self, newNode):
if self.last is None:
self.insertBeginning(newNode)
else:
self.insertAfter(self.last, newNode)
return self
def insertAfter_with_value(self, value, newNode):
node = self.find(value)
if node is not None:
self.insertAfter(node, newNode)
def insertBefore_with_value(self, value, newNode):
node = self.find(value)
if node is not None:
self.insertBefore(node, newNode)
def find(self, value):
node = self.first
while node is not None:
if node.value == value:
return node
node = node.next
print 'can\'t find it!'
return
def delete_node(self, node):
if node.prev is None:
self.first = node.next
else:
node.prev.next = node.next
if node.next is None:
self.last = node.prev
else:
node.next.prev = node.prev
def remove(self, value):
node = self.find(value)
if node is not None:
self.delete_node(node)
list1 = DoublyLinkiedList()
node1 = Node(10)
node2 = Node(20)
node3 = Node(30)
list1.insertEnd(node1).insertEnd(node2).insertEnd(node3)
list1.traverse_forward()
list1.remove(10)
list1.traverse_forward()
node4 = Node(25)
list1.insertAfter_with_value(20, node4)
list1.traverse_forward()
node5 = Node(35)
list1.insertBefore_with_value(30, node5)
list1.traverse_forward()
|
7fc5942a184af626ac6518393b16b6fb2e92c443 | jpang023/MH8811-G1901960C | /06/H1.py | 248 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 18 20:11:07 2019
@author: JIAMPAN
"""
import mod1
n=input("What is the length of your password:")
try:
num = int(n)
print(mod1.genPassword(num))
except:
print("Please type a number")
|
22290b7f3d3cbd1082c2fee755f7de4ee4ccf8be | mocmeo/algorithms | /find-chalk-replacer.py | 203 | 3.578125 | 4 | def chalkReplacer(chalk, k):
modulo = k % sum(chalk)
for i in range(len(chalk)):
modulo -= chalk[i]
if modulo < 0:
return i
print(chalkReplacer([5,1,5], 22))
print(chalkReplacer([3,4,1,2], 25)) |
c25b6619c9d05e567bfa5a3cea82ad56b155b267 | simonfqy/SimonfqyGitHub | /lintcode/medium/902_Kth_smallest_element_in_a_bst.py | 5,354 | 3.6875 | 4 | """
https://www.lintcode.com/problem/kth-smallest-element-in-a-bst/description
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# My own solution, using inorder traversal template in jiuzhang.com.
class Solution:
"""
@param root: the given BST
@param k: the given k
@return: the kth smallest element in BST
"""
def kthSmallest(self, root, k):
# write your code here
if root is None or k <= 0:
return None
dummy = TreeNode(0)
dummy.right = root
stack = [dummy]
counter = 0
while stack:
node = stack.pop()
if node.right:
node = node.right
while node:
stack.append(node)
node = node.left
if stack:
counter += 1
if counter == k:
return stack[-1].val
return None
# Using the inorder traversal from stackoverflow.
class Solution:
"""
@param root: the given BST
@param k: the given k
@return: the kth smallest element in BST
"""
def kthSmallest(self, root, k):
# write your code here
if root is None or k <= 0:
return None
node = root
stack = []
counter = 0
while node or stack:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
counter += 1
if counter == k:
return node.val
node = node.right
return None
# Using the Java example from Jiuzhang.com. Divide-and-conquer, similar to quickSelect algorithm. Performs well for
# repeated reads.
class Solution:
"""
@param root: the given BST
@param k: the given k
@return: the kth smallest element in BST
"""
def kthSmallest(self, root, k):
# write your code here
if root is None or k <= 0:
return None
subtree_element_count = dict()
self.get_element_counts(root, subtree_element_count)
return self.get_kth_smallest(root, k, subtree_element_count)
def get_element_counts(self, root, subtree_element_count):
if root is None:
return 0
left_count = self.get_element_counts(root.left, subtree_element_count)
right_count = self.get_element_counts(root.right, subtree_element_count)
total_count = left_count + right_count + 1
subtree_element_count[root] = total_count
return total_count
def get_kth_smallest(self, root, k, subtree_element_count):
if k <= 0 or k > subtree_element_count[root]:
return None
if root.left:
left_count = subtree_element_count[root.left]
else:
left_count = 0
if left_count >= k:
return self.get_kth_smallest(root.left, k, subtree_element_count)
if k == left_count + 1:
return root.val
# k > left_count + 1
return self.get_kth_smallest(root.right, k - left_count - 1, subtree_element_count)
# My own recursive solution based on the solution provided in jiuzhang.com. Uses a global dict to store the subtree sizes.
class Solution:
node_to_subtree_size = dict()
"""
@param root: the given BST
@param k: the given k
@return: the kth smallest element in BST
"""
def kthSmallest(self, root, k):
# write your code here
if not root:
return None
left_node_count = self.get_node_count(root.left)
if left_node_count >= k:
return self.kthSmallest(root.left, k)
if left_node_count == k - 1:
return root.val
return self.kthSmallest(root.right, k - left_node_count - 1)
def get_node_count(self, root):
if not root:
return 0
if root in self.node_to_subtree_size:
return self.node_to_subtree_size[root]
left_count = self.get_node_count(root.left)
right_count = self.get_node_count(root.right)
total_count = left_count + right_count + 1
self.node_to_subtree_size[root] = total_count
return total_count
# A solution from jiuzhang.com. Similar to the binary tree iterator:
# https://github.com/simonfqy/SimonfqyGitHub/blob/0123e427d382c53293720f3c1c907ba71e66640f/lintcode/easy/67_binary_tree_inorder_traversal.py#L81
# https://github.com/simonfqy/SimonfqyGitHub/blob/97254da6f5cf7340daef850f2f196e95529a677e/lintcode/hard/86_binary_search_tree_iterator.py#L146
class Solution:
"""
@param root: the given BST
@param k: the given k
@return: the kth smallest element in BST
"""
def kthSmallest(self, root, k):
# use binary tree iterator
dummy = TreeNode(0)
dummy.right = root
stack = [dummy]
for _ in range(k):
node = stack.pop()
if node.right:
right_node = node.right
while right_node:
stack.append(right_node)
right_node = right_node.left
if not stack:
return None
return stack[-1].val
|
0389017af033951b98725099cb227bd72ca80625 | AlexandraSem/Python | /Python_week2.1/Zadanie2.py | 858 | 4.3125 | 4 | #1.Запросить у пользователя зарплату.Если зарплата от меньше 100, налог - 3.Если зарплата от 100 до 600, налог - 10 .
# Если зарплата от 600 до 2000, налог - 18.Если зарпата более 2000, налог - 22.Вывести'чистую зарплату', налог, и 'глязную зарплату'
zarplata = int(input("Введите зарплату: "))
if zarplata < 100:
nalog = 0.3
elif zarplata > 100 and zarplata < 600:
nalog = 0.10
elif zarplata > 600 and zarplata < 2000:
nalog = 0.18
elif zarplata > 2000 :
nalog = 0.22
dirtyZarplata = int(zarplata*nalog)
print("Ваша 'чистая зарплата': ",zarplata,"\nНалог: ",nalog,"\nВаша 'грязная зарплата': ",dirtyZarplata)
|
05a6d23d6cb10bdfe3a9f277b20f4bd307ac4e93 | Mubelotix/tetris_nsi | /square.py | 2,410 | 4.125 | 4 | class Square:
"""
A class representing a square.
"""
color_number = 8
x = 0
y = 0
def __init__(self, color_number, x, y):
"""
Coords 0;0 is the square to the top left.
Square colors:
0 => red,
1 => blue,
2 => green,
3 => yellow,
4 => cyan,
5 => purple,
6 => orange,
7 => raimbow,
8 => empty
"""
self.color_number = color_number
self.x = x
self.y = y
def __repr__(self):
return "(" + str(self.color_number) + ", " + str(self.x) + ", " + str(self.y) + ")"
def display(self, window, textures):
"""
Display the square.
"""
if self.color_number < 8 and self.color_number >= 0:
window.blit(textures[self.color_number], (50+self.x*50, self.y*50))
def get_color(self):
return self.color_number
def set_color(self, color):
self.color_number = color
def can_move(self, grid, direction):
"""
Return true if the square can move in a direction.
Direction:
0 => No movement,
1 => Down,
2 => Left,
_ => Right
"""
if direction == 0:
if self.x >= 0 and self.x <= 9 and self.y >= 0 and self.y <= 19:
if grid[self.x][self.y].get_color() == 8:
return True
elif direction == 1:
if self.x >= 0 and self.x <= 9 and self.y >= 0 and self.y < 19:
if grid[self.x][self.y + 1].get_color() == 8:
return True
elif direction == 2:
if self.x > 0 and self.x <= 9 and self.y >= 0 and self.y <= 19:
if grid[self.x - 1][self.y].get_color() == 8:
return True
else:
if self.x >= 0 and self.x < 9 and self.y >= 0 and self.y <= 19:
if grid[self.x + 1][self.y].get_color() == 8:
return True
return False
def move(self, direction):
if direction == 1:
self.y += 1
elif direction == 2:
self.x -= 1
else:
self.x += 1
def put_on_grid(self, grid):
grid[self.x][self.y] = self
return grid
|
785c5b062fbd8592d9855f99c5dfce764cef5d8a | linseycurrie/GuessMyFavouriteColour | /precourse_recap.py | 186 | 3.953125 | 4 | colour = "Blue"
userInput = input("Guess my favourite colour : ")
if userInput == colour:
print("Well Done! You got it right!")
else:
print("Opps, sorry it's not " + userInput) |
aa6992a8afabacc35eccf9feff4634ceb263bac5 | jonzarecki/textual-mqs | /ResearchNLP/util_files/pandas_util.py | 9,568 | 3.796875 | 4 | import numpy as np
import pandas as pd # data analysis lib for python
from pandas import DataFrame
def shuffle_df_rows(df):
# type: (pd.DataFrame) -> pd.DataFrame
"""
returns a new df with $df rows shuffled
:param df: the original df
:return: shuffled $df
"""
return df.iloc[np.random.permutation(len(df))].reset_index(drop=True)
def get_all_positive_sentences(df, text_col, tag_col, pos_tags):
# type: (pd.DataFrame, str, str, list) -> list
"""
puts all positive sentences in df in a list
:param df: input DataFrame
:param text_col: the name of the column that contains the text
:param tag_col: the name of the column that contains the tag
:param pos_tags: a list of tags we consider as positive
:return: a list, that contains all 'positive' sentences in $df
"""
all_positive_df = all_positive_rows_df(df, tag_col, pos_tags)
all_positive_sentences = all_positive_df[text_col].tolist()
return all_positive_sentences
def append_rows_to_dataframe(df, text_col, new_sents):
# type: (pd.DataFrame, str, list) -> pd.DataFrame
"""
appends $new_sents as new rows in $df
:param df: input DataFrame
:param text_col: the name of the column that contains the text
:param new_sents: list of new sentences we want to add to the dataframe
:return: $df appended with new_sents as the bottom rows (doesn't change df)
"""
new_sent_df = copy_dataframe_structure(df)
new_sent_df[text_col] = new_sents # fill the text column with the new sentences
return df.append(new_sent_df, ignore_index=True)
def copy_dataframe_structure(df):
# type: (pd.DataFrame) -> pd.DataFrame
"""
copies the df column to a new df with no data in it
:param df: the original df (pandas'es DataFrame) from which we want to extract the structure
:return: an empty df, with the same structure as $df
"""
df_copy = pd.DataFrame(data=None, columns=df.columns, index=None)
return df_copy
def get_tag_count(df, tag_col, tag_vals):
# type: (pd.DataFrame, str, list) -> int
"""
returns the number of accuracies of the values in $tag_vals (which resides in $tag_column) in $df
:param df: contains the data
:param tag_col: the name of the column in which the tag is
:param tag_vals: str list, contains the tag values we want to count
:rtype: int
"""
return len(all_positive_rows_df(df, tag_col, tag_vals))
def get_cell_val(df, row_index, column_name):
# type: (pd.DataFrame, int, str) -> object
"""
:param df: contains the table data
:param row_index: the row index of the cell
:param column_name: the column name of the cell
:return: the cell value in df[row_index][column_name], type depends on content
"""
assert 0 <= row_index <= len(df.index), "get_cell_val: row index out of range"
return df.loc[row_index].get(column_name)
def set_cell_val(df, row_index, column_name, new_val):
"""
sets a given cell in the DataFrame with new_val, adds the row if it doesn't exist
:param new_val: the new value to put in the cell
:type df: DataFrame
:param row_index: the row index of the cell
:type row_index: int
:param column_name: the column name of the cell
:type column_name: str
:return: None
"""
assert 0 <= row_index <= len(df.index), "set_cell_val: row index out of range"
df.at[row_index, column_name] = new_val
def all_positive_rows_df(df, tag_col, pos_tags):
# type: (pd.DataFrame, str, list) -> pd.DataFrame
"""
:param df: pandas read_csv file (DataFrame), lets the user choose it's parameters
:param tag_col: the column in $in_csv that contains the tag (string)
:param pos_tags: list of Strings, each a valid positive tag
:return: a new df with all the positively tagged rows
"""
assert len(pos_tags) != 0, "should have possible tags in pos_tags"
return df[df[tag_col].astype(type(pos_tags[0])).isin(pos_tags)].sort_index().reset_index(drop=True)
def imbalance_dataset(df, tag_col, pos_percent, pos_tags, neg_tags, shuffle=False, return_rest=False):
# type: (pd.DataFrame, str, float, list, list, bool, bool) -> pd.DataFrame
"""
builds a new data set from $in_csv,
containing $pos_percent examples with 1 tag, and 1-$positive_percent with 0 tag
:param df: pandas read_csv file (DataFrame), lets the user choose it's parameters
:param tag_col: the column in $in_csv that contains the tag (string)
:param pos_percent: 0<=x<=1, percent of positive examples in the output dataset (real)
:param pos_tags: list of Strings, each a valid positive tag
:param neg_tags: list of Strings, each a valid negative tag
:return: new_df with the wanted percent of positive examples
"""
assert 0.0 <= pos_percent <= 1.0, "imbalanced_dataset: invalid $pos_percent parameter"
df_row_count = len(df)
# split into positive df and negative df
positive_df = all_positive_rows_df(df, tag_col, pos_tags)
negative_df = all_positive_rows_df(df, tag_col, neg_tags)
# determines how many positive and negatives examples to keep to maintain the wanted distribution
# (partition_count / partition_%) = total number of examples,
# (examples_num) - partition_count = number of other class examples
if df_row_count * pos_percent < len(positive_df):
neg_count = len(negative_df)
pos_count = (pos_percent / (1-pos_percent)) * neg_count
else:
pos_count = len(positive_df)
neg_count = ((1-pos_percent) / pos_percent) * pos_count
# merge the wanted amount of positive and negative examples while keeping example order
imbalanced_df = pd.concat([negative_df[:int(neg_count)], positive_df[:int(pos_count)]]).sort_index().reset_index(drop=True)
rest_of_data_df = pd.concat([negative_df[int(neg_count):], positive_df[int(pos_count):]]).sort_index().reset_index(drop=True)
if shuffle:
imbalanced_df = shuffle_df_rows(imbalanced_df)
rest_of_data_df = shuffle_df_rows(rest_of_data_df)
if return_rest:
return imbalanced_df, rest_of_data_df
else:
return imbalanced_df
def shrink_dataset(df, percent, shuffle=False):
# type: (pd.DataFrame, float, bool) -> pd.DataFrame
"""
Shrinks the given dataset to a fraction of its original size
:param df: contains the data
:param percent: the % of rows we want to leave ( real)
:param shuffle: decides if to shuffle the rows beforehand
:return: a new DataFrame obj, with only $percent of the rows of $df
"""
if shuffle:
df = shuffle_df_rows(df)
shrinked_df = DataFrame(data=df[:int(len(df.index) * percent)], columns=df.columns, copy=True)
return shrinked_df
def extract_row_from_df(df, idx):
# type: (pd.DataFrame, int) -> pd.DataFrame
"""
Extracts the i'th row and puts it in a new DataFrame
:param df: contains the data
:param idx: the index of the row we want to extract
:return: a new DataFrame obj, with only the idx's row from $df
"""
new_df = copy_dataframe_structure(df) # will contain the chosen rows for the new
new_df.loc[0] = df.loc[idx] # copy row
return new_df
def split_dataset(df, percent):
# type: (pd.DataFrme, float) -> (DataFrame, DataFrame)
"""
splits $df into 2 DataFrames, each contain a split of $df's data
:param df: the original df we want to split
:param percent: the % of $df we want in the first split
:return: 2 DataFrames, each contains a split of $df
"""
first_df_len = int(len(df) * percent)
first_df = DataFrame(data=df[:first_df_len], columns=df.columns, copy=True).reset_index(drop=True)
second_df = DataFrame(data=df[first_df_len:], columns=df.columns, copy=True).reset_index(drop=True)
return first_df, second_df
def save_lists_as_csv(header_list, data_lists, file_path):
# type: (list, list, basestring) -> None
"""
save lists as csv and to the dropbox folder
:param file_path: the output file path
:param header_list: list of strings, each contains the header for the corresponding column
:param data_lists: list of lists, each contains the data for the column
:return: None
"""
assert len(header_list) == len(data_lists), "save_lists_as_csv: lists lens not equal"
# put headers in the start of each column
column_lists = []
for i in range(len(data_lists)):
column_lists.append([header_list[i]] + data_lists[i])
column_lists_lens = map(len, column_lists)
columns_lens_list = zip(column_lists, column_lists_lens)
with open(file_path, 'w') as f:
for i in range(max(column_lists_lens)):
row = ""
for col, col_len in columns_lens_list:
if i < col_len:
row += str(col[i])
row += "\t"
row = row[:-1]
f.write(row + '\n')
def get_pos_neg_balance(df, tag_col, pos_tags):
# type: (pd.DataFrame, str, list) -> float
"""
calculates the percent of $pos_tags in $df
:param df: contains the data
:param tag_col: the name of the column in which the tag is
:param pos_tags: str list, contains the tag values we consider as positive
:return: the portion of positive examples in the dataset (0<=x<=1)
"""
pos_count = get_tag_count(df, tag_col, pos_tags)
return float(pos_count) / len(df.index)
def switch_df_tag(df, tag, old_tag, new_tag):
df.loc[df[tag] == old_tag, tag] = [new_tag] * len(df.loc[df[tag] == old_tag, tag]) |
7a1e8a3597c1803c66980e2229e60040ae15c778 | mxquants/quanta | /example.py | 4,387 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Example file
How to use quanta for machine learning.
import os; os.chdir("/media/rhdzmota/Data/Files/github_mxquants/quanta")
@author: Rodrigo Hernández-Mota
Contact info: rhdzmota@mxquants.com
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from dataHandler import Dataset
from neuralNets import mlpRegressor
# Create sample data
x_data = pd.DataFrame({"x1": np.random.rand(5000),
"x2": np.arange(5000)**2})
y_data = x_data.apply(lambda x: np.power(np.sqrt(x[1]), x[0]) + 5 *
np.sin(np.pi * x[0]), 1)
# Create dataset object
dataset = Dataset(input_data=x_data, output_data=y_data, normalize="minmax")
def numberOfWeights(dataset, hidden_layers, batch_ref=0.7):
"""Get the number of parameters to estimate."""
n_input = np.shape(dataset.train[0])[-1]
n_output = np.shape(dataset.train[-1])[-1]
params = np.prod(np.array([n_input]+list(hidden_layers)+[n_output]))
n_elements = np.shape(dataset.train[0])[0]
return params, n_elements, batch_ref*n_elements > params
# Multilayer perceptron
_epochs = 2000
_hdl = [10, 10, 10]
nparams, nelements, not_warn = numberOfWeights(dataset, _hdl)
print(not_warn)
if not not_warn:
print("Warning: not enough data to train model.")
mlp = mlpRegressor(hidden_layers=_hdl)
mlp.train(dataset=dataset, alpha=0.01, epochs=_epochs)
train = mlp.train_results
train = pd.DataFrame(train)
test = pd.DataFrame(mlp.test(dataset=dataset))
# estimate
y_estimate = mlp.freeEval(dataset.norm_input_data.values)
plt.plot(dataset.norm_input_data[0].values,
[np.asscalar(i) for i in dataset.norm_output_data.values], "b.")
plt.plot(dataset.norm_input_data[0].values, y_estimate, "r.")
plt.show()
# visualize the training performance
plt.plot(np.arange(_epochs), mlp.epoch_error)
plt.title("MSE per epoch.")
plt.xlabel("Epoch")
plt.ylabel("MSE")
plt.show()
train.errors.plot(kind="kde")
test.errors.plot(kind="kde")
plt.show()
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 6))
plt.subplot(121)
plt.plot(train.y, train.y, ".g", label="Real vals")
plt.plot(train.y, train.estimates, ".b", label="Estimates")
plt.title("Train")
plt.xlabel("y-values")
plt.ylabel("estimates")
plt.legend()
plt.subplot(122)
plt.plot(test.y, test.y, ".g", label="Real vals")
plt.plot(test.y, test.estimates, ".r", label="Estimates")
plt.title("Test")
plt.xlabel("y-values")
plt.ylabel("estimates")
plt.legend()
plt.show()
# Test with iterative selection of hidden layers
max_hidden = 10
max_neurons = 10
mse = {"hidden": [], "neurons": [], "mse": []}
hidden_vector = [None]
temp_hidden_vector = [None]
best_per_layer = []
for i in range(1, max_hidden+1):
print("\n")
for j in range(1, max_neurons+1):
temp_hidden_vector[i-1] = j
nparams, nelements, not_warn = numberOfWeights(dataset,
temp_hidden_vector)
if not not_warn:
print("Not viable anymore.")
break
hidden_vector[i-1] = j
print("Evaluating: ({i}, {j})".format(i=i, j=j), sep="\n")
mse["hidden"].append(i)
mse["neurons"].append(j)
mlp = mlpRegressor(hidden_layers=hidden_vector)
mlp.train(dataset=dataset, alpha=0.01, epochs=_epochs)
mse["mse"].append(np.mean(mlp.test(dataset=dataset)["square_error"]))
# print(mse["mse"][-1])
if not not_warn:
break
temp = pd.DataFrame(mse)
min_mse_arg = temp.query("hidden == {}".format(i)).mse.argmin()
temp_hidden_vector[i-1] = temp["neurons"].iloc[min_mse_arg]
hidden_vector[i-1] = temp["neurons"].iloc[min_mse_arg]
best_per_layer.append(temp["mse"].iloc[min_mse_arg])
hidden_vector.append(None)
temp_hidden_vector.append(None)
hidden_vector
plt.plot(np.arange(len(best_per_layer))+1, best_per_layer)
plt.show()
mse_df = pd.DataFrame(mse)
mse_df
x = mse["hidden"]
y = mse["neurons"]
z = mse["mse"]
min_z, max_z = min(z), max(z)
z = [(i-min_z)/(max_z-min_z) for i in z]
plt.scatter(x, y, c=z, s=100)
# plt.gray()
plt.xlabel("Number of hidden layers")
plt.ylabel("Number of neurons at last hl")
plt.grid()
plt.show()
plt.plot(x, mse["mse"])
# plt.gray()
plt.xlabel("Number of hidden layers")
plt.ylabel("mse")
plt.grid()
plt.show()
plt.plot(y, mse["mse"], '.b')
# plt.gray()
plt.xlabel("Number of neurons")
plt.ylabel("mse")
plt.grid()
plt.show()
|
a8aab4f6481fcece5c333a1d5acdd5cc28306a85 | Aasthaengg/IBMdataset | /Python_codes/p02256/s069709928.py | 327 | 4 | 4 | #! python3
# greatest_common_divisor.py
def greatest_common_divisor(x, y):
r = None
if x >= y:
r = x%y
if r == 0: return y
else:
r = y%x
if r == 0: return x
return greatest_common_divisor(y, r)
x, y = [int(n) for n in input().split(' ')]
print(greatest_common_divisor(x, y))
|
9c593b883c3252e3058e121997f84b177e20d1e9 | MasatakeShirai/Python | /chap13/13-1.py | 2,057 | 4.21875 | 4 | #インスタンスにかかわる文法
# インスタンスの生成
# クラス宣言.すべてのクラスは'object'を根底に継承する
# 構文 class クラス名(継承元のクラス名)
class Shape(object):
pass
# インスタンス生成
# 構文 インスタンス = クラス名()
shape = Shape()
#インスタンスの属性
# 個々のインスタンスで保持する属性をインスタンス属性と呼ぶ
# 属性はオブジェクトにピリオドで紐づくもの
# 最初に_がつくものを慣例的にプライベート属性として扱う.
# 両端に__がつくものはシステムで内部的に扱われる
shape1 = Shape()
shape2 = Shape()
shape1.position = 3
shape2.position = 4
print((shape1.position, shape2.position))
#インスタンスのメソッド
import random
class Shape(object):
#インスタンス・メソッド内のselfはインスタンス自身を指す
# メソッドの第1引数はself,第2引数にはインスタンス生成時に渡した引数と対応する
# 第1引数のselfは省略できない
def set_random_position(self, bound):
self.position = bound * random.random()
shape = Shape()
shape.set_random_position(3)
print(shape.position)
#特殊メソッド
# コンストラクタ
class Shape(object):
#コンストラクタの定義
def __init__(self, width):
self.width = width
#コンストラクタが呼び出される
shape = Shape(3)
print(shape.width)
#プロパティ
# プロパティはいわゆるゲッタやセッタのインスタンス・メソッドを使って
# インスタンス属性を扱っているように見せる属性
class Shape(object):
def _get_color(self):
return tuple(v * 255.0 for v in self._rgb)
def _set_color(self, rgb):
self._rgb = tuple(v/255.0 for v in rgb)
color = property(_get_color, _set_color)
shape = Shape()
#0-255のRGBで設定
shape.color = (255, 0, 0)
#0-255のRGBを参照
print(shape.color)
#内部的には0-1で保持
print(shape._rgb) |
1fc996509abc58e0609d1b1e7e55813e955d920f | savanddarji/Encryption-using-Shift-Cipher | /Encrypt the shift cipher_JMD.py | 846 | 4.0625 | 4 | ################### program for forming shift cipher ########################
from __future__ import division
import numpy as np
import string
a = raw_input("Enter the cipher text: ").lower()
key=raw_input('Enter the Key:')#enter the required number of shift
key=int(key)
num = dict(zip(range(0,26),string.ascii_lowercase))# for reverse mapping: numbers to letter
def shift(l1,n1): # for left shift operation
return l1[n1:] + l1[:n1]
a1=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
S1=[]
for character in a:
number= ord(character)-97
# print number
number=((number + key)%26)
# print number
S1.append(number)
a2=[]
for i2 in S1:
a2.append(num[i2])
print '\n','Your shift ciphered text for the given key:',''.join(str(elm) for elm in a2)
|
0d1f50172a3573b6dbb5b74139896fdaf6be0d09 | enrro/TC1014-Files-done-in-class | /3.-Segundo parcial/TablaMultiplicacion2.py | 242 | 3.796875 | 4 | '''
Created on 04/10/2014
Otra forma de hacer la tabla de multiplicacion
@author: A01221672
'''
def multiplica(n):
for i in range (1,n+1):
for e in range (1,n+1):
print( e *i, end ="\t")
print()
multiplica(2)
|
f5462cf469f65f806044b6ae70f704908c968538 | guilhermeribg/pythonexercises | /bhaskara2.py | 753 | 3.984375 | 4 | import math
a = float(input("Digite o valor de a "))
b = float(input("Digite o valor de b "))
c = float(input("Digite o valor de c "))
def d (b,a,c):
return(b**2 - 4*(a*c))
def x (b, a):
return (-b/2*a)
def x1 (b, d2, a):
return ((-b + math.sqrt(delta))/(2*a))
def x2 (b, d2, a):
return ((-b - math.sqrt(delta))/(2*a))
if d(b,a,c) == 0:
print("a raiz desta equação é",x (b, a))
elif d (b,a,c)<0:
print("esta equação não possui raízes reais")
elif d (b,a,c)>0:
delta = d(b,a,c)
raiz1 = x1(b,math.sqrt(delta),a)
raiz2 = x2(b,math.sqrt(delta),a)
if raiz1>raiz2:
print("as raízes da equação são",raiz2, "e",raiz1)
else:
print("as raízes da equação são",raiz1, "e",raiz2) |
4b0be9ac21be53419894000087a234d91195af9d | XinZhaoFu/leetcode_moyu | /733图像渲染.py | 2,071 | 3.515625 | 4 | """
有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。
给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。
最后返回经过上色渲染后的图像。
示例 1:
输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出: [[2,2,2],[2,2,0],[2,0,1]]
解析:
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。
"""
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
img_row = len(image)
img_col = len(image[0])
src_color = image[sr][sc]
if src_color == newColor:
return image
pixels_queue = [(sr, sc)]
while pixels_queue:
pixel_row, pixel_col = pixels_queue.pop(0)
image[pixel_row][pixel_col] = newColor
for temp_row, temp_col in (
(pixel_row - 1, pixel_col), (pixel_row + 1, pixel_col),
(pixel_row, pixel_col - 1), (pixel_row, pixel_col + 1)):
if 0 <= temp_row < img_row and 0 <= temp_col < img_col \
and image[temp_row][temp_col] == src_color:
pixels_queue.append((temp_row, temp_col))
return image
|
e1d30902868ef467c3d68d951c96278b24fe8f9b | igortereshchenko/amis_python | /km73/Savchuk_Ivan/4/Task4.py | 246 | 3.8125 | 4 | n=int(input("Hello, please enter the number of students:",))
k=int(input("Please, enter tne number of apples:",))
d1=k//n
d2=k%n
print('The number of students which are took apples:',d1)
print('the number of apples which are not took:',d2)
|
31060f5e033ccb1e4cecce707ecc7a7cafe4de0c | Ayselin/python | /name.py | 240 | 3.9375 | 4 | def word_count(string):
new_list = string.split()
unique = set(new_list)
my_dict={}
for unique in new_list:
my_dict[unique]=new_list.count(unique)
return my_dict
print(word_count("hello olla hello Hi hi yes Yes no no")) |
abe8072cf4309c98beb0c89630a6778497293ede | yyzz1010/leetcode | /461.py | 329 | 3.609375 | 4 | class Solution:
def hammingDistance(self, x: int, y: int) -> int:
# len('{0:b}'.format(2 ** 31)) = 32
binary_x = '{0:032b}'.format(x)
binary_y = '{0:032b}'.format(y)
count = 0
for (x,y) in zip(binary_x, binary_y):
if x != y:
count += 1
return count
|
bee6328495ea125dfae3d69bfac24f1bf0848436 | ISQA-Classes/3900samples | /11_testing_debugging/complete/p5-2_guesses.py | 1,005 | 4.15625 | 4 | #!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + ".\n")
count = 1
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
|
97076dd53da98f5c60c38113ab522f7473d97608 | blacksheep/blacksheep-mapgeo | /web/distance.py | 586 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def calc_distances_of(a, b, r =3443.9):
# 3963.1 statute miles
# 3443.9 nautical miles
# 6378 km
return math.acos(
math.cos(a[0]) * math.cos(b[0]) * math.cos(a[1]) * math.cos(b[1])
+ math.cos(a[0])* math.sin(b[0]) * math.cos(a[1]) * math.sin(b[1])
+ math.sin(a[0])* math.sin(a[1])) * r
def main():
# a = input()
# b = input()
a = (33.606379, -86.50249)
b = (33.346817, -86.95252)
print calc_distances_of(a,b), ' Miles'
if __name__ == "__main__":
main()
|
69e010aaf96e5708729d083d5c471ff520f7d324 | thesmigol/python | /1013.py | 556 | 3.609375 | 4 | a = None
b = None
c = None
ganhou = None
kkkkkkkkk_eh_maior_po = None
lista = None
valores_de_entrada = None
def read_line():
try:
# read for Python 2.x
return raw_input()
except NameError:
# read for Python 3.x
return input()
valores_de_entrada = read_line()
lista = valores_de_entrada.split(" ")
a = int((lista[0]))
c = int((lista[2]))
b = int((lista[1]))
kkkkkkkkk_eh_maior_po = ((a + b) + (abs((a - b)))) / 2
ganhou = ((kkkkkkkkk_eh_maior_po + c) + (abs((kkkkkkkkk_eh_maior_po - c)))) / 2
print(str(ganhou) + str(" eh o maior"))
|
059f332cf6c0eec7b3220af10e8764f52d1705f3 | EmandM/ladebug | /commandLine/exercises/tutorial.py | 1,281 | 3.84375 | 4 | '''
Use the column on the far left to 'flag' lines in the code that contain errors.
Find and flag an error line, then click the Fix Errors tabs above to edit the code.
Once you've fixed the error, click the Flag Errors tab to go back and run your code.
When all errors are fixed, submit your solution below.
For more hints, read the comments below.
'''
# 'def function_name():' defines a function in python. The line below is missing ()
def count_to_five:
result = []
# Set a breakpoint by clicking on the column to the left of the line number.
# Try this on line 21.
# Now, click the run/play button below and code execution will stop on the breakpoint.
# Check the value of stored variables at this line in the global variables card.
# You can use the step forward and step backward buttons on either side of the
# run/play button to move step by step through the code, and check the variables
# at each line.
for i in range(0, 5):
result.append(i)
return result
output = count_to_five()
correct_result = [1, 2, 3, 4, 5]
print(output)
if output != correct_result:
raise Exception("Incorrect Output")
'''
Description:
This is a tutorial on how to use Ladebug.
Follow the instructions in the comments.
Error Lines: 10, 20
''' |
61360f98175a01562c290bc56dbb15ffa9ed1abb | elj/mailbox-doors | /sound-playback.py | 5,878 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Name: 010_sound_only_no_graphic.py
Purpose: demonstrate use of pygame for playing sound & music
URL: http://ThePythonGameBook.com
Author: Horst.Jens@spielend-programmieren.at
Licence: gpl, see http://www.gnu.org/licenses/gpl.html
works with pyhton3.4 and python2.7
"""
#the next line is only needed for python2.x and not necessary for python3.x
from __future__ import print_function, division
import pygame
import os
import sys
import time
# if using python2, the get_input command needs to act like raw_input:
if sys.version_info[:2] <= (2, 7):
get_input = raw_input
else:
get_input = input # python3
### custom variables for this file ###
# set number of desired asynchronous channels (referenced later in mixer setup)
number_of_channels = 8
# set final fadeout time
exitfade = 1000
### end custom variables ###
### functions and stuff go here ###
# the REAL way to get the number of channels a sound is playing on
def get_num_active_channels(sound):
"""
Returns the number of pygame.mixer.Channel that are actively playing the sound.
http://stackoverflow.com/questions/17534247/pygame-sound-get-num-channels-not-accurate
"""
active_channels = 0
if sound.get_num_channels() > 0:
for i in range(pygame.mixer.get_num_channels()):
channel = pygame.mixer.Channel(i)
if channel.get_sound() == sound and channel.get_busy():
active_channels += 1
print("actually detected active channels = {}".format(active_channels))
return active_channels
# process a door changing state
def toggle_door(d):
if d > (len(doors)-1):
print("door not found!")
return
num_active = get_num_active_channels(doors[d][0])
if num_active > 0:
print("toggling door {} OFF because it is playing on {} channels".format(d, num_active))
doors[d][0].fadeout(doors[d][1]) # expects milliseconds
else:
ch = doors[d][0].play(loops=doors[d][2])
print("toggling door {} ON, channel {}".format(d, ch))
# TODO: more door-audio toggling goes here #
def set_door_audio(d, desired_state):
if d > (len(doors)-1):
print("door not found!")
if(desired_state):
print("playing door ", d)
doors[d][0].play(loops=doors[d][2])
else:
print("stopping door ", d)
doors[d][0].fadeout(doors[d][1])
# work-in-progress for making fades nicer
def fade_down_attempt(sound, target_level, fade_ms):
i = sound.get_volume()
step_time = (i - target_level)/fade_ms
print("step time = {}".format(step_time))
while i > target_level:
i -= 0.01
# sound.set_volume(i)
time.sleep(fade_ms) # expects seconds
print(i)
### end functions ###
pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag
pygame.init() #initialize pygame - this is where terrible things happen
pygame.mixer.set_num_channels(number_of_channels) # must come *after* .init
# look for sound & music files in subfolder 'data'
#pygame.mixer.music.load(os.path.join('data', 'loophole.wav'))#load music
jump = pygame.mixer.Sound(os.path.join('data','jump.wav')) #load sound
fail = pygame.mixer.Sound(os.path.join('data','fail.wav')) #load sound
### LOAD DOOR SOUNDS HERE ###
# door = sound, fadeout_ms, loops]
door0 = [pygame.mixer.Sound(os.path.join('data','fail.wav')), 0, 0]
door1 = [pygame.mixer.Sound(os.path.join('data','loophole.wav')), 2000, 0]
door2 = [pygame.mixer.Sound(os.path.join('data','jump2.wav')), 1000, 0]
door3 = [pygame.mixer.Sound(os.path.join('data','jump3.wav')), 3000, 0]
doors = [door0, door1, door2, door3]
### END LOAD DOOR SOUNDS ###
f = [1.0, 0.99, 0.98, 0.97, 0.96, 0.95, 0.94, 0.93, 0.92, 0.91,
0.90, 0.89, 0.88, 0.87, 0.86, 0.85, 0.84, 0.83, 0.82, 0.81,
0.80, 0.79, 0.78, 0.77, 0.76, 0.75, 0.74, 0.73, 0.72, 0.71,
0.70, 0.69, 0.68, 0.67, 0.66, 0.65, 0.64, 0.63, 0.62, 0.61,
0.60, 0.59, 0.58, 0.57, 0.56, 0.55, 0.54, 0.53, 0.52, 0.51,
0.50, 0.49, 0.48, 0.47, 0.46, 0.45, 0.44, 0.43, 0.42, 0.41,
0.40, 0.39, 0.38, 0.37, 0.36, 0.35, 0.34, 0.33, 0.32, 0.31,
0.30, 0.29, 0.28, 0.27, 0.26, 0.25, 0.24, 0.23, 0.22, 0.21,
0.20, 0.19, 0.18, 0.17, 0.16, 0.15, 0.14, 0.13, 0.12, 0.11,
0.10, 0.09, 0.08, 0.07, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01, 0.00]
# game loop
gameloop = True
print("number of channels = {}".format(pygame.mixer.get_num_channels()))
while gameloop:
# print menu
answer = get_input("{} tracks are playing.\ntype a door # 1-8, or q to stop all: ".format(pygame.mixer.get_busy()))
answer = answer.lower() # force lower case
try:
val = int(answer)
print("N")
toggle_door(val)
continue
except ValueError:
print("NaN")
if "a" in answer:
jump.play(fade_ms=2000)
print("playing jump.wav once")
elif "b" in answer:
fail.play()
print("playing fail.wav once")
elif "f" in answer:
fade_down_attempt(door1[0], 0.5, 5000)
elif "r" in answer:
door1[0].set_volume(1.0)
# elif "m" in answer:
# if pygame.mixer.music.get_busy():
# pygame.mixer.music.stop()
# else:
# pygame.mixer.music.play()
elif "q" in answer:
#nicely fade out playing sounds
pygame.mixer.fadeout(exitfade) # expects milliseconds
# pygame.mixer.music.fadeout(exitfade) # expects milliseconds
time.sleep(exitfade/1000) # expects seconds
#break from gameloop
gameloop = False
else:
print("that is not a thing :(")
# print("{} tracks are playing".format(pygame.mixer.get_busy()))
print("bye-bye")
GPIO.cleanup()
pygame.quit() # clean exit
|
38b393c998de2536289111af29d457dc8bc226ac | dslu7733/functional_python_programming | /chapter1_函数式编程概述/sample.py | 2,665 | 3.671875 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
#+--+--+--+--+--+--+--+--+--+--
#author : lds
#date : 2020-04-16
#function :
#+--+--+--+--+--+--+--+--+--+--
__author__ = 'lds'
# sample 1
class Summable_List( list ):
def sum(self):
s = 0
for i in self:
s += i
return s
sumOfList1 = Summable_List( [1,2,3] )
print( sumOfList1.sum() )
# sample 2
def sumr( seq ):
if len(seq) == 0: return 0
return seq[0] + sumr(seq[1:])
print( sumr([1,2,3]) )
# sample 3
def until( n, filter_func, v ):
"从[v,n)中找出3或5的倍数"
if v == n: return []
if filter_func(v): return [v] + until(n, filter_func, v+1)
else: return until(n, filter_func, v+1)
print( until(20, lambda x : x % 3 == 0 or x % 5 == 0, 4) )
# sample 4
# 混合范式
print( sum(x for x in range(1,10) if x % 3 == 0 or x % 5 == 0 ) )
# sample 5
import timeit
print( timeit.timeit( "(((([]+[1])+[2])+[3])+[4])" ) )
# sample 6
def next_( n,x ):
"牛顿法求n的平方根x"
return (x + n / x) / 2.0
n = 2
a0 = 1.0
f = lambda x : next_(n,x) #lambda还能这么用,封装了函数。函数f求x的平方根
print( [ round(x,4) for x in (a0, f(a0), f(f(a0)), f(f(f(a0))) ) ] )
stmt = '''
def repeat( f, a0 ):
yield a0
while True:
a0 = f(a0)
yield a0
n = 2 #求2的平方根
r = repeat( lambda x : (x+n/x)/2 ,1)
for i in range(4):
#print( next(r) )
next(r)
'''
print( "timeit1 = %f" % timeit.timeit( stmt=stmt ) )
stmt = '''
#a0是第一个猜测的数字
def repeat( f, a0 ):
"牛顿法求平方根的迭代器"
yield a0
for res in repeat(f, f(a0)):
yield res
n = 2
r = repeat(lambda x : (x+n/x)/2, 1)
for i in range(4):
#print( next(r) )
next(r)
'''
print( "timeit2 = %f" % timeit.timeit( stmt=stmt ) )
# sample 7
def repeat(f, a0):
"生成平方根的迭代器,f生成下一个x迭代的值"
yield a0
for x in repeat(f, f(a0)):
yield x
def findSqrt( pre, iterable, a ):
"计算精度为pre的n的平方根"
b = next(iterable)
if abs(a-b) <= pre: return b
return findSqrt(pre, iterable, b)
n = 2.0
a0 = 1.0
iterable = repeat( lambda x : (x+n/x)/2.0, a0 )
next(iterable)
print( findSqrt( 1e-4, iterable, a0 ) )
#闭包封装函数
def within( prec, iterable ):
def head_tail( prec, a ):
b = next(iterable)
if abs(a-b) <= prec: return b
return head_tail( prec, b )
return head_tail(prec, next(iterable))
#调用封装函数
def sqrt(a0, prec, n):
return within( prec, repeat( lambda x : (x+n/x)/2.0, a0) )
print( sqrt(1.0, 1e-4, 2.0) )
|
402260456db0d4b2086160fde3810789881bfdff | Nohxy/PyLearn | /lesson.py | 427 | 4.21875 | 4 | # Calculator
a = float(input("Inter first number: "))
b = float(input("Inter second number: "))
v = input("Chose +,-,*,/ : ")
str(v)
if v == '+':
c = a + b
print("Your number is: ",c)
elif v == '-':
c = a - b
print("Your number is: ",c)
elif v == '*':
c = a * b
print("Your number is: ",c)
elif v == '/':
c = a/b
print("Your number is: ",c)
else:
print("Error")
|
d040b42447b41f596b0ab97d0a52d028ed9ac45a | hussainMansoor876/Python-Work | /Python/Random function.py | 176 | 3.515625 | 4 | from random import randint
mylist=[]
for val in range(0,10):
num = randint(1, 10)
if (num in mylist):
del num
else:
mylist.append(num)
print(mylist) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.