blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
20b40fc8afd01b0d09b0c80997abd5d6549364ea | my13/fa_mbd_2015b | /H3.py | 4,765 | 3.640625 | 4 |
# coding: utf-8
# ### H.3) Human Assisted Binning
# Program will let user decide number of bins for each variable that should be binned, bin them and return the comparisons. It will not suggest the number of bins as this can be garnered from the automatic version of the program
#
# In[2]:
import pandas as pd
import numpy as np
df = pd.read_csv('https://dl.dropboxusercontent.com/u/28535341/dev.csv')
df_clean = df # assign a clean dataframe if we need it later
# In[3]:
# while loop to obtain user input on name of target variable
while True:
tv = input("Enter name of target variable (type e to exit): ")
if tv in df.columns:
print("Perfect! Thanks")
break
elif tv == 'e':
break
# In[4]:
while True:
id_var = input("Enter name of id variable (type e if none or to exit): ")
if id_var in df.columns:
print("Perfect! Thanks")
break
elif id_var == 'e':
break
# In[5]:
td1 = [id_var]
td = [i for i in td1 if i != 'e']
td = [x for x in td if len(x) > 0]
df_drop = df.drop(td,axis=1)
# In[22]:
def user_woe(df):
bin_list = []
for var_name in df_drop:
if(len(df_drop[var_name].unique()) >= 24): # more than 24 unique values to use binning
bin_list.append(var_name)
iv_list = []
a= 0.01
for var_name in bin_list:
biv = pd.crosstab(df[var_name],df[tv])
WoE = np.log((1.0*biv[0]/sum(biv[0])+a) / (1.0*biv[1]/sum(biv[1])+a)) #multiply by 1.0 to transform into float and add "a=0.01" to avoid division by zero.
IV = sum(((1.0*biv[0]/sum(biv[0])+a) - (1.0*biv[1]/sum(biv[1])+a))*np.log((1.0*biv[0]/sum(biv[0])+a) / (1.0*biv[1]/sum(biv[1])+a)))
iv_list.append(IV)
iv_list = iv_list
test = pd.DataFrame({'Column Name' : bin_list,'IV' : iv_list})
return(test.sort_values(by = 'IV', ascending = False))
# In[23]:
def user_bin(df):
col_list = []
iv_list = []
bins_list = []
iv_max = 0
a= 0.01
for var_name in df_drop:
if(len(df_drop[var_name].unique()) >= 24): # more than 24 unique values to use binning (user cannot change)
col_list.append(var_name)
print("There are " + str(len(col_list)) + " columns that are elegible for binning")
print()
for var_name in col_list:
num = input('Please enter the number of bins you would like for varaible: ' + str(var_name) +
' (Min = '+ str(min(df[var_name])) + ', Max = '+ str(max(df[var_name])) +
', Std = ' + str(round(np.std(df[var_name]),2)) + ')')
bins = np.linspace(df[var_name].min(), df[var_name].max(), num)
groups = np.digitize(df[var_name], bins)
biv = pd.crosstab(groups,df[tv])
WoE = np.log((1.0*biv[0]/sum(biv[0])+a) / (1.0*biv[1]/sum(biv[1])+a)) #multiply by 1.0 to transform into float and add "a=0.01" to avoid division by zero.
IV = sum(((1.0*biv[0]/sum(biv[0])+a) - (1.0*biv[1]/sum(biv[1])+a))*np.log((1.0*biv[0]/sum(biv[0])+a) / (1.0*biv[1]/sum(biv[1])+a)))
iv_list.append(IV)
bins_list.append(num)
test = pd.DataFrame({'Column Name' : col_list,'IV' : iv_list, 'Num_Bins' : bins_list})
return(test.sort_values(by = 'IV', ascending = False))
# In[24]:
# Function for determining value of IV
def iv_binning(df2):
df2['Usefulness'] = ['Suspicous' if x > 0.5 else 'Strong' if x <= 0.5 and x > 0.3 else 'Medium'
if x <= 0.3 and x > 0.1 else 'Weak' if x <= 0.1 and x > 0.02 else
'Not Useful' for x in df2['IV']] # Source for 'Usefullness Values' Siddiqi (2006)
return(df2)
# ### These are the two main functions for user assisted binning. The first allows the user to compare the IV for the selected number of bins with the scenario in which no binning was performed. The second transforms the orginal dataset according the number of bins selected for each variable.
# In[25]:
def user_compare(df): # compares IV and Usefullness for binned and IV and Usefullness for unbinned varaibles
df1 = user_woe(df)
df_woe = iv_binning(df1)
df2 = user_bin(df)
df_bin = iv_binning(df2)
common = df_bin.merge(df_woe,on=['Column Name'])
common.columns = ['Column Name', 'IV Bins', 'Num Bins', 'Usefulness IV', 'IV No Bins', 'Usefulness IV']
return(common)
# In[ ]:
def user_transform(df):
common = user_compare(df)
bin_list = common['Num Bins']
variable_list = common['Column Name']
for idx,var_name in enumerate(variable_list):
bins = np.linspace(df[var_name].min(), df[var_name].max(), bin_list[idx])
df[var_name] = np.digitize(df[var_name], bins)
# In[52]:
|
f3169cd9441ce5e923cef3dc990365995e1be1a8 | tomatiks/course_tests | /tin_2019/2_count_letters.py | 301 | 3.875 | 4 |
def count_letters(s):
unique = set(s)
result = ''
for letter in unique:
if s.count(letter) > 1:
result += letter
return result
#assert sorted(count_letters('rtoplkghrtlkrtsazcvbcxwqx')) == ['c', 'k', 'l', 'r', 't', 'x']
s = input()
print(count_letters(s))
|
145096b2065f51ecef3fa821cc4999388a5fbfa4 | n02696438/ELSpring2016 | /code/myBlinkingLed.py | 478 | 3.625 | 4 | import RPi.GPIO as GPIO
import time
# set mode of GPIO and set up pin 17 as gpio output
GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.OUT)
#blinks pin 17 led rapidly argument "blinks" number of times
def Blink(blinks):
for i in range(0,blinks):
GPIO.output(17,True)
time.sleep(.25)
GPIO.output(17,False)
time.sleep(.25)
#blinks LED 3 times, sleeps for 5 seconds then 4 times. Repeats.
while 1:
Blink(3)
time.sleep(5)
Blink(4)
time.sleep(5)
|
069ecf78bf7f2a455e754f0f147bb46d0e9765aa | rafaelperazzo/programacao-web | /moodledata/vpl_data/38/usersdata/109/15254/submittedfiles/decimal2bin.py | 243 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n=input('Digite um número binário:')
a=0
b=n
while b>=1:
b=b/10
a=a+1
cont=0
for i in range (0,a,1):
u=n%10
c=(u*(2**i))
cont=cont+c
n=n//10
print (cont) |
c5ffe60cdb113df30598ed1cc1c30bbbdb08cfb2 | joyfulbean/Algorithms | /leetcode/Hash/LOW/jewls-stones.py | 440 | 3.5625 | 4 | # https://leetcode.com/problems/jewels-and-stones/
class Solution(object):
def numJewelsInStones(self, jewels, stones):
"""
:type jewels: str
:type stones: str
:rtype: int
"""
# a, A
result = 0
for char in jewels:
result += collections.Counter(stones)[char]
return result
## 파이썬 다운 방식
# return sum(s in J for s in S)
## counter사용
|
b0b8a33d0f46684943333ed83578c4064a8e402c | 2XL/Python4Everyone | /tiposbasicos/__init__.py | 1,663 | 4.125 | 4 | # tipos: entero/coma flotante/ complejos/ strings/ booleans
# esto es una cadena
c = "Hola Mundo"
# y esto es un entero
e = 21
# podemos comprobar con la funcion type
print type(c)
print type(e)
# type (enteros) devolveria int
entero = 23
enteroL = 21L
print type(enteroL)
# asignacion ocatal
# 027 octal = 23 en decimal
entero = 027
# en hexadecimal 0x17 = 23 en decimal
print 027
print 0x17
# numeros reales
real=0.2703
print real
print type(real)
# numeros complejos
complejo = 2.1 + 7.8j
print complejo
print type(complejo)
# operadores aritmeticos
r = 3 + 2
print r
r = 4 - 7
print r
r = -7
print r
r = 2*6
print r
r= 2**6
print r
r=3.5/2
print r
r=3.5//2 # division entera xD
print r
r=7%2
print r
# operandos logicos
r=3&2
r= 3 |2
r = 3 ^ 2 # ^ esto es un xor xD
r = ~5 # esto es un not xD
print r
# desplazamiento de bits
r = 1 << 10
print r
r = r >> 5
print r
# cadenas
# pueden tener una codificacion unicode(u) / raw(r)
unicode = u"a"
raw = r"\n"
print unicode
print raw
ucalele = u"\n" # printa una linea blanca xD
print ucalele
triple = ''' primera linea
esto se vera en otra linea '''
tripledoble = """ primar p2
otra linea """ # los tabuladores tambien surgen efecto xD
print triple
print tripledoble
# manipulacion de cadenas
a = "uno"
b= "dos"
c = a + " " + b
print c
d = c + c
print d
doble = a*2
print doble
# Booleanos
r = True and False
print r
r = True or False
print r
r = not True
print r
# expresiones alternativas para booleanos
r = 5==3
r = 5!=3
r = 5<3
r = 5>3
r = 5 <= 4
r = 5 >= 3
|
27b6ce0eeaaacea45fde431ee739c8da81db6a99 | mangalagb/Leetcode | /Easy/AddStrings.py | 1,967 | 4.03125 | 4 | # Given two non-negative integers num1 and num2 represented as string,
# return the sum of num1 and num2.
#
# Note:
#
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if not num1 or not num2:
return ""
elif not num1:
return num2
elif not num2:
return num1
reversed_num1 = num1[::-1]
reversed_num2 = num2[::-1]
len_num1 = len(reversed_num1)
len_num2 = len(reversed_num2)
i = 0
carry = 0
result = ""
while i < len_num1 or i < len_num2:
digit1 = 0
digit2 = 0
sum_digits = 0
if i < len_num1:
digit1 = reversed_num1[i]
if i < len_num2:
digit2 = reversed_num2[i]
if carry:
sum_digits += 1
carry = 0
sum_digits += (int(digit1) + int(digit2))
unit_digit = sum_digits % 10
tens_digit = sum_digits // 10
result = str(unit_digit) + result
if tens_digit != 0:
carry = 1
i += 1
if carry:
result = "1" + result
return result
my_sol = Solution()
num1 = "62"
num2 = "3"
print(my_sol.addStrings(num1, num2)) #65
num1 = "69"
num2 = "99"
print(my_sol.addStrings(num1, num2)) #168
num1 = "9999"
num2 = "1"
print(my_sol.addStrings(num1, num2)) #10000
num1 = "999"
num2 = "11"
print(my_sol.addStrings(num1, num2)) #1010
num1 = "0"
num2 = "0"
print(my_sol.addStrings(num1, num2)) #0
num1 = "10"
num2 = "0"
print(my_sol.addStrings(num1, num2)) #10
|
e67e093fc55269facf58a3a0b7ad0d421f6e7a4e | Sumeet1601/a-program-to-print-table-of-the-given-number-in-python- | /Table_of_a_bumber.py | 102 | 3.9375 | 4 | num=int(input("enter a number="))
sum=0
for i range(1,11):
sum=num*i
print(num,"*",i,"=",sum)
|
f1be4196df1bfcbed5256489a6c56ac17ac1b8d3 | Bernishik/universityAlgorithms | /lab1/main.py | 747 | 3.90625 | 4 | from Tree import Node, create_tree, show_tree_before, PrefixOrder, show_tree,\
PostfixOrder, InfixOrder,SearchNodeBST,InsertNodeBST,DeleteNodeBST,topview
if __name__ == '__main__':
tree = None
# tree =create_tree(tree,5)
# print("Create tree:")
# show_tree(tree)
# print()
# PrefixOrder(tree)
# print()
# PostfixOrder(tree)
# print()
# InfixOrder(tree)
# print()
## part 2
tree2 = Node(8)
tree2 =InsertNodeBST(tree2,12)
tree2 =InsertNodeBST(tree2,4)
tree2 =InsertNodeBST(tree2,2)
#
# print(" BST")
# show_tree(tree2)
# print()
# print("DELETE BST NODE key == 2")
# tree2 = DeleteNodeBST(tree2,2)
# print()
# show_tree(tree2)
topview(tree2)
|
60b41a859968073a08855480ddba699d857d7bd7 | hsiaohan416/stancode | /SC_projects/image_processing/stanCodeshop_basic/green_screen.py | 1,379 | 3.578125 | 4 | """
File: green_screen.py
-------------------------------
This file creates a new image that uses
MillenniumFalcon.png as background and
replace the green pixels in ReyGreenScreen.png
"""
from simpleimage import SimpleImage
def combine(background_img, figure_img):
"""
:param background_img:
:param figure_img:
:return:
"""
blank_img = SimpleImage.blank(figure_img.width, figure_img.height)
for x in range(figure_img.width):
for y in range(figure_img.height):
combine_pixel = blank_img.get_pixel(x, y)
figure_pixel = figure_img.get_pixel(x, y)
bg_pixel = background_img.get_pixel(x, y)
bigger = max(figure_pixel.red, figure_pixel.blue)
if figure_pixel.green > bigger*2:
combine_pixel.red = bg_pixel.red
combine_pixel.green = bg_pixel.green
combine_pixel.blue = bg_pixel.blue
else:
combine_pixel.red = figure_pixel.red
combine_pixel.green = figure_pixel.green
combine_pixel.blue = figure_pixel.blue
return blank_img
def main():
"""
TODO:
"""
space_ship = SimpleImage("images/MillenniumFalcon.png")
figure = SimpleImage("images/ReyGreenScreen.png")
result = combine(space_ship, figure)
result.show()
if __name__ == '__main__':
main()
|
75f9c292acae8fa96ab751efff72bcff35467ace | aphexer/sewer | /sewer/dns_providers/common.py | 4,091 | 3.65625 | 4 | from hashlib import sha256
from sewer.auth import BaseAuthProvider
from sewer.lib import safe_base64
def dns_challenge(key_auth: str) -> str:
"return safe-base64 of hash of key_auth; used for dns response"
return safe_base64(sha256(key_auth.encode("utf8")).digest())
class BaseDns(BaseAuthProvider):
def __init__(self):
super(BaseDns, self).__init__("dns-01")
def create_dns_record(self, domain_name, domain_dns_value):
"""
Method that creates/adds a dns TXT record for a domain/subdomain name on
a chosen DNS provider.
:param domain_name: :string: The domain/subdomain name whose dns record ought to be
created/added on a chosen DNS provider.
:param domain_dns_value: :string: The value/content of the TXT record that will be
created/added for the given domain/subdomain
This method should return None
Basic Usage:
If the value of the `domain_name` variable is example.com and the value of
`domain_dns_value` is HAJA_4MkowIFByHhFaP8u035skaM91lTKplKld
Then, your implementation of this method ought to create a DNS TXT record
whose name is '_acme-challenge' + '.' + domain_name + '.' (ie: _acme-challenge.example.com. )
and whose value/content is HAJA_4MkowIFByHhFaP8u035skaM91lTKplKld
Using a dns client like dig(https://linux.die.net/man/1/dig) to do a dns lookup should result
in something like:
dig TXT _acme-challenge.example.com
...
;; ANSWER SECTION:
_acme-challenge.example.com. 120 IN TXT "HAJA_4MkowIFByHhFaP8u035skaM91lTKplKld"
_acme-challenge.singularity.brandur.org. 120 IN TXT "9C0DqKC_4MkowIFByHhFaP8u0Zv4z7Wz2IHM91lTKec"
Optionally, you may also use an online dns client like: https://toolbox.googleapps.com/apps/dig/#TXT/
Please consult your dns provider on how/format of their DNS TXT records.
You may also want to consult the cloudflare DNS implementation that is found in this repository.
"""
raise NotImplementedError("create_dns_record method must be implemented.")
def delete_dns_record(self, domain_name, domain_dns_value):
"""
Method that deletes/removes a dns TXT record for a domain/subdomain name on
a chosen DNS provider.
:param domain_name: :string: The domain/subdomain name whose dns record ought to be
deleted/removed on a chosen DNS provider.
:param domain_dns_value: :string: The value/content of the TXT record that will be
deleted/removed for the given domain/subdomain
This method should return None
"""
raise NotImplementedError("delete_dns_record method must be implemented.")
def fulfill_authorization(self, identifier_auth, token, acme_keyauthorization):
"""
https://tools.ietf.org/html/draft-ietf-acme-acme-18#section-8.4
A client fulfills this challenge by constructing a key authorization
from the "token" value provided in the challenge and the client's
account key. The client then computes the SHA-256 digest [FIPS180-4]
of the key authorization.
The record provisioned to the DNS contains the base64url encoding of
this digest. The client constructs the validation domain name by
prepending the label "_acme-challenge" to the domain name being
validated, then provisions a TXT record with the digest value under
that name. For example, if the domain name being validated is
"example.org", then the client would provision the following DNS
record:
"""
domain_name = identifier_auth["domain"]
txt_value = dns_challenge(acme_keyauthorization)
self.create_dns_record(domain_name, txt_value)
return {"domain_name": domain_name, "value": txt_value}
def cleanup_authorization(self, **kwargs):
self.delete_dns_record(kwargs["domain_name"], kwargs["value"])
|
d61d917569b2c6bdb455d288ff5ab6fe01beeda3 | zhaolijian/suanfa | /swordToOffer/64.py | 1,420 | 3.546875 | 4 | # class Solution:
# def maxInWindows(self, num, size):
# queue, res, i = [], [], 0
# while size > 0 and i < len(num):
# if len(queue) > 0 and i - size + 1 > queue[0]:
# queue.pop(0)
# while len(queue) > 0 and num[queue[-1]] < num[i]:
# queue.pop(0)
# queue.append(i)
# if i >= size - 1:
# res.append(num[queue[0]])
# i += 1
# return res
# 双端队列
class Solution:
def maxInWindows(self, num, size):
if size < 1 or not num:
return []
if size == 1:
return num
# 滑动窗口中的元素下标所对应的值是一个降序排列
queue = [0]
# 存放窗口中数据量
length = 1
res = []
for i in range(1, len(num)):
if queue[0] < i - size + 1:
queue.pop(0)
length -= 1
while length:
if num[i] > num[queue[-1]]:
queue.pop(-1)
length -= 1
else:
break
queue.append(i)
length += 1
if i + 1 >= size:
res.append(num[queue[0]])
return res
if __name__ == '__main__':
s = Solution()
l = list(map(int, input().split()))
size = int(input())
print(s.maxInWindows(l, size))
|
c61e6143061d5d4dcb8a876eb8756bbea422598d | 51ngularity/custom-modules | /python/list_operations.py | 438 | 3.75 | 4 |
from collections import deque
#make single value list with .popleft ability
def single_value_list(value_list, length_list):
list_temp = deque([])
for x in range(0, length_list):
list_temp.append(value_list)
return list_temp
# update list: new element in, last element out
def update_list(list_, value_):
list_.popleft()
list_.append(value_)
return list_
|
52aefb8ad14d9aa4b242047a17d72390f450c366 | Isaac-Tolu/code-snippets | /swapdict.py | 847 | 4.5625 | 5 | def swapdict(dict_: dict) -> dict:
"""
Swaps the keys and values of a dictionary.
Returns a new dictionary.
- If any of the values of dict_ is unhashable i.e list or dict,
the key-value pair would be ignored.
- If multiple keys in dict_ have the same value,
the keys would be a list in new_dict i.e
{'1': 1, '2': 2, '3': 3, '4': 2} -> {1: '1', 2: ['2', '4'], 3: '3'}
"""
new_dict = {}
for i, j in dict_.items():
if (type(j) == list) or (type(j) == dict):
continue
check = new_dict.get(j)
if check:
if type(check) != list:
new_dict[j] = [check, i]
else:
check.append(i)
new_dict[j] = check
else:
new_dict[j] = i
return new_dict
# Consider dict.setdefault |
dbb0177df1027fc102f89ed636e2b17ad72eb4af | anjalisgrl/MyCaptain | /fibonacci.py | 290 | 4.0625 | 4 | a=0
b=1
n=int(input("Enter the number of terms:"))
if n<0:
print("Input invalid")
elif n==1:
print(a)
else:
print("The fibonacci sequence is: ")
print(a, b , end=" ")
for n in range (0,n):
c=a+b
a=b
b=c
print(c ,end=" ")
|
93b9e41e38bef06e2804716cf9ed1ec278fea03b | chazkiker2/code-challenges | /misc/return_next_number/return_next_number.py | 285 | 3.921875 | 4 | """
Challenge: Create a function that takes a number as an argument, increments the number by +1 and returns the result.
Difficulty: Very Easy
Examples
addition(0) ➞ 1
addition(9) ➞ 10
addition(-3) ➞ -2
Author: @joshrutkowski
"""
def addition(num):
pass # Your code here
|
f5561436ae0bd60044bf4d702919d564e58c9095 | ltzp/LeetCode | /字符串/LeetCode1002_查找常用字符.py | 1,733 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/10/14 0014 18:26
# @Author : Letao
# @Site :
# @File : LeetCode1002_查找常用字符.py
# @Software: PyCharm
# @desc :
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
if not A:
return A
record = A[0]
record_map = {}
for i in record:
if i not in record_map:
record_map[i] = 1
else:
record_map[i] += 1
length = len(A)
res = []
for key,value in record_map.items():
flag = False
if value == 1:
for j in range(1, length):
if A[j].count(key) >= value:
flag = True
else:
flag = False
break
if flag:
res.append(key)
else:
count_min = value
for j in range(1, length):
if A[j].count(key) == 0:
count_min = 0
flag = False
break
elif A[j].count(key) <= count_min:
count_min = A[j].count(key)
flag = True
else:
flag = True
for i in range(count_min):
res.append(key)
return res
if __name__ == "__main__":
solve = Solution()
A = ["dbaabcba","cabcdbab","cdbcbdad","abadbacc","bdddddaa","daddabab","baaaddaa","dccdaabd"]
result = solve.commonChars(A)
print(result) |
be23f75f33ac7f59bfb10d2de765897376a36a83 | bdt-group01/bdt | /Apriori algorithm/reducer2.py | 510 | 3.609375 | 4 | #!/usr/bin/env python
import sys
# input : "count,item1,item2,...,itemi+1"
# output : "count,item1,item2,...,itemi+1"
def readLine(line):
numbers = line.strip().split(',')
lineData = [int(number) for number in numbers]
count = lineData[0]
data = lineData[1:]
return count, data
for line in sys.stdin:
count, data = readLine(line)
if count > 20:
lineDataStr = [str(item) for item in data]
info = ','.join(lineDataStr)
print('{},{}'.format(count, info))
|
3ffe263aae624dfffe25b3b7a448096d8a98e2f6 | pppk520/miscellaneous | /ib/level_5/hashing/equal.py | 1,572 | 3.75 | 4 | '''
Given an array A of integers, find the index of values that satisfy A + B = C + D, where A,B,C & D are integers values in the array
Note:
1) Return the indices `A1 B1 C1 D1`, so that
A[A1] + A[B1] = A[C1] + A[D1]
A1 < B1, C1 < D1
A1 < C1, B1 != D1, B1 != C1
2) If there are more than one solutions,
then return the tuple of values which are lexicographical smallest.
Assume we have two solutions
S1 : A1 B1 C1 D1 ( these are values of indices int the array )
S2 : A2 B2 C2 D2
S1 is lexicographically smaller than S2 iff
A1 < A2 OR
A1 = A2 AND B1 < B2 OR
A1 = A2 AND B1 = B2 AND C1 < C2 OR
A1 = A2 AND B1 = B2 AND C1 = C2 AND D1 < D2
Example:
Input: [3, 4, 7, 1, 2, 9, 8]
Output: [0, 2, 3, 5] (O index)
'''
class Solution:
# @param A : list of integers
# @return a list of integers
def equal(self, A):
d = {}
for i in range(len(A)):
for j in range(i + 1, len(A)):
v = A[i] + A[j]
if not v in d:
d[v] = [(i, j)]
else:
d[v].append((i, j))
for i in range(len(A)):
for j in range(i + 1, len(A)):
v = A[i] + A[j]
if len(d[v]) == 1:
continue
for x, y in d[v][1:]:
if x not in [i, j] and y not in [i, j]:
return [i, j, x, y]
return []
print(Solution().equal([3, 4, 7, 1, 2, 9, 8]))
print(Solution().equal([1, 1, 1, 1, 1]))
print(Solution().equal([0, 0, 1, 0, 2, 1]))
|
8ae7ce27147fe574b5eb9bb4f6fa6213c42eb419 | GongFuXiong/leetcode | /topic10_queue/T621_leastInterval/interview.py | 2,527 | 3.578125 | 4 | '''
621. 任务调度器
给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。
然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的最短时间。
示例 :
输入:tasks = ["A","A","A","B","B","B"], n = 2
输出:8
解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B.
'''
class Solution:
def leastInterval(self, tasks, n):
length = len(tasks)
if length <= 1:
return length
# 用于记录每个任务出现的次数
task_map = dict()
for task in tasks:
task_map[task] = task_map.get(task, 0) + 1
# 按任务出现的次数从大到小排序
task_sort = sorted(task_map.items(), key=lambda x: x[1], reverse=True)
# 出现最多次任务的次数
max_task_count = task_sort[0][1]
# 至少需要的最短时间
res = (max_task_count - 1) * (n + 1)
for sort in task_sort:
if sort[1] == max_task_count:
res += 1
# 如果结果比任务数量少,则返回总任务数
return res if res >= length else length
def leastInterval1(self, tasks, n):
count = [0] * 26
for task in tasks:
count[ord(task) - ord('A')] += 1
count.sort(reverse=True) # 降序
print(f"count:{count}")
max_val = count[0] - 1
res = max_val * n # 空余时间
print(f"res:{res}")
for i in range(1, len(count)):
if count[i] > 0:
res -= min(max_val, count[i]) # 其余任务能安排到空余时间段里 空余时间减小
return res + len(tasks) if res > 0 else len(tasks)
if __name__ == "__main__":
solution = Solution()
while 1:
str1 = input()
str2 = input()
if str1 != "" and str2 != "":
nums = str1.split(",")
k = int(str2)
res = solution.leastInterval(nums,k)
print(res)
else:
break
|
b8abfe2c722bcfac9f723ca6a81fe6bc1f261159 | andrew-yarmola/python-course | /solutions/homework-3/primes.py | 1,993 | 4.4375 | 4 | def primes_less_than(n) :
""" Given an integer n, returns the list of primes less than n. """
if type(n) is not int or n < 3 : return []
# We use a sieve algorithm to
# elimiane all multiples of
# numbers in increasing order
primes = [2]
sieve = list(range(3,n,2)) # all odds less than n
# We will remove all elemnts of the form
# prime*(prime + 2k) wheren k = 0,1,...
while len(sieve) > 0 :
prime = sieve.pop(0)
primes.append(prime)
for x in range(prime**2, n, 2 * prime) :
if x in sieve :
sieve.remove(x)
return primes
def int_sqrt(n) :
""" If n > 0, returns the larges x with x**2 <= n. """
assert n > 0
# smallest integer less than n
if type(n) is not int :
m = int(n//1)
else :
m = n
# We use Newton's method for the function
# f(x) = x^2 - n. We start with x_0 = int(n)+1, and apply
# x_{k+1} = x_k - f(x_k)/f'(x_k) = (x_k + n/x_k)/2
prev, curr = 0, m
while True:
prev, curr = curr, (curr + m // curr) // 2
# Notice that (curr + n//curr) // 2 is at most
# 1 less than (curr + n/curr)/2.
# Thus, by convexity, the first time we are
# f(curr) is negative, we have out answer
if curr**2 <= m :
return curr
def primes_less_than_v2(n) :
""" Given an integer n, returns the list of primes less than n. """
if type(n) is not int or n < 3 : return []
# We start wil all odd numbers less than n
candidates = set(range(3,n,2))
# For odd number x = 3, 5, ..., int_sqrt(n), we will
# remove x^2, x(x+2), x(x+4),... < n from candidates.
# Notice that we are removing only the odd ones.
# Why this works : assume y = a*b with 1 < a <= b
# and y < n, then a < int_sqrt(n), so y will be eliminated.
for i in range(3, int_sqrt(n) + 1, 2) :
candidates.difference_update(range(i**2, n, 2*i))
candidates.add(2)
return sorted(candidates)
|
3a86b75997c9cd42341a2b0e2b17db8ad6bd4e25 | reallybigmistake/hello-world | /gui6.py | 658 | 3.53125 | 4 | from tkinter import *
from sys import exit
class Hello(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
self.data = 42
self.makeWidget()
def makeWidget(self):
widget = Button(self, text='Hello frame world', command=self.message)
widget.pack()
def message(self):
self.data += 1
print('Hello frame world {}!'.format(self.data))
if __name__ == '__main__':
parent = Frame(None)
parent.pack()
Hello(parent).pack(side=RIGHT)
Button(parent, text='Attach', command=quit).pack(side=LEFT)
parent.mainloop()
|
6de77eb4a33a0818328c47647dd1bd8a1fa6ade9 | RawitSHIE/Algorithms-Training-Python | /python/Mountain Demmyeiei.py | 255 | 4.03125 | 4 | """Mountain Demmyeiei"""
def main():
"""ar rai mai ru"""
raw = float(input())
size = int(raw)
for i in range(1, size*2, 2):
for _ in range(size-1):
print(("*"*i).center(size*2), end="")
print(("*"*i).center(size*2))
main()
|
5b5aec4ffbdaedb3e3f222dbd721d561b1c17dc0 | MattChale123/Python-102 | /Phone_Book_App.py | 1,514 | 4.09375 | 4 | import time
phone_book_entries = {
'Melissa': '584-3934-5857',
'Igor': 'You do not contact Igor, Igor contacts you',
'Jazz': '334-584-2345',
}
def phone_book_function(phone_book_entries):
user_input = input('Would you like to: Search, Add, Delete, List All Entries, or Quit? )').lower()
if (user_input == 'search'):
user_input_2 = input('Please list name: ').lower().capitalize()
print(phone_book_entries[user_input_2])
return phone_book_function(phone_book_entries)
elif (user_input == 'add'):
user_input_3 = input('Please enter name: ')
user_input_4 = input('Please enter phone number: ')
for key in phone_book_entries:
adding_entry = {user_input_3: user_input_4}
phone_book_entries.update(adding_entry)
return phone_book_function(phone_book_entries)
elif (user_input == 'delete'):
user_input_5 = input('What name would you like to delete: ')
del phone_book_entries[user_input_5]
return phone_book_function(phone_book_entries)
elif (user_input == 'list all entries'):
print(phone_book_entries)
return phone_book_function(phone_book_entries)
elif (user_input == 'quit'):
print('Now quitting.')
time.sleep(5)
return
else:
print('Please enter Search, Add, Delete, List All Entries, or Quit.')
return phone_book_function(phone_book_entries)
print(phone_book_function(phone_book_entries)) |
aeabe885c36864264c38b80b723db83852992e6d | gustavo-mota/Artificial_Intelligence_Playground | /NRainhasFormigueiro/NRainhas_Fixo/Roleta.py | 1,098 | 3.703125 | 4 | import random
'''
01. var pesos[10]:int = {1,1,1,1,2,3,4,5,5,5};
02 var somaPeso:int = 0;
03. PARA var i=0 ATE 9 FAÇA
04. somaPeso+=pesos[i];
05. FIMPARA
06. var sorteio:INT = ALEATORIO(0,somaPeso);
07. var posicaoEscolhida = -1;
08. FAÇA:
09. posicaoEscolhida++;
10. somaPeso -= pesos[posicaoEscolhida];
11. ENQUANTO(somaPeso>0);
'''
'''
pesos = [1,1,1,1,1,1,1,1,1,1]
#pesos = [1, 1, 1, 1, 2, 3, 4, 5, 5, 5] # cada posição corresponde a uma pergunta
somaPesos = sum(pesos)
sorteio = random.randint(0, somaPesos)
posicaoEscolhida = -1
while sorteio > 0:
posicaoEscolhida += 1
sorteio -= pesos[posicaoEscolhida]
print(pesos[posicaoEscolhida], ", ", posicaoEscolhida)
print(len(pesos))'''
def Roleta(vetor):
somaPesos = sum(vetor)
# Before. try with somaPesos converted to int
sorteio = random.uniform(0, somaPesos) # Error randint don't works with floats
posicaoEscolhida = -1
while sorteio > 0:
posicaoEscolhida += 1
sorteio -= vetor[posicaoEscolhida]
return posicaoEscolhida
# choices(lista, weight=None, cum_weight=None, k=1)[0] |
95b28f33c20cbb6bd849b683bc4d13dc608961d1 | WhosKhoaHoang/db_solid | /hud.py | 2,963 | 3.5 | 4 | #Contains the class that represents a HUD.
import pygame
from colors import *
class HUD(pygame.Surface):
'''A class that represents the HUD for Snake.'''
def __init__(self, width, height, snake):
'''Initializes the attributes of a HUD object.'''
pygame.Surface.__init__(self, (width, height))
self.width, self.height = width, height
self.fill(GRAY)
self.font = pygame.font.SysFont("Arial", 30) #30 == int(self.width * 0.027)
self.health_label = "HEALTH"
self.lives_label = "LIVES"
self.weapon_label = "WEAPON"
self.item_label = "ITEM"
self.snake_health = snake.health
self.snake_weapon = snake.current_weapon
self.snake_item = snake.current_item
self.snake_lives = str(snake.lives)
def draw(self):
'''Draws the HUD.'''
self.fill(GRAY) #Need this so that stuff in the HUD box can get updated
#HEALTH DISPLAY
rendered_health_label = self.font.render(self.health_label, True, WHITE, GRAY)
self.blit(rendered_health_label, (self.width*0.05, self.height*0.20))
pygame.draw.rect(self, RED, (self.width*0.14, self.height*0.15, self.snake_health, 25), 0)
#LIVES DISPLAY
rendered_lives_label = self.font.render(self.lives_label, True, WHITE, GRAY)
rendered_lives_value = self.font.render(self.snake_lives, True, WHITE, GRAY)
self.blit(rendered_lives_label, (self.width*0.05, self.height*0.55))
self.blit(rendered_lives_value, (self.width*0.14, self.height*0.55))
#WEAPON DISPLAY
rendered_weapon_label = self.font.render(self.weapon_label, True, WHITE, GRAY)
rendered_weapon_value = self.font.render(self.snake_weapon.name, True, WHITE, GRAY)
rendered_weapon_stock = self.font.render(str(self.snake_weapon.stock), True, WHITE, GRAY)
self.blit(rendered_weapon_label, (self.width*0.70, self.height*0.20))
self.blit(rendered_weapon_value, (self.width*0.80, self.height*0.20))
self.blit(rendered_weapon_stock, (self.width*0.95, self.height*0.20))
#ITEM DISPLAY
rendered_item_label = self.font.render(self.item_label, True, WHITE, GRAY)
rendered_item_value = self.font.render(self.snake_item.name, True, WHITE, GRAY)
rendered_item_stock = self.font.render(str(self.snake_item.stock), True, WHITE, GRAY)
self.blit(rendered_item_label, (self.width*0.70, self.height*0.55))
self.blit(rendered_item_value, (self.width*0.80, self.height*0.55))
self.blit(rendered_item_stock, (self.width*0.96, self.height*0.55))
def update(self, snake):
'''Updates the HUD.'''
if snake.health >= 0:
self.snake_health = snake.health
self.snake_weapon = snake.current_weapon
self.snake_weapon_stock = snake.current_weapon
self.snake_item = snake.current_item
self.snake_lives = str(snake.lives)
|
56e024fb42801acf7fd62dc5063d69669cb2c474 | LGiave/TPSIT | /Python/Es_vari/Es_11 copy.py | 957 | 3.625 | 4 | import random as rnd
def push(stack,element):
stack.append(element)
return stack
def pop(stack):
element = stack.pop()
return stack,element
def coppaMazzo(stack):
pos=rnd.randint(0,len(stack)-1)
stack = stack[pos:len(stack)] + stack[0:pos]
return stack
def shuffle(stack):
stack1=[]
while stack!=[]:
stack=coppaMazzo(stack)
stack1.append(stack.pop())
return stack1
class carta(object):
def __init__(self,seme,numero):
self.seme = seme
self.numero = numero
def stampa(self):
print(f"La carta ha seme {self.seme} con numero {self.numero}.")
mazzo = []
semi = ["C","P","D","F"]
for i in range(1,14):
for s in semi:
push(mazzo,carta(s,i))
for i in mazzo:
i.stampa()
mazzo=coppaMazzo(mazzo)
print("\n\nmazzo coppato:\n")
for i in mazzo:
i.stampa()
mazzo=shuffle(mazzo)
print("\n\nmazzo mischiato:\n")
for i in mazzo:
i.stampa()
|
eaa4368a796ffd3c034304dad9855f23579039d9 | SaiSudhaV/coding_platforms | /remove_nth_node_from_end.py | 675 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def removeNthFromEnd(self, A, B):
tem, res = A, 1
while tem.next != None:
tem, res, p = tem.next, res + 1, res - B + 1
if B < res:
ptr = A
else:
A = A.next
return A
for i in range(1, res):
if i != p:
ptr = ptr.next
else:
ptr.next = ptr.next.next
return A |
afe3e5614b6dc66a879029a650fbc6b37c73df92 | wai030/Python-project | /wolfs_goats_cabbages.py | 5,884 | 3.734375 | 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
goat=0; wolf=1; cabbage=2
#[[num_Missionaries_left, num_Cannibal_left], [num_Missionaries_right, num_Cannibal_right], boat_position (0=left, 1=right)]
initial_state = [{"goat": 0, 'wolf':0, 'cabbage':0},{'goat':1, 'wolf':1, 'cabbage':1}, RIGHT]
goal_state = [{'goat':1, 'wolf':1, 'cabbage':1},{'goat':0, 'wolf':0, 'cabbage':0}, LEFT]
###################################################
## Functions related to the game
###################################################
# Verifies if the state is safe.
def is_safe(state):
return (
not((state[LEFT].get('goat')==1 and state[LEFT].get('wolf')==1 and state[LEFT].get('cabbage')==0 and state[BOAT_POSITION]==1) or
(state[RIGHT].get('goat')==1 and state[RIGHT].get('wolf')==1 and state[RIGHT].get('cabbage')==0 and state[BOAT_POSITION]==0) or
(state[LEFT].get('goat')==1 and state[LEFT].get('wolf')==0 and state[LEFT].get('cabbage')==1 and state[BOAT_POSITION]==1) or
(state[RIGHT].get('goat')==1 and state[RIGHT].get('wolf')==0 and state[RIGHT].get('cabbage')==1 and state[BOAT_POSITION]==0))
)
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, wolfs, goats, cabbages):
side = state[BOAT_POSITION]
opposite = opposite_side(side)
if state[side].get('goat') >= goats and state[side].get('wolf') >=wolfs and state[side].get('cabbage') >= cabbages:
new_state= copy.deepcopy(state)
new_state[side]['goat'] -= goats
new_state[opposite]['goat'] += goats
new_state[side]['wolf'] -= wolfs
new_state[opposite]['wolf'] += wolfs
new_state[side]['cabbage']-= cabbages
new_state[opposite]['cabbage'] += cabbages
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 wolf
if old_state[side].get('wolf') > 0:
new_state= move(old_state, 1, 0, 0)
if is_safe(new_state):
children.append(new_state)
# Try to move one goat
if old_state[side].get('goat') > 0:
new_state= move(old_state, 0, 1, 0)
if is_safe(new_state):
children.append(new_state)
# Try to move one cabbage
if old_state[side].get('cabbage') > 0 :
new_state= move(old_state, 0, 0, 1)
if is_safe(new_state):
children.append(new_state)
if old_state[side]:
new_state= move(old_state, 0, 0, 0)
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
this = 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:
if this!=True:
this= True
else:
end=True
print("Failed to find a goal state")
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
g_left, w_left, c_left=left
g_right, w_right, c_right=right
if side==LEFT:
boat_l = "#BOAT#";boat_r = " "
else:
boat_l = " ";boat_r = "#BOAT#"
print("wolfs {} goats {} cabbages {} {} |~~~~~| {} wolfs {} goats {} cabbages {}" .format(left[w_left], left[g_left], left[c_left], boat_l, boat_r, right[w_right], right[g_right], right[c_right]))
input()
|
0728e135bdbaaa89ecf243db145ead9645a8c362 | jc003/datascience_yeah | /notes/lecture2/notes.py | 253 | 3.890625 | 4 | ### LECTURE 2 CODE NOTES ###
n = 100
%cpaste
for x in range(100000000):
print(n)
if n % 2 == 0:
#n is even
n = n / 2.0
elif n % 2 == 1:
n = n * 3 + 1
if n == 1:
break;
--
4 2 1
|
195b251226e10cb5afa2103ad0360b18ff434b5d | KamiMoon/python | /crash-course/ch2/strings.py | 360 | 3.875 | 4 | name = "ada lovelace"
print(name.title())
# Ada Lovelace - titlecase
print(name.upper())
print(name.lower())
#concatenation uses +
first_name = "ada"
last_name = "loveland"
full_name = first_name + " " + last_name
print(full_name)
# \t \n work the same
# trim using rstrip(), lstrip, and strip()
favorite_lanague = 'python '
print(favorite_lanague.strip())
|
2c19d4a96328c69cfde86a7f44c218c554e037d6 | joanvaquer/SDMetrics | /sdmetrics/report.py | 8,727 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""MetricsReport module.
This module defines the classes Goal, Metric and MetricsReport, which
are used for reporting the results of the different evaluation
metrics executed on the data.
"""
from enum import Enum
import pandas as pd
class Goal(Enum):
"""
This enumerates the `goal` for a metric; the value of a metric can be ignored,
minimized, or maximized.
"""
IGNORE = "ignore"
MAXIMIZE = "maximize"
MINIMIZE = "minimize"
class Metric():
"""
This represents a single instance of a Metric.
Attributes:
name (str): The name of the attribute.
value (float): The value of the attribute.
tags (set(str)): A set of arbitrary strings/tags for the attribute.
goal (Goal): Whether the value should maximized, minimized, or ignored.
unit (str): The "unit" of the metric (i.e. p-value, entropy, mean-squared-error).
domain (tuple): The range of values the metric can take on.
description (str): An arbitrary text description of the attribute.
"""
def __init__(self, name, value, tags=None, goal=Goal.IGNORE,
unit="", domain=(float("-inf"), float("inf")), description=""):
self.name = name
self.value = value
self.tags = tags if tags else set()
self.goal = goal
self.unit = unit
self.domain = domain
self.description = description
self._validate()
def _validate(self):
assert isinstance(self.name, str)
assert isinstance(self.value, float)
assert isinstance(self.tags, set)
assert isinstance(self.goal, Goal)
assert isinstance(self.unit, str)
assert isinstance(self.domain, tuple)
assert isinstance(self.description, str)
assert self.domain[0] <= self.value and self.value <= self.domain[1]
assert all(isinstance(t, str) for t in self.tags)
def __eq__(self, other):
my_attrs = (self.name, self.value, self.goal, self.unit)
your_attrs = (other.name, other.value, other.objective, self.unit)
return my_attrs == your_attrs
def __hash__(self):
return hash(self.name) + hash(self.value)
def __str__(self):
return """Metric(\n name=%s, \n value=%.2f, \n tags=%s, \n description=%s\n)""" % (
self.name, self.value, self.tags, self.description)
class MetricsReport():
"""
The `MetricsReport` object is responsible for storing metrics and providing a user
friendly API for accessing them.
"""
def __init__(self):
self.metrics = []
def add_metric(self, metric):
"""
This adds the given `Metric` object to this report.
"""
assert isinstance(metric, Metric)
self.metrics.append(metric)
def add_metrics(self, iterator):
"""
This takes an iterator which yields `Metric` objects and adds all
of these metrics to this report.
"""
for metric in iterator:
self.add_metric(metric)
def overall(self):
"""
This computes a single scalar score for this report. To produce higher quality
synthetic data, the model should try to maximize this score.
Returns:
float: The scalar value to maximize.
"""
score = 0.0
for metric in self.metrics:
if metric.goal == Goal.MAXIMIZE:
score += metric.value
elif metric.goal == Goal.MINIMIZE:
score -= metric.value
return score
def details(self, filter_func=None):
"""
This returns a DataFrame containing all of the metrics in this report. You can
optionally use `filter_func` to specify a lambda function which takes in the
metric and returns True if it should be included in the output.
Args:
filter_func (function, optional): A function which takes a Metric object
and returns True if it should be included. Defaults to accepting all
Metric objects.
Returns:
DataFrame: A table listing all the (selected) metrics.
"""
if not filter_func:
def filter_func(metric):
return True
rows = []
for metric in self.metrics:
if not filter_func(metric):
continue
table_tags = [tag for tag in metric.tags if "table:" in tag]
column_tags = [tag for tag in metric.tags if "column:" in tag]
misc_tags = metric.tags - set(table_tags) - set(column_tags)
rows.append({
"Name": metric.name,
"Value": metric.value,
"Goal": metric.goal,
"Unit": metric.unit,
"Tables": ",".join(table_tags),
"Columns": ",".join(column_tags),
"Misc. Tags": ",".join(misc_tags),
})
return pd.DataFrame(rows)
def highlights(self):
"""
This returns a DataFrame containing all of the metrics in this report which
contain the "priority:high" tag.
Returns:
DataFrame: A table listing all the high-priority metrics.
"""
return self.details(lambda metric: "priority:high" in metric.tags)
def visualize(self):
"""
This returns a pyplot.Figure which shows some of the key metrics.
Returns:
pyplot.Figure: A matplotlib figure visualizing key metricss.
"""
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['DejaVu Sans']
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
plt.style.use('seaborn')
fig = plt.figure(figsize=(10, 12), constrained_layout=True)
gs = fig.add_gridspec(5, 4)
# Detectability of synthetic tables
fig.add_subplot(gs[3:, :])
labels, scores = [], []
for metric in self.metrics:
tables = [tag.replace("table:", "")
for tag in metric.tags if "table:" in tag]
labels.append(" <-> ".join(tables))
scores.append(metric.value)
df = pd.DataFrame({"score": scores, "label": labels})
df = df.groupby("label").agg({"score": "mean"}).reset_index()
df = df.sort_values(["score"], ascending=False)
df = df.head(4)
sns.barplot(
x="label",
y="score",
data=df,
ci=None,
palette=sns.color_palette(
"coolwarm_r",
7))
plt.axhline(0.9, color="red", linestyle=":", label="Easy To Detect")
plt.axhline(0.7, color="green", linestyle=":", label="Hard To Detect")
plt.legend(loc="lower right")
plt.title("Detectability of Synthetic Tables", fontweight='bold')
plt.ylabel("auROC")
plt.xlabel("")
# Coming soon.
fig.add_subplot(gs[1:3, 2:])
pvalues = np.array([m.value for m in self.metrics if m.unit == "p-value"])
sizes = [np.sum(pvalues < 0.1), np.sum(pvalues > 0.1)]
labels = ['Reject (p<0.1)', 'Fail To Reject']
plt.pie(sizes, labels=labels)
plt.axis('equal')
plt.title("Columnwise Statistical Tests", fontweight='bold')
plt.ylabel("")
plt.xlabel("")
# Coming soon.
fig.add_subplot(gs[:3, :2])
labels, scores = [], []
for metric in self.metrics:
if metric.unit != "entropy":
continue
for tag in metric.tags:
if "column:" not in tag:
continue
labels.append(tag.replace("column:", ""))
scores.append(metric.value)
df = pd.DataFrame({"score": scores, "label": labels})
df = df.groupby("label").agg({"score": "mean"}).reset_index()
df = df.sort_values(["score"], ascending=False)
df = df.head(8)
sns.barplot(x="score", y="label", data=df, ci=None, palette=sns.color_palette("Blues_d"))
plt.title("Column Divergence", fontweight='bold')
plt.ylabel("")
plt.xlabel("")
# Coming soon.
fig.add_subplot(gs[:1, 2:])
plt.text(0.5, 0.7, r'Overall Score', fontsize=14, fontweight='bold', ha="center")
plt.text(0.5, 0.4, r'%.2f' % self.overall(), fontsize=36, ha="center")
rectangle = plt.Rectangle((0.2, 0.3), 0.6, 0.6, ec='black', fc='white')
plt.gca().add_patch(rectangle)
plt.ylabel("")
plt.xlabel("")
plt.axis('off')
fig.tight_layout(pad=2.0)
return fig
|
c4493af7958e4dce4e45a92803e09c92d624bb2f | Aasthaengg/IBMdataset | /Python_codes/p03262/s772435440.py | 303 | 3.578125 | 4 | import math
from functools import reduce
def gcd(*numbers):
return reduce(math.gcd, numbers)
def gcd_list(numbers):
return reduce(math.gcd, numbers)
N, X = map(int, input().split())
if N>1: x = [int(_)-X for _ in input().split()]; print(gcd_list(x))
else: x = int(input()) - X; print(abs(x))
|
021e08f279a91503133e71909a6ec0a12bfb08e1 | george-marcus/problems-vs-algorithms | /Search in a Rotated Sorted Array/rotated_array_search_tests.py | 741 | 3.609375 | 4 | from rotated_array_search import rotated_array_search
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
test_function([[], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], ''])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
|
0225879ee2e3dd7cd3aae9d537a577c1bcd30f91 | avantika0111/YouTube_Video_Downloader | /downloader.py | 543 | 3.546875 | 4 | from pytube import YouTube
"""
streaming all the formats available for download
"""
link = input("Enter Video URL: ")
yt = YouTube(link)
videos = yt.streams.all()
video = list(enumerate(videos))
for i in video:
print(i)
print("Select download format: ")
dn_option = int(input("Enter the number: "))
try:
dn_video = videos[dn_option]
fn = input('Save As: ')
save_path = input("Enter path to save file: ")
dn_video.download(save_path, filename=fn)
except:
print("Error occurred")
print("Download Successful!!")
|
2c24b086da29869121c4cef26f119195207f0f2e | Miktus/Dissertation | /DSGE_estimation/DSGE/Kalman.py | 5,477 | 3.5 | 4 | """
Implements the Kalman filter for a linear Gaussian state space model.
"""
import numpy as np
from numpy import dot
from scipy.linalg import inv
from textwrap import dedent
class Kalman:
"""
Implements the Kalman filter for the Gaussian state space model
.. math::
x_{t+1} = A x_t + C w_{t+1} \\
y_t = G x_t + H v_t
Here :math:`x_t` is the hidden state and :math:`y_t` is the measurement.
The shocks :math:`w_t` and :math:`v_t` are iid standard normals. Below
we use the notation
.. math::
Q := CC'
R := HH'
Parameters
-----------
A : array_like or scalar(float)
Part of the state transition equation. It should be `n x n`
C : array_like or scalar(float)
Part of the state transition equation. It should be `n x m`
G : array_like or scalar(float)
Part of the observation equation. It should be `k x n`
H : array_like or scalar(float), optional(default=None)
Part of the observation equation. It should be `k x l`
x_hat : scalar(float) or array_like(float), optional(default=None)
An n x 1 array representing the mean x_hat of the
prior/predictive density. Set to zero if not supplied.
Sigma : scalar(float) or array_like(float), optional(default=None)
An n x n array representing the covariance matrix Sigma of
the prior/predictive density. Must be positive definite.
Set to the identity if not supplied.
Attributes
----------
Sigma, x_hat : as above
"""
def __init__(self, A, C, G, H=None, x_hat=None, Sigma=None):
self.A = A
self.C = C
self.G = G
self.Q = np.dot(self.C, self.C.T)
self.m = self.C.shape[1]
self.k, self.n = self.G.shape
if H is None:
self.H = np.zeros((self.k, self.n))
else:
self.H = np.atleast_2d(H)
if Sigma is None:
self.Sigma = np.identity(self.n)
else:
self.Sigma = np.atleast_2d(Sigma)
if x_hat is None:
self.x_hat = np.zeros((self.n, 1))
else:
self.x_hat = np.atleast_2d(x_hat)
self.x_hat.shape = self.n, 1
self.R = np.dot(self.H, self.H.T)
def __repr__(self):
return self.__str__()
def prior_to_filtered(self, y):
r"""
Updates the moments (x_hat, Sigma) of the time t prior to the
time t filtering distribution, using current measurement :math:`y_t`.
The updates are according to
.. math::
\hat{x}^F = \hat{x} + \Sigma G' (G \Sigma G' + R)^{-1}
(y - G \hat{x})
\Sigma^F = \Sigma - \Sigma G' (G \Sigma G' + R)^{-1} G
\Sigma
Parameters
----------
y : scalar or array_like(float)
The current measurement
"""
# === simplify notation === #
G, H = self.G, self.H
R = np.dot(H, H.T)
# === and then update === #
y = np.atleast_2d(y)
y.shape = self.k, 1
E = dot(self.Sigma, G.T)
F = dot(dot(G, self.Sigma), G.T) + R
M = dot(E, inv(F))
print(E.shape, F.shape, M.shape)
self.x_hat = self.x_hat + dot(M, (y - dot(G, self.x_hat)))
self.Sigma = self.Sigma - dot(M, dot(G, self.Sigma))
def filtered_to_forecast(self):
"""
Updates the moments of the time t filtering distribution to the
moments of the predictive distribution, which becomes the time
t+1 prior
"""
# === simplify notation === #
A, C = self.A, self.C
Q = dot(C, C.T)
# === and then update === #
self.x_hat = dot(A, self.x_hat)
self.Sigma = dot(A, dot(self.Sigma, A.T)) + Q
def update(self, y):
"""
Updates x_hat and Sigma given k x 1 nparray y. The full
update, from one period to the next
Parameters
----------
y : np.ndarray
A k x 1 ndarray y representing the current measurement
"""
self.prior_to_filtered(y)
self.filtered_to_forecast()
def __str__(self):
m = """\
Kalman filter:
- dimension of state space : {n}
- dimension of observation equation : {k}
"""
return dedent(m.format(n=self.n, k=self.k))
def log_likelihood(self, y):
"""
Computes log-likelihood of period ``t``
Parameters
----------
y : np.ndarray
A k x 1 ndarray y representing the current measurement
"""
eta = y - np.dot(self.G, self.x_hat) # forecast error
P = np.dot(self.G, np.dot(self.Sigma, self.G.T)) + self.R # covariance matrix of forecast error
logL = - (y.shape[0] * np.log(2*np.pi) + np.log(np.linalg.det(P)) + np.sum(dot(eta.T, dot(inv(P), eta))))/2
return logL
def compute_loglikelihood(self, y):
"""
Computes log-likelihood of entire observations
Parameters
----------
y : np.ndarray
n x T matrix of observed data.
n is the number of observed variables in one period.
Each column is a vector of observations at each period.
"""
T = y.shape[1]
logL = 0
# forecast and update
for t in range(1, T):
logL = logL + self.log_likelihood(y[:, t])
self.update(y[:, t])
return logL
|
6c96e894d8d868a81f6c3abe03814b943029cd64 | erchauhannitin/prod-reports | /readobject.py | 788 | 3.6875 | 4 | class Entry(object):
def __init__(self, NAME, ID, ROLES, STATUS):
super(Entry, self).__init__()
self.NAME = NAME
self.ID = ID
self.ROLES = ROLES
self.STATUS = STATUS
self.entries = []
def __str__(self):
return self.ID + " " + self.ROLES + " " + self.STATUS
def __repr__(self):
return self.__str__()
entries = []
file = open('cluster.txt', 'r').readlines()
title = file.pop(0)
timeStamp = file.pop(0)
header = file.pop(0)
for line in file:
words = line.split()
NAME, ID, ROLES, STATUS = [i for i in words]
entry = Entry(NAME, ID, ROLES, STATUS)
entries.append(entry)
maxEntry = max(entries, key=lambda entry: entry.NAME)
entries.sort(key=lambda entry: entry.ID, reverse=True)
print(entries)
|
19e2d5628966c452305b3f6630f1f7128afaf4ba | jiadaizhao/LeetCode | /1301-1400/1352-Product of the Last K Numbers/1352-Product of the Last K Numbers.py | 573 | 3.75 | 4 | class ProductOfNumbers:
def __init__(self):
self.product = [1]
def add(self, num: int) -> None:
if num == 0:
self.product = [1]
else:
self.product.append(self.product[-1] * num)
def getProduct(self, k: int) -> int:
if k >= len(self.product):
return 0
else:
return self.product[-1] // self.product[-k - 1]
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
|
fc51c4001e6b351ab1ef5776015f1372700383e8 | AdityanJo/Leetcode | /problem_0234_palindrome_linked_list.py | 565 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head is None: return True
if head.next is None: return True
curr = head
val = []
while curr:
# val = val ^ curr.val
val.append(curr.val)
curr = curr.next
# print(val)
if val == val[::-1]:
return True
else:
return False
|
8c62cd7c8d8aaf4b6577f19f14c5c7260a4f40c8 | Faizz79/Python-project-Protek | /Praktikum 9/C9_project 04,faiz.py | 313 | 3.796875 | 4 | #project 4
import random
def shufflestring(kata, n):
listkata = []
while (len(listkata) < n):
acakkata = random.sample(kata, len(kata))
acakurut = ''.join(acakkata)
if(acakurut not in listkata):
listkata.append(acakurut)
print(listkata)
shufflestring('kamu', 7)
|
1d3c5df04a52d231b843c5301c06003b36009576 | miradouro/CursoEmVideo-Python | /aula007 - OPERADORES ARITMETICOS/aula007.py | 274 | 4.03125 | 4 | n1 = int(input('Digite um numero: '))
n2 = n1 - 1
n3 = n1 + 1
print('seu numero é o {}, ele vem depois do numero {} e vem antes do numero {}!'.format(n1, n2, n3))
print('O dobro do seu numero é o {}, o triplo é {} e a raiz quadrada é {}!'.format(n1*2, n1*3, n1**(1/2)))
|
8746feaa87e972879318a2f3afb38e4883847471 | zitorelova/python-classes | /sum.py | 276 | 3.9375 | 4 | def sum(arr):
total = 0
for element in arr:
total = total + element
return total
def sum(arr):
total = 0
if len(arr) > 0:
total = arr[0] + sum(arr[1:])
else:
return 0
return total
test = [1, 2, 3, 4]
print(sum(test)) |
4aaac230de4ad2e5bb06a2f7514c3ef1a4beb125 | mttaborturtle/Image-converters | /JPGtoPNGconvert.py | 997 | 3.765625 | 4 | import sys
import os
from PIL import Image
# Take in the image folder/image and the dest folder
# from the command line
image_folder = sys.argv[1]
dest_folder = sys.argv[2]
# Check to see if the destination folder already
# exists and create it if it does not
try:
if os.path.isdir(dest_folder) == False:
os.mkdir(dest_folder)
print('Sucessfully created folder ' + dest_folder)
else:
print('Your intended dir already exists')
except OSError:
print("Creation of the directory %s failed" % dest_folder)
# Convert all images in folder from JPG to PNG
image_folder_dir = os.listdir(image_folder)
for filename in image_folder_dir:
if filename.endswith('.jpg'):
img = Image.open(f'{image_folder}{filename}')
clean_name = os.path.splitext(filename)[0]
img.save(f'{dest_folder}{clean_name}.png', 'png')
print(f'converted {filename} and saved it to: {dest_folder}')
else:
continue
print('Image Conversion Complete!')
|
5b8592c2c7ed423e99a3eee42b31358dd2b3dc71 | nevepura/python3 | /hardway/ex37.py | 937 | 3.6875 | 4 | ''' Symbol review '''
# assert
def my_assert():
value = 12
treshold = 10
assert value <= treshold, "Value > treshold not allowed: {} > {}".format(value, treshold)
print(isinstance(value, int))
def my_excepion():
print("Exception management starts...")
try:
number = int(input('input an integer: \n> '))
print('Your number is: {}'.format(number))
except ValueError:
print("Input value ain't no number")
finally:
print("Exception management finished.")
# raise: forcefully raise exception: to be used only with custom exceptions
def my_lambda():
value = 3
squareit = lambda x : x * x
print("squareit of {} is: {}".format(value, squareit(value)))
a = 3
b = 5
sumem = lambda x,y : x + y
print("squareit of {} is: {}".format(value, sumem(a,b)))
def main():
# my_excepion()
my_lambda()
if __name__ == "__main__":
main() |
683b52f2f49a93b3df53d52457845bcab80608bd | krimeano/euler-py | /problem504.py | 2,936 | 4 | 4 | """
Let ABCD be a quadrilateral whose vertices are lattice points lying on the coordinate axes as follows:
A(a, 0), B(0, b), C(−c, 0), D(0, −d), where 1 ≤ a, b, c, d ≤ m and a, b, c, d, m are integers.
It can be shown that for m = 4 there are exactly 256 valid ways to construct ABCD. Of these 256 quadrilaterals,
42 of them strictly contain a square number of lattice points.
How many quadrilaterals ABCD strictly contain a square number of lattice points for m = 100?
"""
import math
class Problem504:
def __init__(self):
self.m = 4
self.points_table = {}
self.q_points_table = {}
def construct_qq(self, m):
self.m = m
n = 0
k = 0
m1 = m + 1
max_points = self.count_points_inside_q((m, m, m, m))
ss = [x ** 2 for x in range(1, math.floor(max_points ** 0.5) + 1)]
for a in range(1, m1):
for b in range(1, m1):
for c in range(1, m1):
for d in range(1, m1):
q = (a, b, c, d)
p = self.count_points_inside_q(q)
if p in ss:
k += 1
n += 1
print("\033[F\033[K", q, p, n, k)
print(n, k, "\n")
return n, k
def count_points_inside_q(self, q):
l = len(q)
k = 'x'.join([str(q[j]) for j in range(l)])
if k in self.q_points_table:
# print(k, 'is in cache')
return self.q_points_table[k]
s = 1
for i in range(l):
s += self.count_points_under_line(q[i], q[(i + 1) % l])
# store to cache:
if q[0] == q[1] == q[2] == q[3]:
# print('storing', k)
self.q_points_table[k] = s
return s
for i in range(l):
k = 'x'.join([str(q[(i + j) % l]) for j in range(l)])
# print('storing', k)
self.q_points_table[k] = s
if not (q[0] == q[2] or q[1] == q[3]):
q1 = (q[0], q[3], q[2], q[1])
for i in range(l):
k = 'x'.join([str(q1[(i + j) % l]) for j in range(l)])
# print('storing', k)
self.q_points_table[k] = s
return s
def count_points_under_line(self, a, b):
k = str(a) + 'x' + str(b)
if k in self.points_table:
return self.points_table[k]
s = 0
for x in range(a):
y = b - b * x / a
s += math.ceil(y) - 1
# print(k, x, y, s)
self.points_table[k] = s
return self.points_table[k]
def test(self):
r = self.construct_qq(4)
return r == (256, 42)
def solve(self):
return self.construct_qq(100)[1]
if __name__ == '__main__':
problem = Problem504()
if not problem.test():
print('NOT SOLVED YET')
exit(1)
print(problem.solve())
|
1dc765de9c28d6114a3a43975f80e82a3b398406 | cloew/WiiCanDoIt-Framework | /src/BinaryTreeGame/TwoTeamVersusScreen.py | 3,366 | 3.515625 | 4 | import sys, os
import pygame
from pygame.locals import *
from GameboardClass import *
SCREEN_SIZE = (1152, 864)
BACKGROUND = (235,240,255)
""" Builds the screen for the Two Team Versus Mode game """
class TwoTeamVersusGameScreen:
""" Builds both gameboards and adds their allsprites to the screens allsprites """
def __init__(self, teams):
global BACKGROUND
# Set all variables to the defaults
self.ending = 0
self.surface = pygame.Surface(SCREEN_SIZE)
self.surface.fill(BACKGROUND)
self.gameboards = ([])
self.gboardCoords = [(0,0), (576, 0)]
# Build the Gameboards
self.initGameboard(teams[0], (0, 0))
self.initGameboard(teams[1], (576, 0))
gboard1 = self.gameboards[0]
gboard2 = self.gameboards[1]
# Draw the Gameboards
self.surface.blit(gboard1.surface, (0, 0))
self.surface.blit(gboard2.surface, (576, 0))
# Add the Gameboard's sprites to the screen's allsprites
self.allsprites = pygame.sprite.LayeredUpdates(gboard1.allsprites, gboard2.allsprites)
""" Function that builds the Gameboard objects """
def initGameboard(self, team, coords):
gameboard = Gameboard(team, coords)
self.gameboards.append(gameboard)
""" Updates a specific gameboard """
""" This is called when either the Inserter """
""" has moved the insertSlot """
""" or the rotator has moved the root of the Tree """
def update(self, index):
gboard = self.gameboards[index]
gboard.update()
gboard.guiTree.toUpdate = True
""" Allows users to return to the main screen when the game is over """
def getInput(self, events):
for event in events:
if event.type == MOUSEBUTTONDOWN and self.ending:
return "exit"
""" Tells a Gameboard to make their status button appear """
def itsBalanced(self, index):
self.gameboards[index].statusButton.show()
""" Tells a Gameboard that it has won and should display accordingly """
def drawWinner(self, index):
self.gameboards[index].drawWinner()
self.ending = 1
""" Updates a Gameboard's Queue's currrent """
def moveInQueue(self, index, current):
self.gameboards[index].queue.move(current)
""" Updates a Gameboard's Queue's selected """
def selectQueue(self, index):
self.gameboards[index].queue.select()
""" Updates a Gameboard's Queue's selected """
def deselectQueue(self, index):
self.gameboards[index].queue.deselect()
""" Updates a Gameboard's GUITree's current """
def moveInTree(self, index, current):
self.gameboards[index].guiTree.move(current)
self.update(index)
""" Updates a Gameboard's GUITree's current """
def rotateTree(self, index, current):
self.gameboards[index].guiTree.current = current
self.update(index)
""" Updates a Gameboard's GUITree's selected """
def selectTree(self, index):
self.gameboards[index].guiTree.select()
""" Updates a Gameboard's GUITree's selected """
def deselectTree(self, index):
self.gameboards[index].guiTree.deselect()
|
8e089aec92d6010b5c764c31e53b42bc3f47f3d3 | 418003839/TallerDeHerramientasComputacionales | /Clases/Programas/Tarea4/Problema1.py | 244 | 3.703125 | 4 | # _*_ coding utf-8 _*_
def euc(num1, num2):
if num2 == 0:
return num1
return euc(num2, num1 % num2)
num1 = int(input("Anota el número menor"))
num2 = int(input("Anota el número mayot"))
print("El MCD es:", euc(num1, num2))
|
b304fbb3269e80704e60f478a0b33b9ae833b856 | Ajay6533-hacker/my_python_tutorial | /firstfrog/stringslicing and method.py | 649 | 4.40625 | 4 | str1 = "this is a string and her sometypes of functions"
# str1 = "this" , "is" , "a " ,"string", "and", "her"," sometypes", "of", "functions "
# str1 = "this ,is, a, string, and, her, sometypes, of, functions "
# str1 = "thisisastringandhersometypesoffunctions"
print(str1[0:8])
# print(str1[0:20:2])
# print(str1[0:])
# print(str1[0::2])
# print(str1[0::-1])
# print(str1[-2:-1])
# print(str1.endswith("function"))
# print(str1.isalnum())
# print(str1.isalpha())
# print(str1.find("her"))
# print(str1.replace("functions","method"))
# print(str1.capitalize())
# print(str1.upper())
# print(str1.lower())
# print(str1.islower()) # boolean return
|
ea972532545ead192edd5d49d0ce1bef22d0ae11 | AndreaBruno97/AdventOfCode2020_python | /day_03/puzzle_1.py | 552 | 3.75 | 4 | ''' Open file '''
filename = 'input.txt'
with open(filename) as f:
content = f.readlines()
trees = 0
current_x = 0
module = len(content[0][:-1])
slope = 3
for line_dirty in content:
''' The last character is \n, so it must be removed '''
line = line_dirty.replace("\n", "")
trees += (line[current_x] == "#")
'''
The next point in the next line is given by (old + 3) mod N,
where N is the length of each line
'''
current_x = (current_x + slope) % module
print("There are " + str(trees) + " trees in the path") |
d1c1b77bd395ae006cde976817c8a8599a96cfce | timtadh/crypt_framework | /qcrypt.py | 2,211 | 3.65625 | 4 | #methods for AES encryption of stream
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
import os
def create_aes_key():
sha256 = SHA256.new()
sha256.update(os.urandom(64))
for x in xrange(5000): sha256.update(sha256.digest())
return sha256.digest()
def pub_decrypt(ciphertext, key):
try:
ciphertext = denormalize(ciphertext)
plaintext = key.decrypt(ciphertext)
#print s
return plaintext
except:
return ciphertext
def pub_encrypt(plaintext, key):
try:
ciphertext = key.encrypt(plaintext, 0)[0]
return normalize(ciphertext)
except:
return plaintext
def _appendSpaces(plaintext):
x = 0
if len(plaintext)%16 != 0:
x = 16 - len(plaintext)%16
plaintext += ' '*x
return plaintext, x
return d
def aes_encrypt(plaintext, key):
plaintext, spaces_added = _appendSpaces(plaintext)
aes = AES.new(key, AES.MODE_CBC)
ciphertext = normalize(aes.encrypt(plaintext))
spaces_added = str(spaces_added)
spaces_added = (2 - len(spaces_added))*'0' + spaces_added
return ciphertext + spaces_added
def aes_decrypt(ciphertext, key):
try:
#print 'aes_decrypt try'
spaces_added = -1*int(ciphertext[-2:])
except:
#print 'aes_decrypt except'
spaces_added = 0
finally:
#print 'aes_decrypt finally'
ciphertext = denormalize(ciphertext[:-2])
aes = AES.new(key, AES.MODE_CBC)
plaintext = aes.decrypt(ciphertext)
#print plaintext
if spaces_added: plaintext = plaintext[:spaces_added]
return plaintext
def normalize(text):
s = ''
for c in text:
c = hex(ord(c))[2:]
c = (2-len(c))*'0'+c
s += c
return s
def denormalize(text):
s = ''
buf = ''
for c in text:
buf += c
if len(buf) == 2:
s += chr(int(buf, 16))
buf = ''
return s
if __name__ == '__main__':
sha256 = SHA256.new()
sha256.update('test')
plaintext = 'this is the plaintext'
ciphertext = encrypt(plaintext, sha256.digest())
print plaintext
print ciphertext
print decrypt(ciphertext, sha256.digest())
|
dca43c14024ec1e5183179e300f0fddca72e112a | palabandladileep/python | /hello.py | 1,529 | 4.1875 | 4 | #question 1 ,2
num1 = int(input("Enter the first number"))
num2 = int(input("enter the second number"))
num3 = int(input("enter the third number"))
def find_largest():
if(num1 > num2):
if(num1 > num3):
largest = num1
else:
largest = num3
elif(num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
find_largest()
#question3 using function
name = input("Enter your name:")
age = int(input("Enter the age:"))
def age():
y = 100-age
x = 2021+y
print("Person will turn 100 years in the year", x)
return
print(age())
#question 6
p1= input("player 1, Enter rock/paper/scissors:")
p2= input("player 2, enter rock/paper/scissors:")
def rock_paper_scissors(player1,player2):
while player1 == player2:
print("Match is tied. play again")
player1 = input("player1, Enter rock/paper/scissors:")
player2 = input("player2, Enter rock/paper/scissors:")
if player1 == "rock" and player2 == "paper":
print("player 2 wins")
elif player1 == "paper" and player2 == "rock":
print("player 1 wins")
elif player1 == "rock" and player2 == "scissors":
print("player 1 wins")
elif player1 == "scissors" and player2 == "rock":
print("player 2 wins")
elif player1 == "paper" and player2 == "scissors":
print("player 2 wins")
elif player1 == "scissors" and player2 == "paper":
print("player 1 wins")
rock_paper_scissors(p1,p2)
|
234478e7dbde6f941d5524029bf5e0ee369fb5f8 | devpilgrin/computer-vision-algorithms | /computer-vision/gauss.py | 1,685 | 3.59375 | 4 | """Apply gaussian filters to an image."""
from __future__ import division, print_function
from scipy import signal
from scipy.ndimage import filters as filters
import numpy as np
import random
from skimage import data
import util
np.random.seed(42)
random.seed(42)
def main():
"""Apply several gaussian filters one by one and plot the results each time."""
img = data.checkerboard()
shapes = [(5, 5), (7, 7), (11, 11), (17, 17), (31, 31)]
sigmas = [0.5, 1.0, 2.0, 4.0, 8.0]
smoothed = []
for shape, sigma in zip(shapes, sigmas):
smoothed = apply_gauss(img, gaussian_kernel(shape, sigma=sigma))
ground_truth = filters.gaussian_filter(img, sigma)
util.plot_images_grayscale(
[img, smoothed, ground_truth],
["Image", "After gauss (sigma=%.1f)" % (sigma), "Ground Truth (scipy)"]
)
def apply_gauss(img, filter_mask):
"""Apply a gaussian filter to an image.
Args:
img The image
filter_mask The filter mask (2D numpy array)
Returns:
Modified image
"""
return signal.correlate(img, filter_mask, mode="same") / np.sum(filter_mask)
# from http://stackoverflow.com/questions/17190649/how-to-obtain-a-gaussian-filter-in-python
def gaussian_kernel(shape=(3, 3), sigma=0.5):
"""
2D gaussian mask - should give the same result as MATLAB's
fspecial('gaussian',[shape],[sigma])
"""
m, n = [(ss-1.)/2. for ss in shape]
y, x = np.ogrid[-m:m+1, -n:n+1]
h = np.exp(-(x*x + y*y) / (2.*sigma*sigma))
h[h < np.finfo(h.dtype).eps*h.max()] = 0
sumh = h.sum()
if sumh != 0:
h /= sumh
return h
if __name__ == "__main__":
main()
|
dc3134099a74c5d207fbc186134c460300816732 | sakshi9401/python-files | /arithmatic operations.py | 252 | 3.90625 | 4 | print("enter two numbers")
n1 = input()
n2 = input()
print("sum of two no, is",int(n1)+int(n2))
print("multiplication of two no. is",int(n1)*int(n2))
print("division of two no. is",int(n1)/int(n2))
print("modulus of two no. is",int(n1)%int(n2))
|
37bb37542f107209e4c7f67e2478ffb9ac92b879 | zzh730/LeetCode | /String/Reverse words in a String.py | 878 | 3.609375 | 4 | __author__ = 'drzzh'
"""
one pass without split();
Trick is to keep track of when the word starts and ends,
use substring(i,j) to append
Watch out for the base case:
1)one word
2)no whitespace in head
3)last whitespace in the result
"""
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
a = len(s)-1
b = 0
result = ""
if ' ' not in s:
return s
while(a>-1):
if s[a] != ' ':
b += 1
elif s[a] == ' ' and b != 0:
result += s[a+1:a+b+1] + ' '
b = 0
if a == 0 and b != 0:
result += s[a:a+b+1]
a-=1
return result[:-1]#如果第一个字符是0,抵消26行的空格,如果不是,抵消29的空格
a = Solution()
print(a.reverseWords("I am King ")) |
0ef6f218241ba83ec96f958100d068fcb979459c | tzhou2018/LeetCode | /arrayAndMatrix/566matrixReshape.py | 770 | 3.8125 | 4 | '''
@Time : 2020/3/8 16:31
@FileName: 566matrixReshape.py
@Author : Solarzhou
@Email : t-zhou@foxmail.com
'''
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
m = len(nums)
n = len(nums[0])
if m * n != r * c:
return nums
res = [[0 for _ in range(c)] for _ in range(r)]
index = 0
for i in range(r):
for j in range(c):
res[i][j] = nums[index // n][index % n]
index += 1
return res
if __name__ == '__main__':
arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print(Solution().matrixReshape(arr, 4, 3))
|
bd21d58371b3ae3d56e10bd7f8d63241e24fa5e8 | leskeylevy/IntelTest1 | /RSA.py | 1,092 | 3.9375 | 4 | " RSA is a public-key encryption asymmetric algorithm and the standard for encrypting information transmitted via the internet. RSA encryption is robust and reliable because it creates a massive bunch of gibberish that frustrates would-be hackers, causing them to expend a lot of time and energy to crack into systems"
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close() |
1cc6ccb0b0827e153134978974d9ba5b01e12663 | saleh99er/LeetcodePractice | /Problem1689/Solution.py | 1,375 | 3.984375 | 4 |
"""
Problem 1689: Partioning into min number of Deci-Binary Numbers
a decimal number is called deci-binary if each of its digits is either 0 or 1
without any leading zeros. For example, 101 and 1100 are deci-binary, while
112 and 3001 are not. Given a string n that represents a positive decimal
integer, return the minimum number of positive deci-binary numbers needed so
that they sum up to n.
Solution: An intuition that helps is given the largest value number in all the
digits is x, you need x deci-binary numbers to have their sum add up to n. So
a linear search that finds the largest value digit and outputs that (which is
at most 9) is all that's needed.
Assumption: minPartitions of n = "0" is 0 and minPartitions of n = "" is 0.
N := chars in string n
Runtime Complexity : O(N)
Space Complexity: O(1)
Runtime: 292ms, faster than 15.84%
Memory: 14.8 MB, less than 35.72%
"""
class Solution:
def minPartitions(self, n: str) -> int:
largest_digit = 0
for digit_str in n:
largest_digit = max(largest_digit,int(digit_str))
if largest_digit == 9:
return largest_digit
return largest_digit
if __name__ == "__main__":
solver = Solution()
assert 3 == solver.minPartitions("32")
assert 8 == solver.minPartitions("82734")
assert 9 == solver.minPartitions("27346209830709182346") |
46c4e070b7c9b2b7cee7441c848cb376b5da254a | JustATester123/learnPython | /dir1/test.py | 789 | 3.5625 | 4 | name=['abc','qwe','rty']
def normalize(name):
def zhuanhuan(s):
return str.upper(s[0]) + str.lower(s[1:])
return list(map(zhuanhuan,name))
print(normalize(name))
from functools import reduce
DIGITS ={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
def str2float(s):
def char2num(c):
return DIGITS[c]
l = s.split(sep='.')
x = len(l[1])
def fn(x,y):
return x*10+y
def fm(x):
if x == 0:
return 1
if x >0:
return 10 * fm(x-1)
return reduce(fn,map(char2num,l[0]))+reduce(fn,map(char2num,l[1]))/fm(len(l[1]))
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
|
d9b0dd26cdc8220242c13c2597d8fa9ce11fdacc | TranLuongBang/HackerRank_Python | /scripts.py | 28,612 | 4.0625 | 4 |
# Tran Luong Bang - bangtranluong195@gmail.com
# ADM - HW1
#---------------------------------------------------------------------------------------------------------------
# Problem 1
# A. Introduction total: 7/7
# 1. Say "Hello, World!" With Python
print("Hello, World!")
# 2. Python If-Else
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 != 0:
print('Weird')
elif n >= 2 and n <= 5:
print('Not Weird')
elif n >= 6 and n <= 20:
print('Weird')
elif n > 20:
print('Not Weird')
# 3. Arithmetic Operators
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a+b)
print(a-b)
print(a*b)
# 4. Python: Division
if __name__ == '__main__':
a = int(input())
b = int(input())
print(int(a/b))
print(a/b)
# 5. Loops
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i*i)
# 6. Write a Function
def is_leap(year):
leap = False
# Write your logic here
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
leap = True
return leap
# 7. Print Function
if __name__ == '__main__':
n = int(input())
for i in range(1,n+1):
print(i, end = '')
# B. DATA TYPES total: 6/6
# 1. List Comprehensions
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
result = [[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if sum([i,j,k]) != n]
print(result)
# 2. Find the Runner-Up Score!
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
# using set to remove duplicated elements.
arr = list(set(arr))
# sort the array
arr = sorted(arr)
print(arr[-2])
# 3. Nested Lists
if __name__ == '__main__':
students = []
for _ in range(int(input())):
name = input()
score = float(input())
students.append([name, score])
score = [student[1] for student in students]
score = sorted(set(score))
second_lowest_score = score[1]
selected_students = [i for i in students if i[1] == second_lowest_score]
selected_students = sorted(selected_students, key = lambda x : x[0])
for i in selected_students:
print(i[0])
# 4. Finding the percentage
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
for key, value in student_marks.items():
if key == query_name:
average = sum(value)/len(value)
print(format(average, '.2f'))
# 5. Lists
if __name__ == '__main__':
N = int(input())
result = []
while(N != 0):
command = input()
clist = command.split()
method = clist[0]
if method == 'insert':
index = int(clist[1])
value = int(clist[2])
result.insert(index, value)
if method == 'print':
print(result)
if method == 'remove':
value = int(clist[1])
result.remove(value)
if method == 'append':
value = int(clist[1])
result.append(value)
if method == 'sort':
result.sort()
if method == 'pop':
result.pop()
if method == 'reverse':
result.reverse()
N = N-1
# 6. Tuples
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
print(hash(tuple(integer_list)))
# C. STRING Total: 14/14
# 1. sWap cASE
def swap_case(s):
return s.swapcase()
# 2. String Split and Join
def split_and_join(line):
line = line.split(' ')
line = '-'.join(line)
return line
# 3. What's Your Name
def print_full_name(a, b):
print("Hello " + a + " " + b + '! You just delved into python.')
# 4. Mutations
def mutate_string(string, position, character):
return string[:position] + character+ string[position+1:]
# 5. Finding a string
def count_substring(string, sub_string):
count = 0
for i in range(0, len(string)):
if string[i:].startswith(sub_string):
count += 1
return count
# 6. String Validators
if __name__ == '__main__':
s = input()
print(any([i.isalnum() for i in s]))
print(any([i.isalpha() for i in s]))
print(any([i.isdigit() for i in s]))
print(any([i.islower() for i in s]))
print(any([i.isupper() for i in s]))
# 7. Text Alignment
#Replace all ______ with rjust, ljust or center.
thickness = int(input()) #This must be an odd number
c = 'H'
#Top Cone
for i in range(thickness):
print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1))
#Top Pillars
for i in range(thickness+1):
print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))
#Middle Belt
for i in range((thickness+1)//2):
print((c*thickness*5).center(thickness*6))
#Bottom Pillars
for i in range(thickness+1):
print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))
#Bottom Cone
for i in range(thickness):
print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6))
# 8. Text Wrap
def wrap(string, max_width):
i = 0
str = ''
while(i < len(string)):
str = str + string[i:i+max_width] +'\n'
i = i+max_width
return str
# 9. Designer Door Mat
s = input()
s = s.split(' ')
n= int(s[0])
m = int(s[1])
for i in range(0,n):
if i % 2 != 0:
a = int((m-i*3)/2)
print('-'*a + '.|.'*i + '-'*a)
print ('-'*int((m-7)/2) + "WELCOME" + '-'*int((m-7)/2))
for i in range(n-1,-1,-1):
if i % 2 != 0:
a = int((m-i*3)/2)
print('-'*a + '.|.'*i + '-'*a)
# 10. String Formatting
def print_formatted(number):
# your code goes here
width = len(str(bin(number))[2:])
for i in range(1, number+1):
d = str(i).rjust(width)
o = oct(i)[2:].rjust(width)
h = hex(i)[2:].upper().rjust(width)
b = bin(i)[2:].rjust(width)
print(d, o, h, b)
# 11. Alphabet Rangoli
def print_rangoli(size):
# your code goes here
s = 'abcdefghijklmnopqrstuvwxyz'
result = []
for j in range(size-1,-1,-1):
n = size -1
h = ''
k = ''
while n >= j:
h += s[n]
n -= 1
k = h + h[:-1][::-1]
result.append('-'.join(k).center(4*(size-1)+1,'-'))
for i in range(size-2, -1,-1):
result.append(result[i])
for i in result:
print(i)
# 12. Capitalize!
def solve(s):
s = [ i.capitalize() for i in s.split(' ')]
s = ' '.join(s)
return s
# 13. The Minion Game
def minion_game(string):
# your code goes here
vowels = 'UEOAI'
s1 = 0
s2 =0
n = len(string)
for i in range(n):
if string[i] in vowels:
s1 += n - i
else: s2 += n -i
if s1 > s2:
print('Kevin', s1)
elif s1 == s2:
print('Draw')
else: print('Stuart', s2)
# 14. Merge the Tools!
def merge_the_tools(string, k):
# your code goes here
n = len(string)
for i in range(0,n, k):
d = dict()
s = string[i:i+k]
m = ''
for j in s:
d[j] = j
for key, value in d.items():
print(key, end = '')
print()
# D. SET total: 13/13
# 1. Introduction to Sets
def average(array):
array = set(array)
n = len(array)
return sum(array)/n
# 2. No Idea!
nm = input()
arr = input().split(' ')
a = set(input().split(' '))
b = set(input().split(' '))
u = a.union(b)
arr = [i for i in arr if i in u]
s = sum(1 if i in a else -1 for i in arr )
print(s)
# 3. Symmetric Difference
m = int(input())
marr = set(map(int,input().split()))
n = int(input())
narr = set(map(int,input().split()))
a = marr.difference(narr)
b = narr.difference(marr)
a = a.union(b)
a=sorted(a)
for i in a:
print(i)
# 4. Set.add()
n = int(input())
s = set()
for i in range(0,n):
country = input()
s.add(country)
print(len(s))
# 5. Set .discard(), .remove(), .pop()
n = int(input())
s = set(map(int, input().split()))
m = int(input())
for i in range(0, m):
text = input()
if text == 'pop':
s.pop()
else:
operation, number = text.split(' ')
number = int(number)
if operation == 'discard':
s.discard(number)
if operation == 'remove':
s.remove(number)
print(sum(s))
# 6. Set .union() Operation
n = int(input())
students_E = set(input().split(' '))
m = int(input())
students_F = set(input().split(' '))
print(len(students_E.union(students_F)))
# 7. Set .intersection() Operation
n = int(input())
students_E = set(input().split(' '))
m = int(input())
students_F = set(input().split(' '))
print(len(students_E.intersection(students_F)))
# 8. Set .difference() Operation
n = int(input())
students_E = set(input().split(' '))
m = int(input())
students_F = set(input().split(' '))
print(len(students_E.difference(students_F)))
# 9. Set .symmetric_difference() Operation
n = int(input())
students_E = set(input().split(' '))
m = int(input())
students_F = set(input().split(' '))
print(len(students_E.symmetric_difference(students_F)))
# 10. Set Mutations
n = int(input())
A = set(map(int, input().split()))
m = int(input())
for i in range(0,m):
operation, k = input().split(' ')
B = set(map(int, input().split()))
if operation == 'intersection_update':
A.intersection_update(B)
elif operation == 'update':
A.update(B)
elif operation == 'symmetric_difference_update':
A.symmetric_difference_update(B)
elif operation == 'difference_update':
A.difference_update(B)
print(sum(A))
# 11. The Captain's Room
n = int(input())
m = list(map(int, input().split()))
s = set(m)
i = int((sum(s)*n - sum(m))/(n-1))
print(i)
# 12. Check Subset
n = int(input())
while(n != 0):
k = input()
A = set(input().split(' '))
l = input()
B = set(input().split(' '))
if len(A.difference(B)) != 0:
print(False)
else: print(True)
n -= 1
# 13. Check Strict Superset
A = set(input().split(' '))
n = int(input())
k = 0
for i in range(0,n):
B = set(input().split(' '))
if len(B.difference(A)) != 0 or len(B) >= len(A):
k = 1
break
if k ==0:
print(True)
else: print(False)
# E. COLLECTIONS total: 8/8
# 1. Collections.Counter()
from collections import Counter
n = int(input())
sizes = map(int,input().split())
sizes = Counter(sizes)
customers = int(input())
s = 0
for customer in range(0,customers):
size, price = map(int, input().split())
if size in sizes.keys() and sizes[size] != 0:
s += price
sizes[size] -= 1
print(s)
# 2. DefaultDict Tutorial
from collections import defaultdict
d = defaultdict(list)
n,m = map(int, input().split())
for i in range(1, n+1):
word = input()
d[word].append(i)
for i in range(0,m):
word = input()
if word not in d.keys():
print(-1)
else:
print(' '.join(map(str,d[word])))
# 3. Collections.namedtuple()
n = int(input())
column = input().split().index('MARKS')
s = 0
for i in range(n):
mark = float(input().split()[column])
s += mark
print("{:.2f}".format(s/n))
# 4. Collections.OrderedDict()
from collections import OrderedDict
n = int(input())
ordered_dict = OrderedDict()
for i in range(n):
item = input().split(' ')
name = ' '.join(item[:-1])
price = int(item[-1])
ordered_dict[name] = int(ordered_dict.get(name,0)) + price
for name, price in ordered_dict.items():
print(name, price)
# 5. Word Order
n = int(input())
dict = {}
for i in range(n):
m = input()
dict[m] = dict.get(m, 0) + 1
print(len(dict))
s = ''
for key, value in dict.items():
s = s + str(value) + " "
print(s)
# 6. Collections.deque()
from collections import deque
n = int(input())
d = deque()
for i in range(n):
text = input().split(' ')
method = text[0]
if len(text) != 1:
value = text[-1]
if method == 'append':
d.append(value)
elif method == 'appendleft':
d.appendleft(value)
elif method == 'pop':
d.pop()
elif method == 'popleft':
d.popleft()
elif method == 'clear':
d.clear()
elif method == 'extend':
d.extend(value)
elif method == 'extendleft':
d.extendleft(value)
elif method == 'count':
d.count(value)
elif method == 'remove':
d.remove(value)
elif method == 'reverse':
d.reverse()
elif method == 'rotate':
d.rotate(value)
print(' '.join(d))
# 7. Company Logo
import math
import os
import random
import re
import sys
from collections import Counter
if __name__ == '__main__':
s = input()
frequent = Counter(s)
y = sorted(frequent.items(), key = lambda x: (-x[1], x[0]))[:3]
for item in y:
print(item[0], item[1])
# 8. Piling Up!
from collections import deque
t = int(input())
for i in range(t):
n = int(input())
sideLength = list(map(int, input().split()))
index = sideLength.index(min(sideLength))
left = sideLength[:index]
right = sideLength[index+1:]
if left == sorted(left, reverse = True) and right == sorted(right):
print('Yes')
else: print('No')
# F. DATE AND TIME total: 2/2
# 1. Calendar Module
import calendar
month, day, year = map(int,input().split(' '))
stt = calendar.weekday(year, month, day)
print(calendar.day_name[stt].upper())
# 2. Time Delta
import math
import os
import random
import re
import sys
from datetime import datetime
# Complete the time_delta function below.
def time_delta(t1, t2):
fm = '%a %d %b %Y %H:%M:%S %z'
t1 = datetime.strptime(t1, fm)
t2 = datetime.strptime(t2, fm)
different = (t1-t2).total_seconds()
return str(abs(int(different)))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
t1 = input()
t2 = input()
delta = time_delta(t1, t2)
fptr.write(delta + '\n')
fptr.close()
# G. EXCEPTIONS total 1/1
# 1. Exception
n = int(input())
for i in range(n):
try:
a,b = input().split(' ')
print(int(a)//int(b))
except ZeroDivisionError as e:
print('Error Code:', e)
except ValueError as e:
print('Error Code:', e)
# H. BUILT-INS total: 3/3
# 1. Zipped!
n, m = map(int, input().split(' '))
X = []
for i in range(m):
A = map(float, input().split(' '))
X.append(A)
Y = zip(*X)
for i in Y:
print(sum(i)/m)
# 2. Athlete Sort
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
k = int(input())
a = sorted(arr, key = lambda x: x[k])
for i in a:
i = map(str, i)
print(' '.join(i))
# 3. ginortS
s = input()
lower = []
upper = []
num_even = []
num_odd = []
for i in range(len(s)):
if s[i].islower():
lower.append(s[i])
elif s[i].isupper():
upper.append(s[i])
elif s[i].isdigit() and int(s[i]) % 2 ==0:
num_even.append(s[i])
elif s[i].isdigit() and int(s[i]) % 2 !=0:
num_odd.append(s[i])
sort = sorted(lower) + sorted(upper) + sorted(num_odd) + sorted(num_even)
print(''.join(sort))
# I. PYTHON FUNCTIONS total 1/1
# 1. Map and Lambda Function
cube = lambda x: x**3
def fibonacci(n):
# return a list of fibonacci numbers
fib = [0, 1]
for i in range(2,n):
fib.append(sum(fib[-2:]))
return fib[:n]
# K. REGEX AND PARSING CHALLENGES total: 17/17
# 1. Detect Floating Point Number
import re
pattern = '^(\+|\-)?[0-9]*\.[0-9]+$'
n = int(input())
for i in range(n):
f = input()
if re.search(pattern, f):
print('True')
else: print('False')
# 2. Re.split()
regex_pattern = r"[,.]" # Do not delete 'r'.
# 3. Group(), Groups() and Groupdict()
import re
s = input()
pattern = r'([A-Za-z0-9])\1+'
n = re.search(pattern,s)
if n:
print(n.group(1))
else: print(-1)
# 4. Re.findall() & Re.finditer()
import re
s = input()
pattern = r'(?<=[qwrtypsdfghjklzxcvbnmQWRTYPSDFGHJKLZXCVBNM ])[ueaoaiUEOAI]{2,}(?=[qwrtypsdfghjklzxcvbnmQWRTYPSDFGHJKLZXCVBNM ])'
result = re.findall(pattern,s)
if result:
for i in result:
print(i)
else: print(-1)
# 5. Re.start() & Re.end()
import re
s= input()
k= input()
pattern = re.compile(k)
n = {}
result = re.search(pattern, s)
if not result:
print((-1,-1))
else:
for i in range(len(s)-len(k)-1):
result = re.search(pattern, s[i:])
n[i+result.start()] = i+result.end()-1
for start, end in n.items():
print('({}, {})'.format(start,end))
# 6. Regex Substitution
import re
pattern1 = r'(?<= )\|\|(?= )'
pattern2 = r'(?<= )\&\&(?= )'
n = int(input())
for i in range(n):
s = input()
result1 = re.sub(pattern1, 'or', s)
result2 = re.sub(pattern2, 'and', result1)
print(result2)
# 7. Validating Roman Numerals
regex_pattern = r'^M{0,3}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$'
# 8. Validating phone numbers
import re
n = int(input())
pattern = r'^[789]\d{9}$'
for i in range(n):
s = input()
match = re.match(pattern,s)
if match:
print('YES')
else: print('NO')
# 9. Validating and Parsing Email Addresse
import re
n = int(input())
pattern = r'<([a-z][a-z0-9-._]+@([a-zA-Z])+\.[a-z]{1,3})>'
for i in range(n):
s = input()
result = re.search(pattern, s)
if result:
print(s)
# 10. Hex Coler Code
import re
n = int(input())
pattern = r'(?<=[ :,])#[0-9a-fA-f]+(?=[^\w])'
for i in range(n):
s = input()
result = re.findall(pattern, s)
if result:
print('\n'.join(i for i in result))
# 11. HTML Parser - Part 1
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print('Start :', tag)
if len(attrs) != 0:
for i in attrs:
print('->', i[0], '>', i[1])
def handle_endtag(self, tag):
print('End :', tag)
def handle_startendtag(self, tag, attrs):
print('Empty :', tag)
if len(attrs) != 0:
for i in attrs:
print('->', i[0], '>', i[1])
parser = MyHTMLParser()
n = int(input())
for i in range(n):
m = input()
parser.feed(m)
# 12. HTML Parse - Part 2
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_comment(self, data):
if '\n' in data:
print('>>> Multi-line Comment')
print(data)
else:
print('>>> Single-line Comment')
print(data)
def handle_data(self, data):
if data != '\n':
print (">>> Data")
print(data)
html = ""
for i in range(int(input())):
html += input().rstrip()
html += '\n'
parser = MyHTMLParser()
parser.feed(html)
parser.close()
# 13. Detect HTML, Tags, Attributes and Attribute Values
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print(tag)
if len(attrs) != 0:
for i in attrs:
print('->', i[0], '>', i[1])
def handle_startendtag(self, tag, attrs):
print(tag)
if len(attrs) != 0:
for i in attrs:
print('->', i[0], '>', i[1])
parser = MyHTMLParser()
n = int(input())
for i in range(n):
m = input()
parser.feed(m)
# 14. Validation UID
import re
n = int(input())
patterns = [r'(.*[A-Z].*){2,}', r'(.*[0-9].*){3,}', r"[A-Za-z0-9]{10}"]
for i in range (n):
s = input()
k = 0
for j in patterns:
if bool(re.search(j,s)) == False:
k = 1
break
if bool(re.search(r'.*(.).*\1', s)):
k = 1
if k == 0:
print('Valid')
else: print('Invalid')
# 15. Validating Credit Card Numbers
import re
from collections import Counter
n = int(input())
pattern = r'^[456][0-9]{3}-?[0-9]{4}-?[0-9]{4}-?[0-9]{4}$'
for i in range(n):
s = input()
l = s.replace('-','')
k = 0
for i in range(10):
if str(i)*4 in l:
k =1
if re.match(pattern, s) and k == 0:
print('Valid')
else: print('Invalid')
# 16. Validating Postal Codes
regex_integer_in_range = r"[1-9][0-9]{5}$"
regex_alternating_repetitive_digit_pair = r"(\d)(?=\d\1)"
# 17. Matrix Script
import math
import os
import random
import re
import sys
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
matrix = []
s = ''
for _ in range(n):
matrix_item = input()
matrix.append([i for i in matrix_item])
for i in range(m):
for arr in matrix:
s += arr[i]
pattern = r'(?<=[a-zA-Z])[!@#$%&\s]+(?=[a-zA-Z])'
print(re.sub(pattern, ' ', s))
# J. XML total: 2/2
# 1. XML 1 - Find the Score
def get_attr_number(node):
# your code goes here
s = 0
for i in node.iter():
s += len(i.items())
return s
# 2. XML 2 - Find the Maximun Depth
maxdepth = 0
def depth(elem, level):
global maxdepth
# your code goes here
level += 1
if level > maxdepth:
maxdepth = level
for child in elem:
depth(child, level)
# K. CLOSURES AND DECORATIONS total :2/2
# 1. Standardize Mobile Number Using Decorators
def wrapper(f):
def fun(l):
# complete the function
number = ['+91 {} {}'.format(i[-10: -5], i[-5:]) for i in l]
return f(number)
return fun
# 2. Decorators 2 - Name Directory
def person_lister(f):
def inner(people):
# complete the function
arr = []
for person in sorted(people, key=lambda x: int(x[-2])):
arr.append(f(person))
return arr
return inner
# L. NUMPY total: 15/15
# 1. Arrays
def arrays(arr):
# complete this function
# use numpy.array
arr = numpy.array(arr, dtype = 'f')
return numpy.flip(arr)
# 2. Shape and Reshape
import numpy
arr = input().strip().split(' ')
arr = numpy.array(arr, dtype = 'int64')
print(numpy.reshape(arr, (3,3)))
# 3. Transpose and Flatten
import numpy
n,m = map(int, input().split(' '))
arr = []
for i in range(n):
arr += input().split(' ')
arr = numpy.array(arr, dtype = 'int64')
arr = numpy.reshape(arr, (n,m))
print(numpy.transpose(arr))
print(arr.flatten())
# 4. Concatenate
import numpy
n, m, p = map(int, input().split(' '))
arr1 = []
arr2 = []
for i in range(n):
arr1 += input().split(' ')
arr1 = numpy.array(arr1, dtype='int64')
arr1 = numpy.reshape(arr1, (n,p))
for i in range(m):
arr2 += input().split(' ')
arr2 = numpy.array(arr2, dtype='int64')
arr2 = numpy.reshape(arr2, (m,p))
print(numpy.concatenate((arr1, arr2), axis = 0))
# 5. Zeros and Omes
import numpy
d = list(map(int, input().strip().split(' ')))
print(numpy.zeros((d), dtype = numpy.int))
print(numpy.ones((d), dtype = numpy.int))
# 6. Eye and Identity
import numpy
n, m = map(int, input().split(' '))
numpy.set_printoptions(sign=' ')
print(numpy.eye(n, m, k=0))
# 7. Array Mathematics
import numpy
n, m = map(int, input().split(' '))
A = numpy.array([input().split() for i in range(n)], dtype = 'int64')
B = numpy.array([input().split() for i in range(n)], dtype = 'int64')
print(A+B)
print(A-B)
print(A*B)
print(A//B)
print(A%B)
print(A**B)
# 8. Floor, Ceil and Rint
import numpy
numpy.set_printoptions(sign=' ')
arr = numpy.array(input().split(' '), dtype = 'f')
print(numpy.floor(arr))
print(numpy.ceil(arr))
print(numpy.rint(arr))
# 9. Sum and Prod
import numpy
n,m = map(int, input().split())
arr = numpy.array([input().split() for i in range(n)], int).reshape(n,m)
print(numpy.prod(numpy.sum(arr, axis = 0)))
# 10. Min and Max
import numpy
n,m = map(int, input().split())
arr = numpy.array([input().split() for i in range(n)], int)
arr_min = numpy.min(arr, axis=1)
print(numpy.max(arr_min))
# 11. Mena, Var, and Std
import numpy
#https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html
numpy.set_printoptions(legacy='1.13')
n,m = map(int, input().split())
arr = numpy.array([input().split() for i in range(n)], int)
print(numpy.mean(arr, axis=1))
print(numpy.var(arr, axis=0))
print(numpy.std(arr))
# 12. Dot and Cross
import numpy
n = int(input())
A = numpy.array([input().split() for i in range(n)], int)
B = numpy.array([input().split() for i in range(n)], int)
print(A.dot(B))
# 13. Inner and Outer
import numpy
A = numpy.array(input().split(), int)
B = numpy.array(input().split(), int)
print(numpy.inner(A,B))
print(numpy.outer(A,B))
# 14. Polynomials
import numpy
cof = numpy.array(input().split(), float)
x = int(input())
print(numpy.polyval(cof,x))
# 15. Linear Algebra
import numpy
# https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html
numpy.set_printoptions(legacy='1.13')
n = int(input())
arr = numpy.array([input().split() for i in range(n)], float)
print(numpy.linalg.det(arr))
# ----------------------------------------------------------------------------------------------------
# Promblem 2 total 6/6
# 1. Birthday Cake Candels
import math
import os
import random
import re
import sys
from collections import Counter
def birthdayCakeCandles(candles):
# Write your code here
candles = sorted(candles)
counter = Counter(candles)
return counter[candles[-1]]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
candles_count = int(input().strip())
candles = list(map(int, input().rstrip().split()))
result = birthdayCakeCandles(candles)
fptr.write(str(result) + '\n')
fptr.close()
# 2. Number Line Jumps
import math
import os
import random
import re
import sys
# Complete the kangaroo function below.
def kangaroo(x1, v1, x2, v2):
if v1 > v2 and (x2 - x1) % (v1 - v2) == 0:
return 'YES'
return 'NO'
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
x1V1X2V2 = input().split()
x1 = int(x1V1X2V2[0])
v1 = int(x1V1X2V2[1])
x2 = int(x1V1X2V2[2])
v2 = int(x1V1X2V2[3])
result = kangaroo(x1, v1, x2, v2)
fptr.write(result + '\n')
fptr.close()
# 3. Viral Advertising
import math
import os
import random
import re
import sys
def viralAdvertising(n):
shared = 5
liked = 2
cul = 2
while(n-1 > 0):
shared = 3*int(shared/2)
liked = int(shared/2)
cul += liked
n -= 1
return cul
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
result = viralAdvertising(n)
fptr.write(str(result) + '\n')
fptr.close()
# 4. Recursive Digit Sum
import math
import os
import random
import re
import sys
def superDigit(n, k):
s = sum([int(i) for i in str(n)])*k
if s < 10:
return s
else: return superDigit(s,1)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nk = input().split()
n = nk[0]
k = int(nk[1])
result = superDigit(n, k)
fptr.write(str(result) + '\n')
fptr.close()
# 5. Insertion Sort - Part 1
import math
import os
import random
import re
import sys
def insertionSort1(n, arr):
s = arr[-1]
for i in range(n-1, 0, -1):
if s < arr[i-1] :
arr[i] = arr[i-1]
print(' '.join([str(i) for i in arr]))
if i-1 ==0:
arr[0] = s
print(' '.join([str(i) for i in arr]))
if s > arr[i-1]:
arr[i] = s
print(' '.join([str(i) for i in arr]))
break
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
insertionSort1(n, arr)
# 6. Insertion Sort - Part 2
import math
import os
import random
import re
import sys
def insertionSort2(n, arr):
for i in range(1, n):
s = arr[i]
j = i-1
while j >= 0 and s < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = s
print(' '.join([str(i) for i in arr]))
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
insertionSort2(n, arr)
|
7fa5c5f9392834557627d91c898fe1abc2a257da | andrilor/riskFactors | /hw6/riskFactors.py | 1,695 | 3.53125 | 4 | import csv
import string
def openfile(file_name):
try:
ls = []
with open(file_name, newline="", encoding='utf-8') as dataFile:
readCSV = csv.reader(dataFile)
for row in readCSV:
ls.append(row)
return ls
except FileNotFoundError:
print("Cannot find file " + file_name)
def punctuation_test(value):
punct = list(string.punctuation)
placeholder = ""
if value[-1] == punct:
placeholder = str(value[:-1])
placeholder = float(placeholder[:-1])
else:
placeholder = value
print(placeholder)
print(value[:-1])
return placeholder
def find_min(file_name, num):
min_num = 99999999
min_num_state = ""
for i in file_name[2:]:
placeholder1 = i[num]
placeholder = punctuation_test(placeholder1)
int1 = float(placeholder)
str2 = i[0]
if int1 < min_num:
min_num = int1
min_num_state = str2
return min_num, min_num_state
def find_Max(file_name, num):
max_num = 0
max_num_state = ""
for i in file_name[2:]:
placeholder1 = i[num]
int1 = float(placeholder1)
str2 = i[0]
if int1 > max_num:
max_num = int1
max_num_state = str2
return max_num, max_num_state
filename = input("Enter filename containing csv data: ")
Name = openfile(filename)
num, state = find_min(Name, 11)
print(one)
print(two)
#one, two = find_Max(Name, 11)
#print(one)
#print(two)
#print(Name[0])
#print(Name[1][1])
#print(Name[1][5])
#print(Name[1][7])
#print(Name[1][11][:-1])
#print(Name[1][13][:-1])
#str1 = ''.join(str(i) for i in mylist)
#int1 = float(str1)
|
1ab1466c6e8e8f21c74b4b994e063e2bca41ef56 | hongdonghyun/Project | /09.function/arguments.py | 531 | 3.96875 | 4 | def make_student(name,age,gender):
return {
'name' : name,
'age' : age,
'gender' : gender
}
def print_student(student):
for key,value in student.items():
print('{} : {}'.format(key,value))
s1 = make_student('hongdonghyun',27,"남성")
print_student(s1)
# make_student를 키워드 인자로 호출한 결과를 s2에 할당
#키워드 순서는 age,name gender순으로 주어짐
s2 = make_student(age=27,name='hongdonghyun',gender='남성')
print_student(s2)
|
a1512417f04def396e74338274538865a4b31887 | lawson0628/python200804 | /day2.2.py | 206 | 3.59375 | 4 | n=int(input('請輸入一個數來判別它是否為質數'))
c=2
while c<n:
if n%c==0:
print('不是質數')
break
c+=1
if c==n:
print('是質數')
|
46bb20a0e813834357687f4efc537e8238df9d20 | klknet/geeks4geeks | /algorithm/searchsort/linklist_merge_sort.py | 2,157 | 4.125 | 4 | # Merge sort for doubly link list
class LinkedList:
def __init__(self):
self.head = None
def push(self, v):
node = Node(v, None, self.head)
if self.head is not None:
self.head.prev = node
self.head = node
def merge_sort(self, temp_head):
if temp_head is None or temp_head.next is None:
return temp_head
second = self.split(temp_head)
temp_head = self.merge_sort(temp_head)
second = self.merge_sort(second)
return self.merge(temp_head, second)
# Select the smaller node of the two nodes, place the node as first node, recursive do tail either of is none
def merge(self, first, second):
if first is None:
return second
if second is None:
return first
if first.v < second.v:
first.next = self.merge(first.next, second)
first.next.prev = first
first.prev = None
return first
else:
second.next = self.merge(first, second.next)
second.next.prev = second
second.prev = None
return second
def split(self, node):
slow = fast = node
while True:
if fast.next is None:
break
if fast.next.next is None:
break
fast = fast.next.next
slow = slow.next
temp = slow.next
slow.next = None
return temp
def print_list(self, node):
temp = node
# Forward traversal using next pointers
while node is not None:
print(node.v, end=' ')
temp = node
node = node.next
print()
while temp is not None:
print(temp.v, end=' ')
temp = temp.prev
print()
class Node:
def __init__(self, v, prev, next):
self.v = v
self.prev = prev
self.next = next
if __name__ == '__main__':
l = LinkedList()
l.push(12)
l.push(14)
l.push(10)
l.push(18)
l.push(2)
l.print_list(l.head)
l.head = l.merge_sort(l.head)
l.print_list(l.head)
|
c1363ba5759147172d52336d062cc7fed12b170e | kinow/python-dependency-injector | /examples/providers/overriding_simple.py | 783 | 3.796875 | 4 | """Simple providers overriding example."""
import dependency_injector.providers as providers
class User:
"""Example class User."""
# Users factory:
users_factory = providers.Factory(User)
# Creating several User objects:
user1 = users_factory()
user2 = users_factory()
# Making some asserts:
assert user1 is not user2
assert isinstance(user1, User) and isinstance(user2, User)
# Extending User:
class SuperUser(User):
"""Example class SuperUser."""
# Overriding users factory:
users_factory.override(providers.Factory(SuperUser))
# Creating some more User objects using overridden users factory:
user3 = users_factory()
user4 = users_factory()
# Making some asserts:
assert user4 is not user3
assert isinstance(user3, SuperUser) and isinstance(user4, SuperUser)
|
164bcc66f31595d93c63b1acdfa439aa3cfd09fb | neesh7/Neesh_Python_Dictionaries | /dictionary3.py | 1,418 | 4.8125 | 5 | # like key method we can also use value method in order to get a list of values
fruit = {"Orange": "a sweet, oranges, citrus fruit",
"grapes": "a small, sweet fruit, grows in bunches",
"Mango": "Nice shape,Beautiful, so juicy",
"lemon": "citrus fruit , so juicy , so sour, women likes lemon",
"kivy": "it's cute but it's not from new zeland"
}
for val in fruit.values():
print(val)
# it prints the list of values but it is not advisable we can do it much efficiently by using key method.
print("_________________________________________")
for key in fruit:
print(fruit[key])
# we can do other basic things like
print(fruit.keys())
print(fruit.values())
# both of these line of code will return list of keys and values i.e.., dict_keys and dict_values
# and both together is called view objects
fruit_keys = fruit.keys()
print(fruit_keys)
fruit["tomato"] = "not nice to eat with ice cream"
print(fruit_keys)
print("__"*80)
print(fruit)
print(fruit.items())
# Extracting tuple from this fruit.items
print("#"*80)
f_tuples = tuple(fruit) # This will give only tuple of our keys
print(f_tuples)
f_tuples1 = tuple(fruit.items()) # This will give our tuple of keys and values altogether called as view object.
print(f_tuples1)
# iterating over tuples
print("#"*80)
for snack in f_tuples1:
items, description = snack
print(items + " is " + description)
|
abc835c96cfb6837d3871ffb004535c9bebaa1eb | js837/project-euler | /1-100/30/digits.py | 254 | 3.734375 | 4 | def isPower(n,power):
t=n
tot=0
while t>0:
dig=t%10
tot=tot+dig**power
#print tot
t=(t-dig)//10
if n==tot:
return True
else:
return False
sum=0
for n in xrange(10,1000000):
if isPower(n,5):
sum=sum+n
print sum
|
e0195581775916fa9a1e57f130f2989872d3f305 | greeshmasunil10/Word-Guessing-Game | /guess.py | 4,619 | 3.703125 | 4 | '''
Created on May 19, 2019
@author: Greeshma
'''
from msvcrt import getch
class guess(object):
def __init__(self):
self.gameobjects=[]
def _newgame(self):
self.gobj= game()
base=stringDatabase()
base._readwords()
self.gameword= base._loadword()
self.gobj._setword(self.gameword)
print('')
self.found='----'
print ("** The great guessing game **")
print('Current Guess: ----')
self._greet()
def _greet(self):
print('')
print ('g = guess, t = tell me, l for a letter, and q to quit')
self.inp = input()
if self.inp == 'g':
word= input('Enter the guessed word:')
if word==self.gameword:
print("You guessed the word!")
self.gobj._setstatus("Success")
self._storegame()
else :
self.gobj._incbadguess()
self._greet()
if self.inp == 't':
print('The word was:',self.gameword)
self.gobj._setstatus("Gave Up")
self._storegame()
if self.inp == 'l':
print('Enter a letter:')
self.letter=input()
self._guessletter()
if self.inp == 'q':
print('')
print("Game over")
self.gameobjects.append(self.gobj)
# self.gameobjects= self.gameobjects+ self.gobj
self._results()
else:
self._greet()
def _guessletter(self):
tempword=self.gameword
if(self.letter in self.gameword) :
count=0
while self.letter in tempword:
index=tempword.find(self.letter)
self.found = self.found[:index]+self.letter+self.found[index+1:]
tempword=tempword[:index]+'*'+tempword[index+1:]
count=count+1
print("You found",count,"letters")
print("Current guess:",self.found)
if '-' not in self.found:
print("You have guessed the word!")
self.gobj._setstatus("Success")
self._storegame()
else :
print('Wrong guess')
self.gobj._incmissed()
self._greet()
def _storegame(self):
input('Press any key for new game')
self.gameobjects.append(self.gobj)
# self.gameobjects= self.gameobjects+ self.gobj
for x in self.gameobjects :
print('gameobj',x.word)
self._newgame()
def _results(self):
# print("size:",len(self.gameobjects))
print('%-12s%-12s%-12s%-12s%-12s%-12s' %('Game', 'Word','Status','Bad Guesses','Missed Letters','Score') )
count=1
for x in self.gameobjects:
print('%-12s%-12s%-12s%-12s%-12s%-12s' % (count,x._retword(),x._retstatus(),x._retbadguess(),x._retmissed(),x._retscore()) )
count= count+1
class stringDatabase(object):
def _readwords(self):
file= open("four_letters.txt","r")
self.wordlist=[]
import re
for line in file:
word=re.split('\\s|\n|,',line)
self.wordlist+= word
for x in self.wordlist:
if len(x)==0:
self.wordlist.remove(x)
#`print(self.wordlist)
self.no_of_words= len(self.wordlist)
def _loadword(self):
import random
self.ourword=self.wordlist[random.randint(0,self.no_of_words)]
print(self.ourword)
return self.ourword
class game(object):
def __init__(self):
self.badguess=0
self.missed=0
self.score=0
self.word=""
self.gamestatus='Gave Up'
def _setword(self,par):
self.word=par
def _retword(self):
return self.word
def _setstatus(self,par):
self.gamestatus=par
def _retstatus(self):
return self.gamestatus
def _incbadguess(self):
self.badguess= self.badguess+1
def _retbadguess(self):
return self.badguess
def _incmissed(self):
self.missed = self.missed+1
def _retmissed(self):
return self.missed
def _setscore(self,par):
self.score=par
def _retscore(self):
return self.score
menu= guess()
menu._newgame() |
497bf3093130858b422dbb8040baa1c7c11a8e69 | coremedy/Python-Algorithms-DataStructure | /Python-Algorithms-DataStructure/src/general_problems/string/count_unique_words.py | 808 | 3.828125 | 4 | '''
Created on 2014-12-13
Copyright info: The code here comes, directly or indirectly, from Mari Wahl and her great Python book.
I'm not the original owner of the code.
Thanks Mari for her great work!
'''
import string
def count_unique_word(file_name):
words = dict()
strip = string.whitespace + string.punctuation + string.digits + '\'"`'
with open(file_name) as file:
for line in file:
for word in line.lower().split():
word = word.strip(strip)
if len(word) > 2:
words[word] = words.get(word, 0) + 1
for word in sorted(words.keys()):
print('{0} occurred {1} times'.format(word, words[word]))
if __name__ == '__main__':
count_unique_word('C:\\test.txt') |
1d52f2b34bba51ae04f633b2f0df658c4e7475ab | angelorohit/tictactoe_python | /game/game_board.py | 2,606 | 3.59375 | 4 | from typing import Optional
import numpy as np
from game.player import Player
class GameBoard:
def __init__(self, size: int = 3):
self.empty_cell_symbol = '-'
self.clear(size)
def gather_board_size(self):
size = input(
'Enter a game board size between 3 and 9 (inclusive): ').strip()
if size.isdigit() and int(size) >= 3 and int(size) <= 9:
self.clear(int(size))
else:
self.clear(size=3)
print(
f'The game board size must be between 3 and 9 (inclusive). Defaulting to 3')
def clear(self, size: int) -> None:
self.size = size
self.grid = np.empty(shape=(size, size), dtype=Player)
def render(self) -> str:
# Print all the column labels
render_result = ' '
col_start_ascii = ord('A')
for col_ascii in range(col_start_ascii, col_start_ascii + self.size):
render_result += f'{chr(col_ascii)} '
render_result += '\n'
# Print row labels along with cells for each row
row_label = 1
for row in self.grid:
render_result += f'{row_label} | '
for player in row:
render_result += f'{self.empty_cell_symbol if player == None else player.symbol} | '
render_result += '\n'
row_label += 1
return render_result
def make_player_move(self, row: int, col: int, player: Player) -> Optional[Player]:
existing_player = self.grid[row][col]
if not existing_player:
self.grid[row][col] = player
return existing_player
def check_win_state(self) -> (Optional[Player], bool):
all_items_same = (lambda items: all(
item and item == items[0] for item in items))
# Make transposed matrix of grid to check columns
transposed_grid = np.transpose(self.grid)
for pos in range(0, self.size):
# Check rows
if all_items_same(self.grid[pos]):
return self.grid[pos][0], False
# Check columns
if all_items_same(transposed_grid[pos]):
return transposed_grid[pos][0], False
left_to_right_diagonal = np.diagonal(self.grid)
if all_items_same(left_to_right_diagonal):
return left_to_right_diagonal[0], False
right_to_left_diagonal = np.diagonal(np.fliplr(self.grid))
if all_items_same(right_to_left_diagonal):
return right_to_left_diagonal[0], False
is_draw = np.all(self.grid != None)
return None, is_draw
|
2f71c033d7132a203e3017effce9558c636c0836 | mdezylva/coursera | /machine-learning-ex1/python/computeCost.py | 309 | 3.828125 | 4 | def compute_cost(X,y,theta):
'''
Compute cost for linear regression
J = COMPUTECOST(X, y, theta) computes the cost of using theta as the parameter for linear regression to fit the data points in X and y
'''
# Initialise some useful values
m = length(y)
h_theta = X*theta
|
04896f127475d2054d644634a2e5519daa1bdab2 | ilia-makhonin/python-simple-example | /python-math-master/power_recurs.py | 127 | 3.578125 | 4 | def power_recurs(num, pow):
if pow == 1:
return num
result = num * power_recurs(num, pow - 1)
return result |
388570282788ce6ff456a70e35d263b94cb7af89 | wliu24/creative-cooking | /ingredients-image-detection/ingredients-prediction-with-preprocessing.py | 4,138 | 3.734375 | 4 | #!/usr/bin/env python3
# Making single image predictions
# use: python3 (y or n for using preprocessing) file_path
def preprocess_background(input_img):
'''
This function preprocesses an image based on cv2.
It tries to remove the background of an image.
The intention is to make then prediction easier for the model.
Input:
- Image object
Output:
- Preprocessed image
Source: https://stackoverflow.com/questions/29313667/how-do-i-remove-the-background-from-this-kind-of-image
'''
import numpy as np
import cv2
# Parameters
BLUR = 21
CANNY_THRESH_1 = 10
CANNY_THRESH_2 = 200
MASK_DILATE_ITER = 10
MASK_ERODE_ITER = 10
MASK_COLOR = (0.0,0.0,1.0) # In BGR format
image_size = (100, 100) # width and height of the used images
input_shape = (100, 100, 3)
# Convert image
img = (input_img*255).astype(np.uint8)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Edge detection
edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)
edges = cv2.dilate(edges, None)
edges = cv2.erode(edges, None)
contour_info = []
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
for c in contours:
contour_info.append((
c,
cv2.isContourConvex(c),
cv2.contourArea(c),
))
contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)
max_contour = contour_info[0]
# Create empty mask, draw filled polygon on it corresponding to largest contour
# Mask is black, polygon is white
mask = np.zeros(edges.shape)
cv2.fillConvexPoly(mask, max_contour[0], (255))
# Smooth mask, then blur it
mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)
mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)
mask_stack = np.dstack([mask]*3)
# Blend masked img into MASK_COLOR background
mask_stack = mask_stack.astype('float32') / 255.0 # Use float matrices,
img = img.astype('float32') / 255.0 # for easy blending
masked = (mask_stack * img) + ((1-mask_stack) * MASK_COLOR) # Blend
masked = (masked * 255).astype('uint8') # Convert back to 8-bit
image = cv2.resize(masked, image_size)
image = np.reshape(image, input_shape)
return image
def predict_image(label_file='/home/miber/creative-cooking/labels.txt', model_path='/home/miber/creative-cooking/ingredients_training_output_files/ingredients_detection_model/model.h5'):
'''
Making a single image prediction. Image path and model path are required.
'''
# load model
model = load_model(model_path)
# load image
image_size = (100, 100)
input_shape = (1, 100, 100, 3)
image = str(sys.argv[2])
image = cv2.imread(image)
if str(sys.argv[1]) == 'y':
image = preprocess_background(image)
image = cv2.resize(image, image_size)
image = np.reshape(image, input_shape)
# make prediction
learning_rate = 0.1
optimizer = Adadelta(lr=learning_rate)
model.compile(optimizer=optimizer, loss="sparse_categorical_crossentropy", metrics=["accuracy"])
prediction = model.predict(image)
# format prediction and yield top 5 results with prob
label_file = label_file
with open(label_file, "r") as f:
labels = [x.rstrip('\n') for x in f.readlines()]
for ingredient, prob in sorted(list(zip(labels, prediction[0])), key = lambda x: -x[1])[:5]:
print('{}: {:.2f}%'.format(ingredient.replace('_'," "), round(prob, 4) * 100))
if __name__ == '__main__':
# Libraries
import os
# No messages
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import sys
stderr = sys.stderr
sys.stderr = open(os.devnull, 'w')
import keras
sys.stderr = stderr
from keras.models import load_model
from keras.optimizers import Adadelta
import cv2
import numpy as np
# Predict image
predict_image() |
3f1aa6741fc6e9b978eb57c53ca507827e44fc0a | luixeiner/semana-8 | /problema8.py | 170 | 3.71875 | 4 | num = 0
suma = 0
n = int(input("ingrese un numero"))
for i in range(1, n):
if num % i ==0:
suma = num
print ("perfecto")
else:
print("no perfecto")
|
d094983a5e2e43a42bd7ef84b5109c227e1a0e37 | juraj80/myPythonCookbook | /days/10-12-testing-your-code-with-pytest/sample_tests/107_filter_numbers_with_list_comprehension/test_list_comprehension.py | 507 | 3.515625 | 4 | from list_comprehension import filter_positive_even_numbers
def test_filter_positive_and_negatives():
numbers = list(range(-10,11))
expected = [2, 4, 6, 8, 10]
actual = filter_positive_even_numbers(numbers)
assert expected == actual
def test_filter_only_positives():
numbers = [2, 4, 51, 44, 47, 10]
assert filter_positive_even_numbers(numbers) == [2,4,44,10]
def test_filter_zero_and_negatives():
numbers = [0,-1,-3,-5]
assert filter_positive_even_numbers(numbers) == []
|
1ebc27af1ae880611a317b0641d0b01682ed0d97 | loumatheu/ExerciciosdePython | /Mundo 1/Exercicio19.py | 937 | 3.6875 | 4 | from random import choice
import emoji
cores = {'azul':'\033[1;34m','verde':'\033[1;32m','semestilo':'\033[m', 'vermelho':'\033[1;31m',
'lilas':'\033[1;35m', 'amarelo':'\033[1;33m', 'verdepiscina':'\033[1;36m'}
print(f"""{cores['azul']}====================================================================
CHALLENGE 19
===================================================================={cores['semestilo']}""")
print(emoji.emojize(':star::star::star::star: SORTEIO :star::star::star::star:', use_aliases=True))
print('Digite o número dos quatro alunos a serem sorteados para apagar o quadro.')
a1 = str(input('Digite o nome do primeiro aluno: '))
a2 = str(input('Digite o nome do segundo aluno: '))
a3 = str(input('Digite o nome do terceiro aluno: '))
a4 = str(input('Digite o nome do quarto aluno: '))
alunos = [a1, a2, a3, a4]
print(f'O aluno que apagará o quadro será: {choice(alunos)}')
|
572e3360307f2fe1290a6903eb1642352ea7976e | connordittmar/avoidance | /avoidance/logic_motion.py | 2,904 | 3.6875 | 4 | from bin import gpsutils
from math import sqrt, sin, cos, atan2
def diff_dist(obj1,obj2):
if len(obj1)==2:
calc_dist = sqrt( abs(obj1[0]-obj2[0])**2 + abs(obj1[1]-obj2[1])**2 )
return calc_dist
elif len(obj1)==3:
calc_dist = sqrt( abs(obj1[0]-obj2[0])**2 + abs(obj1[1]-obj2[1])**2 + abs(obj1[2]-obj2[2])**2)
return calc_dist
else:
raise "Input Must be two or three element float lists."
def check_for_obstacle(position_of_obstacle,obstacle_radius,point=[0,0,0]):
if diff_dist(position_of_obstacle,point) < obstacle_radius:
return True
else:
return False
def check_for_danger(obstacles):
for obstacle in obstacles: #enu coordinates of obstacles
if check_for_obstacle(obstacle.enu,obstacle.radius)==True:
return True
return False
def circle_proj(obstacles,time,dr_point,safety_heading):
heading_to_dr_point= atan2(obstacles.enu[1]-dr_point[1],obstacles.enu[0]-dr_point[0])
if heading_to_dr_point < safety_heading:
i=0.2
while(1):
sym_enu=(obstacle.enu[0]+obstacles.speed[0]*3.0*i,obstacle_enu[1]+obstacles.speed[1]*3.0*i)
radius=obstacle.radius*(1.0+i)
if check_for_obstacle(sym_enu,radius,dr_point) == True:
return True
break
if i==1.0
break
i=i+0.2
return False
def check_for_object_ext(obstacle,time,dr_point):
if diff_dist(obstacle.enu,dr_point) < obstacle.radius:
return True
if cicle_proj(obstacles,dr_point,safety_heading) == True:
return True
return False
def find_wp_multi(current_position, position_of_obstacle,obstacle_radius,position_desired,step_size):
heading = atan2(position_desired[1]-current_position[1],position_desired[0]-current_position[0])
x = cos(heading)*step_size + current_position[0]
y = sin(heading)*step_size + current_position[1]
dr_point = [x, y, 0]
def find_wp(current_position,position_of_obstacle,obstacle_radius,position_desired,step_size):
heading = atan2(position_desired[1]-current_position[1],position_desired[0]-current_position[0])
x = cos(heading)*step_size + current_position[0]
y = sin(heading)*step_size + current_position[1]
dr_point = [x, y, 0]
while(check_for_obstacle(position_of_obstacle,obstacle_radius,dr_point)==True):
if atan2(position_of_obstacle[1]-current_position[1],position_of_obstacle[0]-current_position[0]) < heading:
heading += 0.085
dr_point = [cos(heading)*50+current_position[0], sin(heading)*50+current_position[1], 0]
else:
heading -= 0.085
dr_point = [cos(heading)*50+current_position[0], sin(heading)*50+current_position[1], 0]
if diff_dist(current_position,position_desired)<step_size:
dr_point = position_desired
return dr_point
|
dc8bdc5cd8ef7aab8d4d154fa62197fb7f0fddc4 | PytlaaS/Python-Project-Spring-2019 | /test 4.py | 1,508 | 3.703125 | 4 | from random import choices
def main():
print("Bienvenue au Jeu du juste prix, vou connaisez le concept")
print("Choisissez un chiffre compris entre 0 et 1000")
print("Une fois que Gustave aura choisie, vous pourrez essayer de trouver le meme que lui")
number = list(range(0, 1001))
Gustav = choices(number)
Gustave = Gustav[0]
print("Gustave a fais son choix a ton tour")
trying = 1
Pedro = int(input("C'est a toi de choisir, que choisis tu ?"))
if Pedro == Gustave:
print("Bravo Pedro El Chico tu est le maitre de ce jeu")
else:
while Pedro != Gustave:
print("Ouhh Pas loiiin")
if Pedro < Gustave:
print("C'est plus mon Garcon")
else:
print("C'est moins mon Garcon")
trying += 1
Pedro = int(input("Alors tu dirais quoi cette fois ci?"))
print("Bravo Pedro tu sais maintenant combien de briques il te faut pour ériger ton mur")
print("Tu as effectué {} essaies avant d'arrivé au juste prix".format(trying))
yo = trying
x = 1
t = 1000
k = 0.999
while yo != 0:
if yo > 1:
yo = yo - 1
x = x * k
t = t - 1
k = (1 - (1 / t))
else:
yo = yo - 1
x = x * (1 - k)
x = x * 100
print("Tu avais " + str(x) + " % de chance de trouver en {} essais.".format(trying))
if __name__ == '__main__':
main()
|
1a6b9a8f5b07cf710026ffef89e4f6aacbc546ca | rexhzhang/LeetCodeProbelms | /TwoPointers/TwoSumUniquePairs.py | 1,252 | 3.953125 | 4 | """
Given an array of integers, find how many unique pairs in the array such that their sum is equal to a specific target
number. Please return the number of pairs.
Have you met this question in a real interview? Yes
Example
Given nums = [1,1,2,45,46,46], target = 47
return 2
1 + 46 = 47
2 + 45 = 47
"""
class Solution:
# @param nums {int[]} an array of integer
# @param target {int} an integer
# @return {int} an integer
def twoSum6(self, nums, target):
# Write your code here
if not nums or len(nums) < 2:
return 0
left, right = 0, len(nums) - 1
counter = 0
nums.sort()
while left < right:
value = nums[left] + nums[right]
if value == target:
counter += 1
left += 1
right -= 1
# while 要卸载 if 里
while (left < right) and (nums[left] == nums[left - 1]):
left += 1
while (left < right) and (nums[right] == nums[right + 1]):
right -= 1
elif value > target:
right -= 1
else:
left += 1
return counter |
80df1078bb9763c68e4b01366171cea80168632c | Argton/ProblemsFromWebsites | /CyclicRotation.py | 558 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 23 22:35:46 2018
This programs takes a list A an rotates every element by one position,
K times.
@author: Anton
"""
def CyclRot(A, K):
if len(A)==0 or K==0:
return A
else:
for nbrOfTurns in range(0, K):
tempArr=[]
tempArr.append(A[len(A)-1])
for index in range(0, len(A)-1):
tempArr.append(A[index])
A.clear()
A=tempArr.copy()
return tempArr
A=[1,2,3,4,5]
K=3
print(CyclRot(A, K)) |
ebae29093f8063cbfd72d5fe813c00e468ae9355 | stephenjayakar/problems | /reverseWords.py | 927 | 4.125 | 4 | # reverses the words in the string in place
def reverseWords(s: str) -> str:
s = list(s)
N = len(s)
# first reverse string's characters
i, j = 0, N - 1
reverseSubstring(s, i, j)
i, j = 0, 0
reverse = False
# for each word, reverse it
for index in range(N):
if s[index] == ' ' and reverse:
j = index - 1
reverseSubstring(s, i, j)
reverse = False
elif index == N - 1 and reverse:
j = index
reverseSubstring(s, i, j)
reverse = False
elif not reverse and s[index] != ' ':
reverse = True
i = index
return "".join(s)
def reverseSubstring(s, i, j):
while i < j:
temp = s[i]
s[i] = s[j]
s[j] = temp
i += 1
j -= 1
string = "hello guys my name is stephen jayakar"
print(string)
string = reverseWords(string)
print(string)
|
01d1925672fb5a4604e4ef5e6a4c2fea85420979 | wasimashraf88/Python-tutorial | /argr_kwargs.py | 922 | 3.921875 | 4 | # # Arbitrary Arguments or *args
# def my_func(*kids):
# print("The youngest child is:",kids[3])
# my_func("Emil", "Tobias","Sara","Nib")
# # Keyword Arguments
# #You can also send arguments with the key = value syntax.This way the order of the arguments does not matter.
# def my_func1(child1,child2,child3):
# print("The yougest child is:" + child2)
# my_func1(child1="Harry",child2="Merry",child3="Carry")
# # Arbitrary Keyword Arguments, **kwargs
# # If you do not know how many keyword arguments that will be passed into your function, add two asterisk: **
# def my_func2(**kids):
# print("His last name is " + kids["lname"])
# my_func2(fname = "Asim", lname = "Irshad")
def concatenate(**kwargs):
new = " "
# Iterating over the Python kwargs dictionary
for arg in kwargs.values():
new += arg
return new
print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))
|
6a9325dbc0099b786556cac12e463220f08be518 | bi0kemika21/tweet | /app/loy.py | 500 | 3.609375 | 4 | from datetime import datetime
from apscheduler.scheduler import Scheduler
import time
# Start the scheduler
sched = Scheduler()
sched.start()
@sched.interval_schedule(seconds=5)
def job_function():
return fun()
def fun():
print "Loloy"
# Schedule job_function to be called every two hours
#sched.add_interval_job(fun, hours=.001)
# The same as before, but start after a certain time point
#sched.add_interval_job(job_function, hours=.01, start_date='2014-03-26 17:01')
while True:
pass
|
f73ce622037d91e15b1d9068928b5d6273d86dd2 | Mark-Zhang-007/python_from_Liao | /exercise/函数式编程/高阶函数/mapreduce.py | 1,263 | 3.5 | 4 | # -*- coding: utf-8 -*-
from functools import reduce
def normalize(name):
name = str.lower(name)
return name.capitalize()
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
def prod(L):
return reduce(lambda x, y: x * y, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
DIGITS = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4,
"5": 5, "6": 6, "7": 7, "8": 8, "9": 9}
def str2float(s):
length = len(s)
def finddot(s):
for i in range(length):
if s[i] is ".":
return i
def char2int(s):
return DIGITS[s]
def integerpart(x, y):
return 10 * x + y
def add(x, y):
return x + y
i = finddot(s)
intp = reduce(integerpart, map(char2int, s[0: i]))
decp = reduce(integerpart, map(char2int, s[-length + i + 1:]))
return reduce(add, [intp, pow(0.1, length - i - 1) * decp])
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
# 使用split相当于借助内置函数将浮点数划分成两部分,以上是手动划分。
|
708998f496192a5d4d89f3dafcc4499908f17a2c | BasilBibi/Coursera_Python | /test/exceptions/test_exceptions.py | 3,878 | 3.796875 | 4 | import unittest
import traceback
from coursera_python.exceptions.ManagingFailure import *
class ManagingFailureTests(unittest.TestCase):
def test_00_basic_try_except_finally_none_failing(self):
try:
print('test_00_basic_try_except_finally_none_failing TRY')
n = int('0')
print(n)
except:
print('test_00_basic_try_except_finally_none_failing EXCEPT')
finally:
print('test_00_basic_try_except_finally_none_failing FINALLY')
print('test_00_basic_try_except_finally_none_failing SUCCESS')
def test_01_basic_try_except_finally_none_failing_else(self):
try:
print('test_01_basic_try_except_finally_none_failing_else TRY')
except:
print('test_01_basic_try_except_finally_none_failing_else EXCEPT')
else:
print('test_01_basic_try_except_finally_none_failing_else ELSE')
n = int('0')
print(n)
finally:
print('test_01_basic_try_except_finally_none_failing_else FINALLY')
print('test_01_basic_try_except_finally_none_failing_else SUCCESS')
def test_02_basic_try_except_finally(self):
try:
print('test_02_basic_try_except_finally TRY')
AlwaysRaisesException(0)
except:
print('test_02_basic_try_except_finally EXCEPT')
finally:
print('test_2_basic_try_except_finally FINALLY')
def test_03_basic_try_except_multi(self):
try:
print('test_03_basic_try_except_multi TRY')
MultiCatch(AlwaysRaisesException, '0')
except:
print('test_03_basic_try_except_multi EXCEPT')
finally:
print('test_03_basic_try_except_multi FINALLY')
def test_04_basic_try_except_multi_bbbexception(self):
try:
print('test_04_basic_try_except_multi TRY')
MultiCatch(AlwaysRaiseBbbException, '0')
except:
print('test_04_basic_try_except_multi EXCEPT')
finally:
print('test_04_basic_try_except_multi FINALLY')
def test_05_basic_try_except_inline(self):
try:
print('test_05_basic_try_except_inline TRY')
MultiCatchInline(AlwaysRaisesException, '0')
except:
print('test_05_basic_try_except_inline EXCEPT')
finally:
print('test_05_basic_try_except_inline FINALLY')
def test_06_basic_try_except_inline_bbbexception(self):
try:
print('test_06_basic_try_except_inline TRY')
MultiCatchInline(AlwaysRaiseBbbException, '0')
except:
print('test_06_basic_try_except_inline EXCEPT')
finally:
print('test_06_basic_try_except_inline FINALLY')
def test_07_swallowing_an_exception(self):
try:
AlwaysRaisesException(0)
except:
pass
def test_08_printing_an_exception(self):
try:
AlwaysRaisesException(0)
except:
print('test_08_printing_an_exception EXCEPT')
traceback.print_exc()
def test_09_printing_a_reraised_exception(self):
try:
CatchAndRaise(AlwaysRaisesException,0)
except:
print('test_09_printing_a_reraised_exception EXCEPT')
traceback.print_exc()
def test_10_printing_a_new_exception(self):
try:
CatchAndRaiseNew(AlwaysRaisesException,0)
except:
print('test_10_printing_a_new_exception EXCEPT')
traceback.print_exc()
def test_11_printing_a_bad_int_exception(self):
try:
RaiseExceptionOnBadInt('This is not an int')
except:
print('test_11_printing_a_bad_int_exception EXCEPT')
traceback.print_exc()
if __name__ == '__main__':
unittest.main()
|
61cdb6e7729e8e0acf90b1b2c94100766c9e2dd4 | arteev/stepik-course-python | /week-3/week-3-2-step7.py | 150 | 3.59375 | 4 | d = dict()
for x in [int(input()) for x in range(int(input()))]:
if x in d:
print(d[x])
else:
d[x] = f(x)
print(d[x])
|
f884c61a4f49a88af21de0421c275c7d9aa87cb3 | IslaMurtazaev/PythonApplications | /MIT/searchingSorting.py | 1,921 | 4 | 4 | # BUBBLE SORT
def bubbleSort(L):
'''
Because of the two nested loops (which can possibly be of linear complexity O(n))
fns's order of growth is O(n^2)
'''
swap = False
while not swap: # by the end of first loop, I'm sure that the biggest e is at the end -> O(n)
swap = True
for j in range(1, len(L)):
if L[j-1] > L[j]:
L[j-1], L[j], swap = L[j], L[j-1], False
return L
# print(bubbleSort([x for x in range(20, 0, -1)]))
# SELECTION SORT -> O(n^2)
def selectionSort(L): # logic seems to be similar and opposite to Bubble sort
suffixSt = 0
while suffixSt != len(L): # after one loop the smallest e will be at the beggining
for i in range(suffixSt, len(L)):
if L[i] < L[suffixSt]:
L[suffixSt], L[i] = L[i], L[suffixSt]
suffixSt += 1
return L
# print(selectionSort([x for x in range(100, 0, -1)]))
def insertionSort(L):
for i in range(1, len(L)):
j = i
while j > 0 and L[j-1] > L[j]:
L[j], L[j-1] = L[j-1], L[j] # SWAPING
j-=1
return L
print(insertionSort([x for x in range(50, 0, -1)]))
# MERGE SORT -> O(n log n)
def merge(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
def mergeSort(L):
if len(L) < 2:
return L[:]
else:
mid = len(L)//2
left = mergeSort(L[:mid])
right = mergeSort(L[mid:])
return merge(left, right)
# print(mergeSort([x for x in range(50, 0, -1)])) |
18ac9f285c54b7127b67f2e8a4ed4077ebe46c7b | robinfelix/coding-algorithms | /algorithms/sorting_algo/selection_sort.py | 484 | 3.6875 | 4 | '''
O(n^2)
selection sort can be used when min number of swaps is required
'''
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
j = i + 1
# print(len(arr[j:]))
while j < len(arr):
if arr[min_idx] > arr[j]:
min_idx = j
j += 1
else:
j += 1
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
arr = [17,2,1,9,8,7,13]
print (selection_sort(arr))
|
90ca1e2800d837333115c5ad021b0d08e579a562 | wilbertgeng/LintCode_exercise | /BFS/788.py | 2,516 | 4.09375 | 4 | """788. The Maze II
"""
class Solution:
"""
@param maze: the maze
@param start: the start
@param destination: the destination
@return: the shortest distance for the ball to stop at the destination
"""
def shortestDistance(self, maze, start, destination):
# write your code here
## Practice:
m = len(maze)
n = len(maze[0])
steps = {tuple(start): 0}
queue = collections.deque([tuple(start)])
while queue:
i, j = queue.popleft()
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
x = i + dx
y = j + dy
while 0 <= x < m and 0 <= y < n and maze[x][y] != 1:
x += dx
y += dy
x -= dx
y -= dy
if maze[x][y] == 0:
if (x, y) in steps and steps[(x, y)] > steps[(i, j)] + (abs(x - i) + abs(y - j)):
steps[(x, y)] = steps[(i, j)] + (abs(x - i) + abs(y - j))
queue.append((x, y))
if (x, y) not in steps:
steps[(x, y)] = steps[(i, j)] + (abs(x - i) + abs(y - j))
queue.append((x, y))
if tuple(destination) in steps:
return steps[tuple(destination)]
return -1
####
m = len(maze)
n = len(maze[0])
queue = collections.deque([tuple(start)])
steps = {tuple(start): 0}
while queue:
i, j = queue.popleft()
for x, y in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
i_new = i + x
j_new = j + y
while 0 <= i_new < m and 0 <= j_new < n and maze[i_new][j_new] != 1:
i_new += x
j_new += y
i_new -= x
j_new -= y
if maze[i_new][j_new] == 0:
if (i_new, j_new) not in steps:
steps[(i_new, j_new)] = steps[(i, j)] + abs(i_new - i + j_new - j)
queue.append((i_new, j_new))
if steps[(i_new, j_new)] > steps[(i, j)] + abs(i_new - i + j_new - j): #如果发现了最短路径 需要写入queue重新计算
steps[(i_new, j_new)] = steps[(i, j)] + abs(i_new - i + j_new - j)
queue.append((i_new, j_new))
if tuple(destination) in steps:
return steps[tuple(destination)]
return -1
|
68f710e132605c543b0172a2047a888972896267 | peitruthxxx/learning_log_python | /estimate.py | 867 | 4.03125 | 4 | import math
def cal(x ,a):
y = (x + a/x) / 2
return y
def main():
a = float(input("Enter a value to find square root: "))
x = 3.0
prev = 0
curr = cal(x, a)
while abs(prev - curr) > 0.0000001:
print(curr)
prev = curr
curr = cal(prev, a)
print(curr)
print(math.sqrt(a))
main()
#目的:利用牛頓法求平方根近似值
#利用迴圈無限逼近root值 前後值相差<0.0000001時跳出迴圈
#再印出sqrt函數值
"""
#YC另一個寫法
import math
PRECISION = 10 ** -8
def estimate(target, x = 1):
while True:
x = (x + target / x) / 2
yield x
def main():
sqrtOfFive = estimate(5) #input
prev, now = 0, next(sqrtOfFive)
while abs(now - prev) > PRECISION:
prev, now = now, next(sqrtOfFive)
print(now)
print(math.sqrt(5))
if __name__ == '__main__':
main()
""" |
543a75494783ae3e5a2b559ec15611941bf8ea8f | paulm29/tkinter-tutorial | /3-widgets/widget_table.py | 395 | 3.609375 | 4 | from tkinter import *
from tkinter.ttk import *
root = Tk()
tree = Treeview(root)
tree["columns"]=("one","two")
tree.column("one", width=100 )
tree.column("two", width=100)
tree.heading("one", text="coulmn A")
tree.heading("two", text="column B")
tree.insert("" , 0, text="Line 1", values=("1A","1b"))
tree.insert("" , 1, text="Line 2", values=("2A","2b"))
tree.pack()
root.mainloop() |
85d1e75364d2924540a6e5236d10fdc744cb2b88 | hercilioln/python_studies | /new2.py | 905 | 4.15625 | 4 | '''
soma de dois numeros
num1 = int(input())
num2 = int(input())
print (num1 + num2)
'''
'''
#converter Farenhait em Celcius
F = int(input())
C = (5*(F-32)/9)
print(C)'''
'''num1 = int(input())
num2 = int(input()) #numero inteiro
numR = float(input()) #numero real usar float
prod = num1 * 2 * (num2/2)
print('o produto do dobro com a metade do segundo é', prod) #sempre colocar virgula depois das aspas
tripsome = num1 * 3 + numR
print("a soma do triplo:", tripsome)
cube = numR**3
print('o terceiro elevado ao cubo:', cube)'''
'''
largura = int(input("Largura do quadrado: "))
altura = int(input("Altura do quadrado: "))
area = largura * altura
print(area)
print ((area * 2))
'''
'''
file = int(input("Qual o tamanho do arquivo em MB? "))
link = int(input("Qual a velocidade do link em Mbps?"))
time = ((file * 8)/ link) / 60
print("The time of download is:", time, "minutos")
'''
|
f383ac9b6a80a2d72da58b1bfd6d970aa6f430cf | YTnogeeky/leetcode | /Lowest Common Ancestor of a Binary Tree.py | 597 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, A, B):
if root is None or root == A or root == B:
return root
left = self.lowestCommonAncestor(root.left, A, B)
right = self.lowestCommonAncestor(root.right, A, B)
if left and right:
return root
if left:
return left
if right:
return right
return None
|
4658026e765d5680d98f7df50da306fc41b899bb | DmitryTsybin/Study | /Coursera/Algorithmic_Thinking/Project_3-Closest_pairs_and_clustering_algorithms/closest_pairs_and_clustering_algorithms.py | 8,925 | 4.21875 | 4 | """
File with functions to calculate different pairs and clustering algorythms.
"""
import math
import alg_cluster
def pair_distance(cluster_list, idx1, idx2):
"""
Helper function that computes Euclidean distance between two clusters in a list
Input: cluster_list is list of clusters, idx1 and idx2 are integer indices for two clusters
Output: tuple (dist, idx1, idx2) where dist is distance between
cluster_list[idx1] and cluster_list[idx2]
"""
return (cluster_list[idx1].distance(cluster_list[idx2]), min(idx1, idx2), max(idx1, idx2))
def slow_closest_pair(cluster_list):
"""
Compute the distance between the closest pair of clusters in a list (slow)
Input: cluster_list is the list of clusters
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum distance dist.
"""
if len(cluster_list) < 2:
return -1
min_distance = pair_distance(cluster_list, 0, 1)
for idx1 in range(len(cluster_list)):
for idx2 in range(len(cluster_list)):
if idx1 != idx2:
distance = pair_distance(cluster_list, idx1, idx2)
if distance[0] < min_distance[0]:
min_distance = distance
return min_distance
def return_min_tuple(tuple1, tuple2):
"""
implement function min for tuples (dist, i, j)
"""
ret_tuple = tuple1
if tuple2[0] < tuple1[0]:
ret_tuple = tuple2
return ret_tuple
def closest_pair_strip(cluster_list, horiz_center, half_width):
"""
Helper function to compute the closest pair of clusters in a vertical strip
Input: cluster_list is a list of clusters produced by fast_closest_pair
horiz_center is the horizontal position of the strip's vertical center line
half_width is the half the width of the strip (i.e; the maximum horizontal distance
that a cluster can lie from the center line)
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] lie in the strip and have minimum distance dist.
"""
if len(cluster_list) < 2:
return -1
points_in_strip = []
for point in cluster_list:
if abs(point.horiz_center() - horiz_center) < half_width:
points_in_strip.append(point)
points_in_strip.sort(key = lambda x: x.vert_center())
strip_point_count = len(points_in_strip)
ret_tuple = (float('inf'), -1, -1)
for coordinate in points_in_strip:
if points_in_strip.index(coordinate) == strip_point_count - 1:
break
else:
for check in range(1, 4): # check 3 points
rt_index = points_in_strip.index(coordinate)+check
if (rt_index) == strip_point_count:
break
else:
strip_tuple = slow_closest_pair([coordinate, points_in_strip[rt_index]])
if strip_tuple[0] < ret_tuple[0]:
answer_list = []
answer_list.append(strip_tuple[0])
#put the indices in increasing order
if cluster_list.index(coordinate) < cluster_list.index(points_in_strip[rt_index]):
answer_list.append(cluster_list.index(coordinate))
answer_list.append(cluster_list.index(points_in_strip[rt_index]))
else:
answer_list.append(cluster_list.index(points_in_strip[rt_index]))
answer_list.append(cluster_list.index(coordinate))
ret_tuple = tuple(answer_list)
return ret_tuple
def fast_closest_pair(cluster_list):
"""
Compute the distance between the closest pair of clusters in a list (fast)
Input: cluster_list is list of clusters SORTED such that horizontal positions of their
centers are in ascending order
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum distance dist.
"""
size = len(cluster_list)
if size < 4:
ret_tuple = slow_closest_pair(cluster_list)
else:
# divide
split = size / 2
left = cluster_list[:split]
rigth = cluster_list[split:]
left_tuple = fast_closest_pair(left)
right_tuple = fast_closest_pair(rigth)
right_list = list(right_tuple)
right_list[1] += split
right_list[2] += split
right_tuple = tuple(right_list)
# merge
left_and_right_min_tuple = return_min_tuple(left_tuple, right_tuple)
# print 'cluster_list[split]: ', cluster_list[split]
middle = 0.5 * (cluster_list[split - 1].horiz_center() + cluster_list[split].horiz_center())
ret_tuple = return_min_tuple(
left_and_right_min_tuple,
closest_pair_strip(cluster_list, middle, left_and_right_min_tuple[0]))
return ret_tuple
######################################################################
# Code for hierarchical clustering
def hierarchical_clustering(cluster_list, num_clusters):
"""
Compute a hierarchical clustering of a set of clusters
Note: the function may mutate cluster_list
Input: List of clusters, integer number of clusters
Output: List of clusters whose length is num_clusters
"""
num = len(cluster_list)
while num > num_clusters:
cluster_list.sort(key = lambda clu: clu.horiz_center())
idx = fast_closest_pair(cluster_list)
cluster_list[idx[1]].merge_clusters(cluster_list[idx[2]])
cluster_list.pop(idx[2])
num -= 1
return cluster_list
######################################################################
# Code for k-means clustering
def kmeans_clustering(cluster_list, num_clusters, num_iterations):
"""
Compute the k-means clustering of a set of clusters
Note: the function may not mutate cluster_list
Input: List of clusters, integers number of clusters and number of iterations
Output: List of clusters whose length is num_clusters
"""
# position initial clusters at the location of clusters with largest populations
num = len(cluster_list)
print "num_clusters: ", num_clusters
points = [idx for idx in xrange(num)]
points.sort(reverse = True, key = lambda idx:
cluster_list[idx].total_population())
points = [[cluster_list[points[idx]].horiz_center(),
cluster_list[points[idx]].vert_center()]
for idx in xrange(num_clusters)]
clusters = [-1 for _ in xrange(num)]
population = [0 for _ in xrange(num_clusters)]
for _ in xrange(num_iterations):
for cidx in xrange(num):
mind = (float("inf"), -1, -1)
for idx in xrange(num_clusters):
dist = cluster_point_distance(cluster_list,
points,
cidx, idx)
if mind > dist:
mind = dist
clusters[cidx] = mind[2]
for idx in xrange(num_clusters):
points[idx][0] = 0.0
points[idx][1] = 0.0
population[idx] = 0
for cidx in xrange(num):
idx = clusters[cidx]
cpopul = cluster_list[cidx].total_population()
population[idx] += cpopul
points[idx][0] += cluster_list[cidx].horiz_center() * cpopul
points[idx][1] += cluster_list[cidx].vert_center() * cpopul
for idx in xrange(num_clusters):
if population[idx] != 0:
points[idx][0] /= population[idx]
points[idx][1] /= population[idx]
result = [0 for _ in xrange(num_clusters)]
for cidx in xrange(num):
idx = clusters[cidx]
if result[idx] == 0:
result[idx] = cluster_list[cidx].copy()
else:
result[idx].merge_clusters(cluster_list[cidx])
return result
def cluster_point_distance(cluster_list, points, cidx, idx):
"""
Helper function that computes Euclidean distance between cluster and point
Input: cluster_list is list of clusters, points is list of points,
cidx1 and idx are integer indices for cluster and point
Output: tuple (dist, cidx, idx) where dist is distance between
cluster_list[cidx] and points[idx]
"""
d_x = cluster_list[cidx].horiz_center() - points[idx][0]
d_y = cluster_list[cidx].vert_center() - points[idx][1]
return (math.sqrt(d_x ** 2 + d_y ** 2), cidx, idx)
def compute_distortion(cluster_list, data_table):
distortion = 0
for cluster in cluster_list:
if type(cluster) == 'instance' and cluster != 0:
distortion += cluster.cluster_error(data_table)
return distortion
|
e2fb0febbe02e8f4a58d9da56898e34f80abc64a | ankurjain8448/leetcode | /search-insert-position.py | 692 | 3.53125 | 4 | #https://leetcode.com/problems/search-insert-position/description/
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
start = 0
end = len(nums) - 1
s = 0
e = len(nums)-1
index = -1
if target < nums[0]:
index = 0
elif target > nums[e]:
index = e + 1
else:
while s <= e:
mid = (s+e)/2
if nums[mid] == target:
index = mid
break
elif target < nums[mid]:
if start < mid and target > nums[mid-1]:
index = mid
break
e = mid - 1
else:
if mid < end and target < nums[mid+1]:
index = mid + 1
break
s = mid + 1
return index
|
036741075e6b880713124c6c302f7ffde0f39b76 | ZorkinMaxim/Python_school_lvl1 | /recursion.py | 84 | 3.578125 | 4 | def repeat(n):
print('>', n)
if n < 8:
repeat(n+1)
repeat(1) |
d4cc38bb1211524669ad8c97162e6225c9b2aacd | uzuran/AutomaticBoringStuff | /Loops/loops.py | 285 | 4.125 | 4 | #spam = 1
#if spam < 5:
# print('Hello World')
# spam = spam + 1
# This loop can repeat 5 times, end is spam = spam + 1 if we change value
# to + 2 its equal 5 - 2 = 3, thats mean its
# repeat 3 times!
spam = 0
while spam < 5:
print('Loop Loop Loop')
spam = spam + 1
|
2e5144d43dbdbd1a31289b266be3a0701e2309a3 | u101022119/NTHU10220PHYS290000 | /student/101022219/ack.py | 312 | 3.890625 | 4 | m = float (raw_input('Enter the value of m:'))
n = float (raw_input('Enter the value of n:'))
def ackermann(m, n):
if m == 0:
return n + 1
elif m >= 0 and n == 0:
return ackermann(m-1, 1)
elif m >= 0 and n >= 0:
return ackermann(m-1, ackermann(m, n-1))
print ackermann(m, n)
|
182a35d1b9b483d223337b261bf7367b0247c090 | SiddhiPevekar/Python-Programming-MHM | /prog24.py | 293 | 4.28125 | 4 | #leap year(number divisible by 4 and 400 is leap year and year divisible by 4 and 100 is not a leap year)
year=int(input("enter any leap:\n"))
if(year%4==0 and year%100!=0 or year%400==0):
print("{} is a leap year".format(year))
else:
print("{} is not a leap year".format(year))
|
cbc08657b411f25ebc2defabf05d223f7379e82b | SSRTLandscapeEvaluation/Deng | /City_Color/生成器.py | 926 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 20:24:53 2018
@author: Administrator
"""
'''
# 简单的生成器函数
def my_gen():
n=1
print("first")
# yield区域
yield n
n+=1
print("second")
yield n
n+=1
print("third")
yield n
a=my_gen()
print("next method:")
# 每次调用a的时候,函数都从之前保存的状态执行
print(next(a))
print(next(a))
print(next(a))
print("for loop:")
# 与调用next等价的
b=my_gen()
for elem in my_gen():
print(elem)
'''
def my_gen():
n=1
print("first")
# yield区域
yield n
n+=1
print("second")
yield n
n+=1
print("third")
yield n
def m2y_gen():
n=1
print("f")
# yield区域
yield n
n+=1
print("s")
yield n
n+=1
print("t")
yield n
a=my_gen()
b=m2y_gen()
print("next method:")
print(next(b))
|
74541996e03fe00d803b020ab72eab02eb32feeb | Harlow777/crabs | /crabgender.py | 2,320 | 3.84375 | 4 | import math
import random
import string
import csv
import random
# Jacob Harlow
# October 4, 2014
# CSC 475 Artifical Intelligence
#
# This program is a single perceptron built to learn what crabs are male
# or female based on two attributes from the csv CW(carapace width) and
# RW(rear width).
# initialize weights randomly
weight1 = round(random.uniform(0.1, 10.0), 10)
weight2 = round(random.uniform(0.1, 10.0), 10)
weights = [1, weight1, weight2]
#initialize alpha
alpha = 0.01
Guessright = 0
Sex = []
Rw = []
Cw = []
# read from crabs csv
with open('crabs.csv') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
for row in csvreader:
sex = row[2]
Sex.append(sex)
rw = row[5]
Rw.append(rw)
cw = row[6]
Cw.append(cw)
# learning algorithm
def learn(sex, CW, RW):
# call hypothesis
hypothesis = Hyp(CW, RW)
# train it down if it correctly guesses male
if (hypothesis and sex == 'M'):
err = -2
# train it up if it correctly guesses female
elif (not hypothesis and sex == 'F'):
err = 2
# 0 if its wrong
else:
err = 0
# adjust weights according to the error
weights[1] = weights[1] + err * CW * alpha
weights[2] = weights[2] + err * RW * alpha
if(hypothesis):
print "Guess = M"
else:
print "Guess = F"
print "Actual sex = %s" % sex
print "error = %s" % err
# hypothesis algorithm, multiply attributes by weights and sum with bias
def Hyp(CW, RW):
h = CW*weights[1] + RW*weights[2] + weights[0]
# return true if its positive
return h>0
# testing algorithm, just calls hypothesis
def test(Sex, Cw, Rw):
hypothesis = Hyp(Cw, Rw)
if(hypothesis):
print "Guess = F"
Guess = 'F'
else:
print "Guess = M"
Guess = 'M'
print "Actual sex = %s" % Sex
if(Sex == Guess):
increment()
# increments the percentage variable
def increment():
global Guessright
Guessright = Guessright+1
# training loop
for i in range(1000):
# random crab selector
randindex = random.randint(1, 199)
# call learn then decrement alpha slightly
learn(Sex[randindex], float(Cw[randindex]), float(Rw[randindex]))
alpha = alpha/1.03
print ""
# testing loop
for i in range(100):
randindex2 = random.randint(1, 199)
test(Sex[randindex2], float(Cw[randindex2]), float(Rw[randindex2]))
print ""
# print percent right
print "Percent correct: %s" % Guessright
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.