blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
3116e38d76b7c3fc580a2ae08210590554b2a8e9 | ivanrp05/Ivanindra-Rizky-Pratama_I0320054_Tiffany-Bella_Tugas9 | /I0320054_Exercise9.8.py | 403 | 3.546875 | 4 | #Mulai
print("")
print("Exercise 9.8")
print("Nama : Ivanindra Rizky P")
print("NIM : I0320054")
print("")
print("===========================")
print("")
print("Jawab :")
>>> #mengonversi list ke dalam array.array
>>> li = [10,20,30,40,50]
>>> C = array.array('i')
>>> C.fromlist (li)
>>> type(C)
<type 'array.array'>
>>> for nilai in C:
print("%d " % nilai, end ='')
10 20 30 40 50
>>> |
5fdf4320e124078dff1eb7cfaa77a4519668f218 | tomcroll/mitpython | /isIn.py | 789 | 4.03125 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
if aStr == '':
return False
mid = len(aStr) / 2
if aStr[mid] == char:
return True
elif char < aStr[mid]:
return isIn(char, aStr[:mid])
else:
return isIn(char, aStr[mid + 1:])
print isIn('a', 'abcdefghijklmn') == True
print isIn('o', 'abcdefghijklmn') == False
print isIn('k', 'abcdefghijklmn') == True
print isIn('n', 'abcdefghijklmn') == True
if __name__ == "__main__":
assert isIn('a', 'abcdefghijklmn') == True
assert isIn('o', 'abcdefghijklmn') == False
assert isIn('k', 'abcdefghijklmn') == True
assert isIn('n', 'abcdefghijklmn') == True
|
12daee0834e9d08d29f2716dc8cace74dd710e1a | DincerDogan/Hackerrank-Codes | /Python/company-logo.py | 1,779 | 4.1875 | 4 |
'''
Company Logo
https://www.hackerrank.com/challenges/most-commons/problem
A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a string s, which is the company name in lowercase letters, your task is to find the top three most common characters in the string.
Print the three most common characters along with their occurrence count.
Sort in descending order of occurrence count.
If the occurrence count is the same, sort the characters in alphabetical order.
For example, according to the conditions described above,
google would have it's logo with the letters g, o, e.
Input Format
A single line of input containing the string S.
Constraints
3 < len(S) <= 10^4
Output Format
Print the three most common characters along with their occurrence count each on a separate line.
Sort output in descending order of occurrence count.
If the occurrence count is the same, sort the characters in alphabetical order.
Sample Input 0
aabbbccde
Sample Output 0
b 3
a 2
c 2
Explanation 0
aabbbccde
Here, b occurs 3 times. It is printed first.
Both a and c occur 2 times. So, a is printed in the second line and c in the third line because a comes before c in the alphabet.
Note: The string S has at least 3 distinct characters.
'''
if __name__ == '__main__':
s = input().strip("\n").strip()
char_counts = {}
for c in s:
char_counts.setdefault(c, 0)
char_counts[c] += 1
count = 0
for (c, cnt) in sorted(char_counts.items(), key=lambda x: (-x[1], x[0]), reverse=False):
print(c, cnt)
count += 1
if count == 3:
break |
82a3c58149dbf05008e7845185134c5060196adf | Uditendu/Python_Files | /Count_Occurance.py | 535 | 4 | 4 | """Module to count how many times check appears in a String
"""
def count_occurance(txt, check):
Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ-123456789'
txt+=' '
l = len(check)
n=0
i=0
j=0
while i<(len(txt)-l+1):
if txt[i]==check[0]:
if txt[i:i+l]==check and txt[i-1].upper() not in Alphabet and txt[i+l].upper() not in Alphabet:
n+=1
i+=l
else:
i+=1
else:
i+=1
return "No. of Occurance of "+check+"="+str(n) |
7d900b9d8a49c9f3b4753b7c8effd72764ddbbf6 | sweenejp/learning-and-practice | /treehouse/python-beginner/monty_python_tickets.py | 1,349 | 4.15625 | 4 | SERVICE_CHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100
def calculate_price(number_of_tickets):
# $2 service charge per transaction
return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE
while tickets_remaining > 0:
print("There are only {} tickets remaining!\nBuy now to secure your spot for the show!".format(tickets_remaining))
name = input("Hi there! What's your name? ")
order = input("Okay, {}, how many tickets would you like? ".format(name))
try:
order = int(order)
if order > tickets_remaining:
raise ValueError("There are only {} tickets remaining".format(tickets_remaining))
except ValueError as err:
# Include the error text in the output
print("Oh no, we ran into an issue.")
print("{} Please try again".format(err))
else:
amount_due = calculate_price(order)
print("Great, {}! You ordered {} tickets. Your amount due is ${}".format(name, order, amount_due))
intent_to_purchase = input('Do you want to proceed with your purchasing order?\nPlease enter "yes" or "no" ')
if intent_to_purchase.lower() == 'yes':
print('SOLD!')
tickets_remaining -= order
else:
print('Thank you for stopping by, {}.'.format(name))
print('We are so sorry! This event is sold out. :(')
|
ed0990ab618588058e59a675e1e1b48c19384b6a | RoncoLuis/artificial_neural_net | /scripts/SIngle-Layer Net.py | 356 | 3.671875 | 4 | """
Single-Layer Net -> red de capa simple
"""
x1 = [1,1,0,0]
x2 = [1,0,1,0]
w1 = 1
w2 = 1
umbral = 2
for i in x1:
sum = (x1[1]*w1)+(x2[i]*w2)
print("sumatoria: ",sum)
if sum > umbral:
print("se dispara neurona ->",1,":",i)
elif sum <= umbral:
print("no se disparo neurona ->",0,":",i)
else:
print("Entro aqui") |
b2993132593b941ba3da41fae670e742755edb8b | chaecramb/exercism | /python/clock/clock.py | 889 | 3.734375 | 4 | class Clock:
def __init__(self, hours, minutes):
self.hours = hours
self.minutes = minutes
self.time = None
def __str__(self):
return self.clock_time()
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.clock_time() == other.clock_time()
else:
return False
def clock_time(self):
if not self.time:
hours, minutes = self.convert()
self.time = self.pretty_string(hours, minutes)
return self.time
def add(self, minutes):
self.minutes += minutes
return self
def convert(self):
hours = str((self.hours + self.minutes // 60) % 24)
minutes = str(self.minutes % 60)
return((hours, minutes))
def pretty_string(self, hours, minutes):
if len(hours) == 1:
hours = "0" + hours
if len(minutes) == 1:
minutes = "0" + minutes
return hours + ':' + minutes
|
88ee6cb20d480c28058469fd99b5dca8243ca1b1 | Kaifee-Mohammad/labs | /PythonLab/datas.py | 523 | 3.9375 | 4 | # tuples
days = ('Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat')
# print(type(days))
# print(days)
# lists
junk = ['this is a string', 'second word', 22, 44, 5.5]
# print(type(junk))
# print(junk)
# dictionary
emp = {"Kaifee Mohammad": "kaifee@microsoft.com",
"Chris": "chris@microsoft.com"}
# print(type(emp))
# print(emp)
# operators
# print("d" + "o")
# print("d" * 3)
# iterate thru tuple, list and dictionary
# for d in days:
# print(d)
# for j in junk:
# print(type(j))
for name, email in emp.items():
print(name, email)
|
cece0912a682e6a162e2c19da04069d5bc140977 | ShinW0330/ps_study | /01_Brute_Force/Level4/9663.py | 1,033 | 3.5 | 4 | # N-Queen
# https://www.acmicpc.net/problem/9663
# 힌트 : 세로줄은 column 값으로 확인가능
# 대각선(\)은 row - column + N - 1 값으로 확인 가능.
# Skew-대각선(/)은 row + column 값으로 확인 가능.
# 해당 방법은 pypy3으로 컴파일 해야 시간 초과되지 않음.
def dfs(r):
global answer
if r == N - 1:
answer += 1
return
for j in range(N):
# 세로줄, 대각선(\, /) 값을 만족하는지 확인
if j in cols or (r + 1 + j) in diag or (r + 1 - j + N - 1) in skew_diag:
continue
cols.append(j); diag.append(r + 1 + j); skew_diag.append(r + 1 - j + N - 1)
dfs(r + 1)
cols.pop(); diag.pop(); skew_diag.pop()
if __name__ == "__main__":
N = int(input())
cols, diag, skew_diag = [], [], []
answer = 0
for i in range(N):
cols.append(i); diag.append(0 + i); skew_diag.append(0 - i + N - 1)
dfs(0)
cols.pop(); diag.pop(); skew_diag.pop()
print(answer)
|
4c3dad60ea0dee8ed68c6c7ee8f612e99235febc | demeth0/REPO_CS_P2024 | /Python Project/TD/Archive/Samuel/fibonacci.py | 278 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
"""
#suite de fibonacci
def fibonacci(n):
f0 = 0
f1 =1
fi = 0
if(n == 1):
fi = f1
for i in range(2, n+1):
fi = f0 +f1
f0 = f1
f1 = fi
print(fi)
|
4bae997e61c31f0a5987411c1778eaac703c10fa | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4184/codes/1595_825.py | 307 | 3.796875 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
from math import*
r=float(input("insira o valor de r:"))
a= pi*(r**2)
v= 4/3*pi*(r**3)
print(round(a,3 ))
print(round(v,3 )) |
c1d083198693ddb34e9cb53e4c87110ee7d75609 | tazeemsyed/python-flask-assignment | /day2.py | 1,904 | 4.53125 | 5 | #code for changing data type from integer to string using python
n = 12
print (type(n),n)
n = str (n)
print (type(n),n)
#code for changing data type from integer to float using python
n = 12
print (type(n),n)
n = float (n)
print (type(n),n)
#code for changing data type from integer to boolean using python
n = 12
print (type(n),n)
n = bool (n)
print (type(n),n)
#code for changing data type from string to int using python
n = '100'
print (type(n),n)
n = int (n)
print (type(n),n)
#code for changing data type from string to float using python
n = '100'
print (type(n),n)
n = float (n)
print (type(n),n)
#code for changing data type from string to boolean using python
n = '100'
print (type(n),n)
n = bool (n)
print (type(n),n)
#code for changing data type from float to int using python
n = 265.65
print (type(n),n)
n = int (n)
print (type(n),n)
#code for changing data type from float to string using python
n = 265.65
print (type(n),n)
n = str (n)
print (type(n),n)
#code for changing data type from float to boolean using python
n = 265.65
print (type(n),n)
n = bool (n)
print (type(n),n)
#code for changing data type from boolean to int using python
n = True
print (type(n),n)
n = int (n)
print (type(n),n)
#code for changing data type from float to string using python
n = True
print (type(n),n)
n = str (n)
print (type(n),n)
#code for changing data type from boolean to float using python
n = True
print (type(n),n)
n = float (n)
print (type(n),n)
#code for changing data type from boolean to int using python
n = False
print (type(n),n)
n = int (n)
print (type(n),n)
#code for changing data type from boolean to string using python
n = False
print (type(n),n)
n = str (n)
print (type(n),n)
#code for changing data type from boolean to float using python
n = False
print (type(n),n)
n = float (n)
print (type(n),n) |
bd3feeafc0b5377b88dd4fba42fc905f63fc242e | indranildchandra/ML101-Codelabs | /src/linear_regression_example1.py | 2,552 | 3.671875 | 4 | import collections
stepSize = 0.01 # learning rate
def read_data() :
data = open("./../resources/vehicle_sale_data.csv" , "r")
gdp_sale = collections.OrderedDict()
for line in data.readlines()[1:] :
record = line.split(",")
gdp_sale[float(record[1])] = float(record[2].replace('\n', ""))
print(gdp_sale)
return gdp_sale
def sale_for_data(constant, slope, data):
return constant + slope * data # y = c + ax format
def step_cost_function_for(gdp_sale, constant, slope) :
global stepSize
diff_sum_constant = 0 # diff of sum for constant 'c' in "c + ax" equation
diff_sum_slope = 0 # diff of sum for 'a' in "c + ax" equation
gdp_for_years = list(gdp_sale.keys())
for year_gdp in gdp_for_years: # for each year's gdp in the sample data
# get the sale for given 'c' and 'a'by giving the GDP for this sample record
trg_data_sale = sale_for_data(constant, slope, year_gdp) # calculated sale for current 'c' and 'a'
a_year_sale = gdp_sale.get(year_gdp) # real sale for this record
diff_sum_slope = diff_sum_slope + ((trg_data_sale - a_year_sale) * year_gdp) # slope is (h(y) - y) * x
diff_sum_constant = diff_sum_constant + (trg_data_sale - a_year_sale) # constant is (h(y) - y)
step_for_constant = (stepSize / len(gdp_sale)) * diff_sum_constant # distance to be moved by c
step_for_slope = (stepSize / len(gdp_sale)) * diff_sum_slope # distance to be moved by a
new_constant = constant - step_for_constant # new c
new_slope = slope - step_for_slope # new a
return new_constant, new_slope
def get_weights(gdp_sale) :
constant = 1
slope = 1
accepted_diff = 0.01
while 1 == 1: # continue till we reach local minimum
new_constant, new_slope = step_cost_function_for(gdp_sale, constant, slope)
# if the diff is too less then lets break
if (abs(constant - new_constant) <= accepted_diff) and (abs(slope - new_slope) <= accepted_diff):
print("Difference between values in last iteration and current iteration for both constant and slope are less than " + str(accepted_diff))
return new_constant, new_slope
else:
constant = new_constant
slope = new_slope
print("Updated values: Constant = " + str(new_constant) + ", Slope = " + str(new_slope))
def main():
contant, slope = get_weights(read_data())
print("Final values: Constant : " + str(contant) + ", Slope:" + str(slope))
if __name__ == '__main__':
main()
|
27c9edf0ec8926443c66e98dc6eb9a9fd748dcf3 | michelgalle/hackerrank | /CrackingTheCodingInterview/20-BitManipulation-LonelyInteger.py | 285 | 3.546875 | 4 | #!/bin/python3
import sys
def lonely_integer(a):
n = 0
for i in a:
#xor negando os numeros, assim sobra somente o numero unico
n ^= i
return n
n = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]
print(lonely_integer(a))
|
1770806d218ad6c114727f4244274cc2236c6ec9 | HyeonJun97/Python_study | /Chapter08/Chapter8_pb1.py | 575 | 3.640625 | 4 |
number=input("주민번호를 입력하세요: ").strip()
if len(number)!=14:
print("주민번호가 올바르지 않습니다.")
else:
for i in range(len(number)):
test=True
check=ord(number[i])
if i==6:
if check!=45:
test=False
else:
if check<48 and check>57:
test=False
if test==True:
print("올바른 주민번호입니다.")
else:
print("주민번호가 올바르지 않습니다.")
|
cdf82c036d1761d8887960b12c685dd96adb81fa | frclasso/acate18122018 | /01_Sintaxe_Basica/11_set.py | 893 | 4 | 4 | #!/usr/bin/env python3
# Sets
cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Chemistry'}
art_courses = {'History', 'Design', 'Art', 'Math'}
'''Interseção (tem em ambos)'''
print(cs_courses.intersection(art_courses)) # Math, History
'''Diferença, o que tem em cs_courses e nao tem art_courses'''
print(cs_courses.difference(art_courses)) # CompSci,Physics,Chemistry
'''União'''
print(cs_courses.union(art_courses))
print()
"""Ou ainda poderiamos usar os seguintes operadores"""
print(cs_courses & art_courses) # intersection
print(cs_courses - art_courses) # diference
print(cs_courses | art_courses) # union, PIPE
print()
'''Filtrando duplicatas'''
print(set([1,2,1,3,1,3,2]))
'''Criando um set vazio'''
colecao = set() # com parenteses
print(colecao)
print(type(colecao))
# Nao confundir com dicionarios que tambem utilizamos chaves {}, no entanto
# {chave:valor} |
1d1bfcd574c19cfa0810728e2579fb04ea3edf01 | danielliu000/MyPythonLearning | /7_Reverse_Integer.py | 754 | 3.890625 | 4 | '''Given a 32-bit signed integer, reverse digits of an integer.'''
class Solution:
def reverse(self, x: int) -> int:
import math
if -math.pow(2,31) < x < math.pow(2,31)-1:
if x > 0:
result = int(str(x).rstrip('0')[::-1])
if result < math.pow(2,31)-1:
return result
else:
return 0
if x < 0:
result = 0-int(str(-x).rstrip('0')[::-1])
if result > -math.pow(2,31):
return result
else:
return 0
if x ==0:
return 0
else:
return 0
|
0bd66d6bcb68afe3c44995adee36ee5f95c58386 | YoByron/generative-art | /src/utils/unsplash.py | 1,075 | 3.640625 | 4 | import urllib
import requests
def query_unsplash(
api_key: str, search_term: str, max_number_of_images: int = 30, page_number: int = 1
) -> dict:
"""
Given a search term, queries pixabay for free-use images, returning less than
or equal to the max_number_of_images.
:param api_key: (str) Auth API key for pixabay service.
:param search_term: (str) The search term you want to query pixabay for.
:param max_number_of_images: (int) The maximum number of images you want returned.
:param page_number: (int) The page of search results you want returned.
:returns: (dict) Pixabay JSON response containing the image details.
"""
url = "https://api.unsplash.com/search/photos"
url_encoded_search_term = urllib.parse.quote_plus(search_term)
params = {
"client_id": api_key,
"query": url_encoded_search_term,
"per_page": max_number_of_images,
"page": page_number,
}
response = requests.get(url=url, params=params)
data = response.json()
return data
|
f3a4a1ce6cf8d44c74b7756882fbc8953b7cf1ac | Rivarrl/leetcode_python | /leetcode/offer/36.py | 1,046 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 36.py
# @Time : 2020/5/6 20:54
# @Author : Rivarrl
# ======================================
# [面试题36. 二叉搜索树与双向链表](https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/comments/)
from algorithm_utils import *
class Solution:
def treeToDoublyList(self, root: 'TreeNode') -> 'TreeNode':
if not root: return root
stk = []
last = head = tail = None
while stk or root:
while root:
stk.append(root)
root = root.left
root = stk.pop()
tail = root
if last:
last.right = root
root.left = last
else:
head = root
last = root
root = root.right
head.left, tail.right = tail, head
return head
if __name__ == '__main__':
a = Solution()
x = construct_tree_node([4,2,5,1,3])
a.treeToDoublyList(x)
|
31e2a60896dc26743492494e8e887bed429f9814 | mbreedlove/project-euler | /Python/euler3.py | 315 | 3.5 | 4 | #!/usr/bin/env python3
from math import sqrt
num = 600851475143
p = 1
for i in range(2, int(sqrt(num))):
if num % i == 0:
is_prime = True
for n in range(2, int(sqrt(i)) + 1):
if i % n == 0:
is_prime = False
if is_prime == True:
p = i
print(p)
|
b2a8c9b9590a13570ee4b04e69693b155632db30 | nashashibi/coding-interview-solutions | /py/BST_zigzag_order_traversal.py | 1,350 | 3.640625 | 4 | from collections import deque
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def zigzag_order(self):
q = deque([None, self])
popLeft = False
order = []
while len(q):
if popLeft:
node = q.popleft()
else:
node = q.pop()
if node:
if popLeft:
if node.right:
q.append(node.right)
if node.left:
q.append(node.left)
else:
if node.left:
q.appendleft(node.left)
if node.right:
q.appendleft(node.right)
order.append(node.val)
if node is None and len(q):
if popLeft:
q.appendleft(node)
else:
q.append(node)
popLeft = not popLeft
return order
# test 1
n8 = Node(8)
n9 = Node(9)
n10 = Node(10)
n11 = Node(11)
n12 = Node(12)
n13 = Node(13)
n14 = Node(14)
n15 = Node(15)
n4 = Node(4, n8, n9)
n5 = Node(5, n10, n11)
n6 = Node(6, n12, n13)
n7 = Node(7, n14, n15)
n2 = Node(2, n4, n5)
n3 = Node(3, n6, n7)
n1 = Node(1, n2, n3)
# test 2
# n4 = Node(4)
# n5 = Node(5)
# n6 = Node(6)
# n7 = Node(7)
# n2 = Node(2, n4, n5)
# n3 = Node(3, n6, n7)
# n1 = Node(1, n2, n3)
print(zigzag_order(n1))
# output 1:
# [1, 3, 2, 4, 5, 6, 7, 15, 14, 13, 12, 11, 10, 9, 8]
#
# output 2:
# [1, 3, 2, 4, 5, 6, 7] |
03007a91f57356bf2f8bcfb6649020f08666f59e | Zugwang/PrepaGithub | /TD2/ex7.py | 886 | 3.640625 | 4 | def addition(i):
return i + 2
def apply_function_global(t,f):
for i in range(len(t)):
t[i] = f(t[i])
def apply_function(t,f):
t2 = t.copy()
for i in range(len(t2)):
t2[i] = f(t[i])
return t2
def triplet_des():
list = []
for i in range(1,7):
for j in range(1,7):
for k in range(1,7):
a = i
b = j
c = k
list.append((a,b,c))
return list
def somme_produit_triplet(t):
somme = t[0] + t[1] + t[2]
produit = t[0] * t[1] * t[2]
return (somme,produit)
def fonction_finale():
t_somme = []
t_produit = []
t_triplet = triplet_des()
for i in range(len(t_triplet)):
u = somme_produit_triplet(t_triplet[i])
t_somme.append(u[0])
t_produit.append(u[1])
return (t_somme,t_produit)
print(fonction_finale())
|
d4fc9bc982916da6bb8a7f16f86b150804acb3a5 | aviadr1/learn-python3 | /content/_build/jupyter_execute/08_test_driven_development/exercise/questions.py | 2,353 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
#
# <a href="https://colab.research.google.com/github/aviadr1/learn-advanced-python/blob/master/content/08_test_driven_development/exercise/questions.ipynb" target="_blank">
# <img src="https://colab.research.google.com/assets/colab-badge.svg"
# title="Open this file in Google Colab" alt="Colab"/>
# </a>
#
# # Unit testing a contact list
#
# The code sample below has `Contact` class that contains both a `Person` and an `Address` class, and finally, a `Notebook` class that contains multiple contacts.
#
# Can you use `pytest` and `unittest.mock` modules to write tests for these classes and fix the bugs in this code
# In[1]:
### useful: This is the code you should test
class Address:
def __init__(self, street, city):
self.street = str(street)
self.city = str(city)
def __repr__(self):
return f"Address({self.city!r}, {self.street!r})"
class Person:
def __init__(self, name, email):
self.name = name
self.email= email
def __repr__(self):
return f"Person({self.name!r}, {self.email!r})"
class Contact:
def __init__(self, street, city, name, email, **kwargs):
self.person = Person(name, email)
self.address = Address(street, city)
def __str__(self):
return f""" {self.person.name}:
{self.person.email}
address:
{self.address.city}
{self.address.street}
"""
class Notebook:
def __init__(self):
self.contacts = dict()
def add(self, street, city, name, email):
self.contacts[name] = Contact(name, email, city, street)
def remove(name):
self.contacts.remove(name)
def __str__(self):
results = []
for name, contact in self.contacts.items():
results.append(str(contact))
results.append("")
return '\n'.join(results)
# In[43]:
# In[2]:
### useful: run the tests you wrote
import ipytest
# enable pytest's assertions and ipytest's magics
ipytest.config(rewrite_asserts=True, magics=True)
# set the filename
__file__ = 'ex 08 - solutions.ipynb'
# execute the tests via pytest, arguments are passed to pytest
ipytest.run('-qq')
#
# ```{toctree}
# :hidden:
# :titlesonly:
#
#
# solutions
# ```
#
|
9ab57a37c993a7f3216244d5e13f8f996a095b23 | dr-ehret/examples | /regarding_args.py | 379 | 3.671875 | 4 | def print_twice(bruce): # parameter bruce is for definition only.
print(bruce)
print(bruce)
print_twice('caleb') # It can be any argument.
tosh = "Peter Tosh, that is..." # Use of variable.
print_twice(tosh)
##
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
y = "Hey, hey, my, my, "
z = "Rock and roll will never die"
print(cat_twice(y,z)) |
0222b8403a51a1b50eeccf0e47bfb213b1f345f8 | kwintasha/bataille-navale | /bataille navale/bataille navale amin.py | 1,925 | 3.578125 | 4 | from random import randint,choice
from turtle import *
reset()
setup(405,405,50,50)
speed(10)
hideturtle()
ordi1=()
ordi2=()
colonnes=("a","b","c","d","e","f","g","h")
lignes=("1","2","3","4","5","6","7","8")
def plouf(col,lign,coul):
up()
x=-160+(ord(col)-97)*40
y=160-(ord(lign)-48)*40
color(coul)
goto(x,y)
begin_fill()
for line in range (4):
forward(40)
left(90)
end_fill()
def dessinquadrillage():
color("#A034C0","#A004C0")
for ligne in range (8+1):
up()
goto(-4*40,4*40-40*ligne)
down()
forward(40*8)
left(90)
for col in range (8+1):
up()
goto(-4*40+40*col,-4*40)
down()
forward(40*8)
right(90)
def bateau():
colonne=choice(colonnes)
ligne=choice(lignes)
return colonne,ligne
def saisie(colonnes,lignes):
saisie=True
while saisie:
s=input('Saisir une lettre entre a et h et puis un numero entre 1 et 8 (Ex: d1):')
if s[0] in colonnes and s[1] in lignes:
c=s[0]
l=s[1]
saisie=False
else:
print('Tir en dehors du jeu.')
return c,l
def traitement(joueur,ordi1):
global jouer
touché1=False
touché2=False
if joueur[0]==ordi1[0] and joueur[1]==ordi1[1]:
print('Gagné')
if touché1==False:
jouer=-1
touché1=True
return "red"
elif joueur[0]==ordi1[0] or joueur[1]==ordi1[1]:
print('En vue')
return "yellow"
else:
print("A l'eau")
return "blue"
while ordi1==ordi2:
ordi1=bateau()
ordi2=bateau()
jouer=2
while jouer:
dessinquadrillage()
print(ordi1)
joueur=saisie(colonnes,lignes)
print(joueur)
coul=traitement(joueur,ordi1)
plouf(joueur[0],joueur[1],coul) |
eea378921a111c7a93a483b104deb3857a473b80 | ArthurGini/EstudosPython | /Processsos Estagio/Strings.py | 534 | 3.875 | 4 | import re
#Determinar a maior palavra em uma string
print ("\nprograma 1: Exibir a maior palavra ")
string = "Aquela boa e velha frase"
string = string.split()
print(max(string, key=len))
#Transformar a string em Camel Case
print ("\nprograma 2: Editar frases para Camel Case")
camel = "camel case bom e velho"
camel = camel.title()
print(camel)
print ("\nprograma 3: tirar os char especial")
string = "hey th~~^^^~$#@$ere"
#char = re.sub('[^a-zA-Z0-9\.]', '', string)
string = re.sub('[^a-zA-Z0-9 \\\]', '', string)
print(string) |
3dbd10a141f84dfd148cd0de86aec7e5ea5a5aec | mabogunje/preschool-poker | /PreschoolPoker.py | 5,642 | 3.59375 | 4 | '''
author: Damola Mabogunje
contact: damola@mabogunje.net
summary: This program allows the user to pit a Reinforcement learning AI
against one of four opponents in a game of PreschoolPoker
multiple times to allow the AI to learn an optimal strategy.
'''
import argparse;
from poker import StudPoker, DrawOnePoker;
from player import *;
GAMES = [StudPoker(), DrawOnePoker()];
ROBOTS = [DumbPlayer('Randy'), OddPlayer('OddBall'), SmartPlayer('Deep Preschooler')];
DEFAULT_TRIALS = 10;
LEARNING_RATE = 0.2; # EDIT HERE to modify default learning rate
def main():
parser = argparse.ArgumentParser(prog="Preschool Poker", description="%(prog)s is a reinforcement learning program for a simplified version of poker.\
You may play against the computer or have it play one of its robot AI's to learn.", epilog="This program was developed by Damola Mabogunje")
parser.add_argument('-t', '--type', metavar='GAME_TYPE', type=int, choices=range(len(GAMES)),
help='Game Type. Must be an integer from [%(choices)s]'
);
parser.add_argument('-o', '--opponent', metavar='OPPONENT', type=int, choices=range(len(ROBOTS)),
help='Robot Opponent. Must be an integer from [%(choices)s]'
);
parser.add_argument('-n', '--trials', metavar='NUMBER_OF_TRIALS', type=int, nargs='?',
default=DEFAULT_TRIALS,
help='Number of times to play game. Must be a positive integer.'
);
parser.add_argument('-r', '--rate', metavar='LEARNING_RATE', type=float, nargs='?',
default=LEARNING_RATE,
help='Speed of learning. Must be a float between 0 and 1.'
);
args = parser.parse_args();
run(args.type, args.opponent, args.trials, args.rate);
def run(game, opponent, trials, learning_rate):
if not game in range(len(GAMES)):
prompt = "> Which Poker rules do you play by?";
print prompt;
for i,game in enumerate(GAMES):
print "(%d): %s" % (i, game.__class__.__name__);
game = GAMES[input()];
else:
game = GAMES[game];
if not opponent in range(len(ROBOTS)):
prompt = "> Who should I learn from? (Enter 3 to play against me)";
print prompt;
for i,player in enumerate(ROBOTS):
print "(%d): %s" % (i, player.name);
try:
opponent = ROBOTS[input()] ;
except:
opponent = Player(raw_input("Enter your name: "));
else:
opponent = ROBOTS[opponent];
player = Learner('Computer', learning_rate);
players = [player, opponent];
if type(opponent) == type(Player("Instance")):
while run_interactive(game, players[0], players[1]):
# Clear player cards and start a new game of the same type
game = DrawOnePoker() if isinstance(game, DrawOnePoker) else StudPoker();
player.cards = [];
opponent.cards = [];
players = [players[1], players[0]];
else:
for i in range(trials):
game.play(players[0], players[1]);
'''
Clear player cards
Start a new game of the same type
Reverse play order
'''
game = DrawOnePoker() if isinstance(game, DrawOnePoker) else StudPoker();
player.cards = [];
opponent.cards = [];
players = [players[1], players[0]];
print "\nState probabilities:"
for hand, weight in sorted(player.weights.items(), key=lambda w: w[1]):
print "%s => %s" % (hand, weight);
def run_interactive(game, player, opponent):
'''
Play a game of poker with a human opponent
'''
players = [player, opponent];
bot = player if isinstance(player, Learner) else opponent;
human = opponent if type(opponent) == type(Player("Instance")) else player;
print '''
============================
GAME START
============================
'''
for p in players:
p.draw(2, game.deck);
print "%s's Hand: %s\n" % (human.name, human.cards);
if isinstance(game, DrawOnePoker):
prompt = "> What will you do?";
print prompt;
moves = dict(enumerate(human.get_moves()));
for i, move in moves.items():
print "(%d): %s" % (i, Action.describe(move));
action = moves[input()];
for p in players:
if p is human:
if action is Action.STAND:
p.stand();
elif action is Action.DISCARD_ONE:
human.discard(Card.ONE, game.deck);
elif action is Action.DISCARD_TWO:
human.discard(Card.TWO, game.deck);
elif action is Action.DISCARD_TWO:
human.discard(Card.THREE, game.deck);
print "You performed '%s'" % Action.describe(action);
else:
print "\nI shall '%s'" % Action.describe(p.play(game.deck));
print "\nMy Hand: %s" % bot.cards;
print "%s's Hand: %s" % (human.name, human.cards);
winner = game.winner(human, bot);
if winner:
if winner is bot:
bot.learn(tuple(set(bot.cards)), game.WIN);
else:
bot.learn(tuple(set(bot.cards)), game.LOSE);
print "Winner: %s" % winner.name;
else:
print "Draw";
prompt = "> Play again (y/n)?";
return (raw_input(prompt).lower() == 'y');
if __name__ == "__main__":
main();
|
42e463c60b8cca356ae31d70542b98bed9b4691c | GaryVermeulen/gdata | /data_structures/tree3.py | 7,756 | 4.15625 | 4 | # Data and structures (classes, lists, tuples, hashes, dicts, hybirds)
#
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
# Original recursive code
#if self.data:
# if data < self.data:
# if self.left is None:
# self.left = Node(data)
# else:
# self.left.insert(data)
# elif data > self.data:
# if self.right is None:
# self.right = Node(data)
# else:
# self.right.insert(data)
#else:
# self.data = data
# Non-recursive
# Create a new node
# node = TreeNode(data)
if (self == None):
# When adds a first node in bst
self.data = data
else:
find = self
# Add new node to proper position
while (find != None):
if (find.data >= data):
if (find.left == None):
# When left child empty
# So add new node here
find.left = data
return
else:
# Otherwise
# Visit left sub-tree
find = find.left
else:
if (find.right == None):
# When right child empty
# So add new node here
find.right = data
return
else:
# Visit right sub-tree
find = find.right
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data) # WHat does this comma do? ,
if self.right:
self.right.PrintTree()
# Inorder traversal
# Left -> Root -> Right
def inorderTraversal(self, root):
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
# Preorder traversal
# Root -> Left ->Right
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
return res
# Postorder traversal
# Left ->Right -> Root
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)
res.append(root.data)
return res
# findval method to compare the value with nodes
def findval(self, lkpval):
print('start')
if lkpval < self.data:
if self.left is None:
return str(lkpval)+" Not Found"
return self.left.findval(lkpval)
elif lkpval > self.data:
if self.right is None:
return str(lkpval)+" Not Found"
return self.right.findval(lkpval)
else:
print(str(self.data) + ' is found')
# getVal method to compare the value with nodes
def getVal(self, lkpval):
if lkpval < self.data:
if self.left is None:
return str(lkpval)+" Not Found"
return self.left.getVal(lkpval)
elif lkpval > self.data:
if self.right is None:
return str(lkpval)+" Not Found"
return self.right.getVal(lkpval)
else:
# print(str(self.data) + ' is found')
return self.data
# Iterative function for inorder tree traversal
def inOrder(root):
# Set current to root of binary tree
current = root
stack = [] # initialize stack
while True:
# Reach the left most Node of the current Node
if current is not None:
# Place pointer to a tree node on the stack
# before traversing the node's left subtree
stack.append(current)
current = current.left
# BackTrack from the empty subtree and visit the Node
# at the top of the stack; however, if the stack is
# empty you are done
elif(stack):
current = stack.pop()
print(current.data, end=" ") # Python 3 printing
# We have visited the node and its left
# subtree. Now, it's right subtree's turn
current = current.right
else:
break
print()
fData = 'data.txt'
fDict = 'dict.csv'
def getAllData():
allData = []
with open(fData, 'r') as f:
while (line := f.readline().rstrip()):
if '#' not in line:
line = line.replace(' ', '')
line = line.split(";")
if line[0] != '#':
# print(line)
allData.append(line)
f.close()
return allData
# END getAllData()
def getDict():
allDict = []
with open(fDict, 'r') as f:
while (line := f.readline().rstrip()):
if '#' not in line:
# line = line.replace(' ', '')
line = line.split(",")
if line[0] != '#':
# print(line)
allDict.append(line)
f.close()
return allDict
# END getDict()
#myDict = getDict()
#print(len(myDict))
#print(type(myDict))
#for d in myDict:
# print(d)
###
# Not be able to use cuurent tree objects for large
# datasets with Python recursion limit of 1000
#
###
#
#allData = getAllData()
#
#print(len(allData))
#
#for d in allData:
# print(d)
#
#allData.sort()
#
#print(type(allData))
#print(len(allData))
#
#for s in allData:
# print(s)
# Use the insert method to add nodes
# Orginal sample data
#root = Node(12)
#root.insert(6)
#root.insert(14)
#root.insert(3)
#nodeA = 3
#nodeB = 6
#nodeC = 12
#nodeD = 14
#nodeE = 32
#nodeF = 64
# max dicts
# 2^27 = 134,217,728
#
#MAX = 134217728
#halfMAX = 134217728 / 2
# Python max recursion is 1000
#
MAX = 180000 # 2001 # Max with recursion
halfMAX = MAX / 2
#
print(MAX)
print(str(int(halfMAX)))
#
root = Node(int(halfMAX))
#
for n in range(MAX):
root.insert(n)
#nodeA = ['A', 'red', 'apple', 'tree']
#nodeB = ['B', 'blue', 'bird', 'sky']
#nodeC = ['C', 'green', 'bean', 'tree']
#nodeD = ['D', 'dog', 'paw', 'tail']
#nodeE = ['E', 'cat', 'paw', 'claw']
#nodeF = ['F', 'frank', 'man', 'hat']
#
#root = Node(nodeD)
#root.insert(nodeA)
#root.insert(nodeB)
#root.insert(nodeC)
#root.insert(nodeE)
#root.insert(nodeF)
#print('root.PrintTree')
#root.PrintTree()
#print('inorder')
#print(root.inorderTraversal(root))
#print('preorder')
#print(root.PreorderTraversal(root))
#print('postorder')
#print(root.PostorderTraversal(root))
#print('--------')
#print(root.findval(3))
#print('--------')
#print(root.findval(1))
#print(root.findval(['E', 'cat', 'paw', 'claw']))
#print('--------')
#ret = root.getVal(1)
#print(ret)
|
10489d194279d9da63df299d9a7a0e5061a21c27 | JoelAtDeluxe/DailyCodingProblem | /7/solution.py | 2,010 | 3.8125 | 4 | # Given:
# coding = {
# "a": "1",
# "b": "2",
# ...
# "z": "26"
# }
# how many ways are there to decode a particular message?
# for example, we could be given the message:
# "abc", which encoded is "123"
# But going in reverse, to decode, we could end up with:
# (a, b, c), (a, w), (l, c)
# Given "cab" (312) we could only get:
# (c, a, b), (c, l)
# And given "dog" (4157), we would get:
# (d, a, e, g), (d, o, g)
coding = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
"g": 7,
"h": 8,
"i": 9,
"j": 10,
"k": 11,
"l": 12,
"m": 13,
"n": 14,
"o": 15,
"p": 16,
"q": 17,
"r": 18,
"s": 19,
"t": 20,
"u": 21,
"v": 22,
"w": 23,
"x": 24,
"y": 25,
"z": 26,
}
decoding = {v: k for k, v in coding.items()}
def encode(word):
encoded = []
for letter in word:
encoded.append(coding[letter])
return ''.join([str(i) for i in encoded])
class Tree(object):
def __init__(self, data=None):
self.data = data
self.left: Tree = None
self.right: Tree = None
def get_in_prefix(self):
data = [self.data] if self.data is not None else []
right_data = self.right.print_prefix() if self.right is not None else []
left_data = self.left.print_prefix() if self.left is not None else []
return [*data, *left_data, *right_data]
def count_leaves(self):
leaves = 0
if self.left is None and self.right is None:
return 1
if self.left is not None:
leaves += self.left.count_leaves()
if self.right is not None:
leaves += self.right.count_leaves()
return leaves
def decode(code):
root = build_tree(Tree(), code)
return root
def build_tree(root, code):
if code is None or len(code) == 0:
return root
root.left = build_tree( Tree(decoding[int(code[0])]), code[1:])
if len(code) > 1 and int(''.join(code[0:2])) in decoding:
root.right = build_tree( Tree(decoding[int(code[0:2])]), code[2:])
return root
tree = decode(encode("ball"))
print( tree.count_leaves() ) |
2d126c0c9623452ad88783cd6de9f0595acd17da | Vitalismirnov/Problem_Set | /problem9.py | 850 | 3.9375 | 4 | # This is a work by
# Vitalijs Smirnovs
# Stydent ID # g00317774
# Problem 9: Write a program that reads in a text file and outputs evry secondline.
# The program should take the filename from an argument on the command line.
# open a text file, save as openfile
# openfile = open('theinvisibleman.txt')
# to read filename from a command line:
# import sys
import sys
# to read in file from a command line as an argument 2
openfile = open(sys.argv[1])
lines = openfile.readlines()
# count number of lines
# from https://www.sanfoundry.com/python-program-count-lines-text-file/
linecount = 0
for line in lines:
linecount += 1
openfile.close()
# to print every second line, start with line 2
i=2
# while counter is less or equal number lines, print every second line
for each in lines:
while i<=linecount:
print(lines[i])
i=i+2 |
54122d064370dc4e4e5f84adbd5c78c862128b3d | libo-sober/LearnPython | /day24/__call__方法.py | 563 | 3.90625 | 4 | # callable(对象)
# 对象() 能不能运行,就是callabele判断的事
class A:
def __call__(self, *args, **kwargs):
print('---------------')
obj = A()
print(callable(obj))
obj() # 对象加括号调用类中的__call__方法
# A()()
# __len__
class Clas:
def __init__(self, name):
self.name = name
self.students = []
def __len__(self):
return len(self.students)
py2 = Clas('py2')
py2.students.append('nihao')
py2.students.append('nihao')
py2.students.append('nihao')
# print(len(py2.students))
print(len(py2)) |
be07019bc55be95a2a00065a83a6fe413fdde0c4 | suhanacharya/student-db-demo | /database.py | 644 | 3.703125 | 4 | import sqlite3
def init_db():
with sqlite3.connect("student.db") as conn:
c = conn.cursor()
c.execute("""
CREATE TABLE Students(
name TEXT,
usn TEXT PRIMARY KEY,
sem INT
);
""")
conn.commit()
c.execute("""
CREATE TABLE Teachers(
name TEXT,
eno TEXT PRIMARY KEY,
subject TEXT
);
""")
conn.commit()
init_db() |
9825987008b446218528fd008985ff8609a386cf | jonathf/numpoly | /numpoly/array_function/square.py | 1,798 | 3.875 | 4 | """Return the element-wise square of the input."""
from __future__ import annotations
from typing import Any, Optional
import numpy
from ..baseclass import ndpoly, PolyLike
from ..dispatch import implements
from .multiply import multiply
@implements(numpy.square)
def square(
x: PolyLike,
out: Optional[ndpoly] = None,
where: numpy.typing.ArrayLike = True,
**kwargs: Any,
) -> ndpoly:
"""
Return the element-wise square of the input.
Args:
x:
Input data.
out:
A location into which the result is stored. If provided, it must
have a shape that the inputs broadcast to. If not provided or
`None`, a freshly-allocated array is returned. A tuple (possible
only as a keyword argument) must have length equal to the number of
outputs.
where:
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value. Note
that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
kwargs:
Keyword args passed to numpy.ufunc.
Return:
Element-wise `x*x`, of the same shape and dtype as `x`.
This is a scalar if `x` is a scalar.
Example:
>>> numpoly.square([1j, 1])
polynomial([(-1+0j), (1+0j)])
>>> poly = numpoly.sum(numpoly.variable(2))
>>> poly
polynomial(q1+q0)
>>> numpoly.square(poly)
polynomial(q1**2+2*q0*q1+q0**2)
"""
return multiply(x, x, out=out, where=where, **kwargs)
|
704a26c6cb9e86a4ccf61abe9aeeb04615bad60a | Seezium/Algorithms | /GetTheMiddleChar/GetTheMiddleChar.py | 250 | 3.78125 | 4 | def get_middle(s):
x = len(s)//2
if len(s) % 2 == 0:
return "{}{}".format(s[x-1],s[x])
else:
return s[x]
print(get_middle("test"))
print(get_middle("testing"))
print(get_middle("middle"))
print(get_middle("A"))
|
6133c44c5f99072ba95ce384aea4d9a619791aab | ISFP1021/Lecture7inclass | /L7E4.py | 153 | 3.8125 | 4 | def printlist(title, alist):
print (title)
for i in alist:
print (i)
somelist=[1,45,87,'go']
title="The Title"
printlist(title,somelist)
|
ee5cbf7e426223a464a8770d03e958d9abce3118 | MarkintoshZ/FontTransformer | /demo/gui.py | 5,122 | 3.796875 | 4 | import pygame, math, sys
pygame.init()
from model import evaluate, refresh
import numpy as np
X = 900 # screen width
Y = 600 # screen height
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 50, 50)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 50)
BLUE = (50, 50, 255)
GREY = (200, 200, 200)
ORANGE = (200, 100, 50)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
TRANS = (1, 1, 1)
flow = False # controls type of color flow
class Gradient():
def __init__(self, palette, maximum):
self.COLORS = palette
self.N = len(self.COLORS)
self.SECTION = maximum // (self.N - 1)
def gradient(self, x):
"""
Returns a smooth color profile with only a single input value.
The color scheme is determinated by the list 'self.COLORS'
"""
i = x // self.SECTION
fraction = (x % self.SECTION) / self.SECTION
c1 = self.COLORS[i % self.N]
c2 = self.COLORS[(i+1) % self.N]
col = [0, 0, 0]
for k in range(3):
col[k] = (c2[k] - c1[k]) * fraction + c1[k]
return col
def wave(num):
"""
The basic calculating and drawing function.
The internal function is 'cosine' >> (x, y) values.
The function uses slider values to variate the output.
Slider values are defined by <slider name>.val
"""
for i, letter in enumerate('abcdefghijklmnopqrstuvwxyz'):
evaluate(i, np.array([s.val for s in slides]))
sprite = pygame.image.load('out.png')
sprite = pygame.transform.scale2x(sprite)
rect = sprite.get_rect()
rect.center = (50 + i % 13 * 62, 50 + i//13 * 90)
screen.blit(sprite, rect)
class Slider():
def __init__(self, name, val, maxi, mini, pos):
self.val = val # start value
self.maxi = maxi # maximum at slider position right
self.mini = mini # minimum at slider position left
self.xpos = pos # x-location on screen
self.ypos = 550
self.surf = pygame.surface.Surface((100, 50))
self.hit = False # the hit attribute indicates slider movement due to mouse interaction
self.txt_surf = font.render(name, 1, BLACK)
self.txt_rect = self.txt_surf.get_rect(center=(50, 15))
# Static graphics - slider background #
self.surf.fill((100, 100, 100))
pygame.draw.rect(self.surf, GREY, [0, 0, 100, 50], 3)
pygame.draw.rect(self.surf, ORANGE, [10, 10, 80, 10], 0)
pygame.draw.rect(self.surf, WHITE, [10, 30, 80, 5], 0)
self.surf.blit(self.txt_surf, self.txt_rect) # this surface never changes
# dynamic graphics - button surface #
self.button_surf = pygame.surface.Surface((20, 20))
self.button_surf.fill(TRANS)
self.button_surf.set_colorkey(TRANS)
pygame.draw.circle(self.button_surf, BLACK, (10, 10), 6, 0)
pygame.draw.circle(self.button_surf, ORANGE, (10, 10), 4, 0)
def draw(self):
""" Combination of static and dynamic graphics in a copy of
the basic slide surface
"""
# static
surf = self.surf.copy()
# dynamic
pos = (10+int((self.val-self.mini)/(self.maxi-self.mini)*80), 33)
self.button_rect = self.button_surf.get_rect(center=pos)
surf.blit(self.button_surf, self.button_rect)
self.button_rect.move_ip(self.xpos, self.ypos) # move of button box to correct screen position
# screen
screen.blit(surf, (self.xpos, self.ypos))
def move(self):
"""
The dynamic part; reacts to movement of the slider button.
"""
self.val = (pygame.mouse.get_pos()[0] - self.xpos - 10) / 80 * (self.maxi - self.mini) + self.mini
if self.val < self.mini:
self.val = self.mini
if self.val > self.maxi:
self.val = self.maxi
font = pygame.font.SysFont("Verdana", 12)
screen = pygame.display.set_mode((X, Y))
clock = pygame.time.Clock()
COLORS = [MAGENTA, RED, YELLOW, GREEN, CYAN, BLUE]
xcolor = Gradient(COLORS, X).gradient
pen = Slider("1", 0, 1, -1, 25)
freq = Slider("2", 0, 1, -1, 150)
jmp = Slider("3", 0, 1, -1, 275)
size = Slider("4", 0, 1, -1, 400)
focus = Slider("5", 0, 1, -1, 525)
phase = Slider("6", 0, 1, -1, 650)
speed = Slider("7", 0, 1, -1, 775)
slides = [pen, freq, jmp, size, focus, phase, speed]
num = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for s in slides:
if s.button_rect.collidepoint(pos):
s.hit = True
elif event.type == pygame.MOUSEBUTTONUP:
for s in slides:
s.hit = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
refresh()
# Move slides
for s in slides:
if s.hit:
s.move()
# Update screen
screen.fill(WHITE)
num += 2
wave(num)
for s in slides:
s.draw()
pygame.display.flip()
clock.tick(30)
|
25b7ab214d5628a0246a6e63226323789a46fb94 | Alkhithr/Mary | /BUCI057N0/recap/exam2014.py | 1,379 | 3.8125 | 4 | def compute_sum(L):
total = 0
for i in range(0, len(L)):
if i % 2 == 0:
total += L[i]
else:
total -= L[i]
return total
def get_fib(n):
fib = [0, 1, 1]
i = 3
while len(fib) <= n:
fib.append(fib[i-1] + fib[i-2])
i += 1
return fib[n], fib
def not_string(x):
result = 'not ' + x
if x[0:3] == 'not':
result = x
return result
def missing_char(x, n):
return x[0:n] + x[n:]
def main():
# L = [3, 4, 5, 10]
# print('the sum of {} is:'.format(L, compute_sum(L)))
# print('The {} position of the fib sequence is {}'.format(21, get_fib(21)))
# n = 0
# n_list = []
#
# while n != 99:
# n = int(input('Enter number: '))
# n_list.append(n)
#
# n_list = n_list[:-1]
# total = 1
# for i in range(0, len(n_list)):
# if i % 2 == 0:
# print(n_list[i])
# total *= n_list[i]
# print('The every other product of {} is {}'.format(n_list, total))
assert not_string('not') == 'not'
assert not_string('antonio') == 'not antonio'
assert not_string('antonio not') == 'antonio not'
assert not_string('candy') == 'not candy'
assert missing_char('kitten', 1) == 'ktten'
assert missing_char('kitten', 0) == 'itten'
assert missing_char('kitten', 4) == 'kittn'
main()
|
096120ce265e99413660d6ee1974782b351e4ee3 | ItamarHavenstein-zz/Python | /Exercicio41a50/ex049.py | 145 | 3.734375 | 4 | tabuada = int(input('Digite a tabuada que vc deseja: '))
for c in range(1, 11):
print('{} X {} = {}'.format(tabuada, c, (tabuada * c)))
|
0dd6822ea8b887d410e9da7f526ac8d69f12f629 | Pattol/20F_CST8279_300-Intro-to-Comp.-Prog.-using-Python | /Random.py | 295 | 4.03125 | 4 | # Pattol Albadry
# Sep 17.2020
# Lab 2: Demo code
from random import randint
roll = input("press Y to roll the dice, press N to quit")
while roll.lower () == "y":
print(randint(1,10))
roll = input("press Y to roll again, press N to quit")
print("okay, we'll put the dice away.")
|
e131cb909698c19f74df6babd2cb2da072ec6993 | varunverma760/Python | /patterns.py | 158 | 4.15625 | 4 | print("Enter the value of n")
n=int(input())
i=1
while i<=n:
j=1
while j<=n:
#print the jth column
print('*',end='')
j=j+1
print()
i=i+1
|
8fdb8cbe0a0f0db586c55dc6bb4e483b4e1d3953 | ASKJR/URI-judge | /Python/2803.py | 262 | 3.515625 | 4 | '''
Problem: Estados do Norte
URI Online Judge | 2803
Solution developed by: Alberto Kato
'''
northStates = ['roraima', 'acre', 'amapa', 'amazonas', 'para', 'rondonia', 'tocantins']
if input() in northStates:
print('Regiao Norte')
else:
print('Outra regiao')
|
c1e5dba8045f1443b7a9693a0663c109a40657d0 | eladeliav/PythonProjects | /School2018PY/Slicing2.py | 480 | 3.96875 | 4 | """Slicing Exercises
Elad Eliav"""
def analyze_number():
"""
gets number and analyzes
"""
num = raw_input("Enter num: ")
diglist = list(num)
# Create list of ints for the number
sum_of_digs = sum([int(r) for r in diglist])
print("You entered: " + num)
print("The digits: " + ", ".join(diglist))
print("The sum: " + str(sum_of_digs))
def main():
"""calls analyze_number()"""
analyze_number()
if __name__ == '__main__':
main()
|
551c877a2da034b6ea820791ab5bb22f7decba17 | MayankHirani/PowerWorld2019 | /PowerWorld Work Summer 2019/Other/old_method.py | 1,030 | 3.5 | 4 | # Old way of timing (Outdated)
# Number of values that the average will be calculated from. The more
# values used, the more accurate results will be. Adjust this value if
# runtime is too long or too short
precision = 100
# Make a list of timings to get a more accurate mean
timings = [ timeit.timeit('solve', 'from __main__ import solve', number=1000) for x in range(precision + 1) ]
# The first time is always much longer, so delete this one
del timings[0]
# Remove the timings that are 0, and replace them with other timings
timings_filtered = [ ]
for timing in timings:
if timing != 0:
timings_filtered.append(timing)
else:
x = 0
while x == 0:
x = timeit.timeit('solve', 'from __main__ import solve', number=1000)
timings_filtered.append(x)
# Convert the average time to scientific notation for readability
average = sum(timings_filtered)/precision
average = '%.4E' % Decimal(average)
# Calculate the mean time from the list of values
print("Average time:", average, "sec") |
e19b7ab0f7defb696c9f8185c5c74399190051d7 | jgathogo/python_level_1 | /week3/problem6.py | 3,980 | 4 | 4 | import os
import sys
import math
"""
Notes:
- Excellent job! I'm glad that you figured out the correct equations to compute
the internal angles. I see that this has also forced you to read up on
Python math library. This is exactly the kind of activity by which someone
grows, not just attending class but solving problems in increasing difficulty.
- Remember to run 'clean' often to make sure that the correct number of spaces
between functions etc. This habit will come in handy when we start writing classes
since quite often we want to fold code and make sure we have enough space
between methods.
- I see you have 'reused' x, y, and z. Try and avoid that. It's innocent acts like
these that lead to very hard to track down bugs.
- I hope it's also becoming apparent how linear code quickly begins to clutter your module.
Once we get into functions our code can get a whole lot cleaner. But for now this
is perfectly OK because we are concentrating on other constructs.
- [DONE] Trivial point: in terms of presentation of floating point numbers, one can use
round() to clean things up. Typically, 4 decimal places is sufficient.
- Read the scoring notes in scores.txt
"""
def main():
print("Enter values for point A")
x1, y1, z1 = input("Enter values x1, y1 and z1 separated by a comma and space: ").split(", ")
print("Enter values for point B")
x2, y2, z2 = input("Enter values x2, y2 and z2 separated by a comma and space: ").split(", ")
x1 = float(x1)
y1 = float(y1)
z1 = float(z1)
x2 = float(x2)
y2 = float(y2)
z2 = float(z2)
x = (x1 - x2) ** 2
y = (y1 - y2) ** 2
z = (z1 - z2) ** 2
# If we strive that our code only always ever refer to a and b
# then we can never be confused.
# This is the power of good variable naming to be in line with the
# domain application. I call this 'avoiding logical tension'.
# Try and imagine how mind-scrambling it gets when you start dealing
# with an application spanning 5 packages each with 10 modules with
# each module extending to over 2000 lines of code (LOC).
# Variable names matter a lot! ;-)
# o = (0, 0, 0)
# a = (x1, y1, z1)
# b = (x2, y2, z2)
# d_ab = round(math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2)), 4)
# d_ao = round(math.sqrt((a[0]-o[0])**2 + (a[1]-o[1])**2 + (a[2]-o[2])**2)), 4)
# d_bo = round(math.sqrt((b[0]-o[0])**2 + (b[1]-o[1])**2 + (b[2]-o[2])**2)), 4)
# angle_o = math.acos(math.degrees((d_ao ** 2 + d_bo ** 2 - d_ab ** 2) / (2*d_ao * d_bo)))
# ...
d_ab = round(math.sqrt(x + y + z), 4)
print(f"a. The distance between point A{x1, y1, z1} and B{x2, y2, z2} is: {d_ab}")
# Distance between points and origin
m = (0 - x1) ** 2
n = (0 - y1) ** 2
o = (0 - z1) ** 2
d_ao = round(math.sqrt(m + n + o), 4)
print(f"b.1 . Distance between point A{x1, y1, z1} and origin(0, 0, 0) is: {d_ao}")
r = (0 - x2) ** 2
s = (0 - y2) ** 2
t = (0 - z2) ** 2
d_bo = round(math.sqrt(r + s + t), 4)
print(f"b.2 . Distance between point B{x2, y2, z2} and origin(0, 0, 0) is: {d_bo}")
# Use cosine rule to compute internal angles
a = d_ao
b = d_bo
c = d_ab
cos_d = (a ** 2 + b ** 2 - c ** 2) / (2 * a * b)
angle_d = round(math.degrees(math.acos(cos_d)), 4)
print(f"Angle D, at origin, (in degrees) is: {angle_d}")
a = d_ab
b = d_bo
c = d_ao
cos_d = (a ** 2 + b ** 2 - c ** 2) / (2 * a * b)
angle_da = round(math.degrees(math.acos(cos_d)), 4)
print(f"Angle A (in degrees) is: {angle_da}")
a = d_ab
b = d_ao
c = d_bo
cos_d = (a ** 2 + b ** 2 - c ** 2) / (2 * a * b)
angle_db = round(math.degrees(math.acos(cos_d)), 4)
print(f"Angle B (in degrees) is: {angle_db}")
print(f"Check if the three angles add up to 180 degrees: "
f"{angle_d + angle_da + angle_db == 180.0}")
return os.EX_OK
if __name__ == "__main__":
sys.exit(main())
|
53694c19010288180b97649fd680afe56e3c2bc2 | harihavwas/pythonProgram | /fUNCTIONAL PROGRAMMING/Lambda/demo.py | 387 | 3.9375 | 4 | # To reduce code
'''
def cb(n):
print("Result : ",n**3)
n=int(input("Enter number : "))
cb(n)
'''
# Cube
'''
cube=lambda n:n**3
print(cube(5))
'''
# Addition
'''
add=lambda a,b:a+b
print(add(2,3))
'''
# String
'''
str=lambda s:s[0]
print(str(input("Enter String : ")))
'''
#even or not
demo=lambda n:n%2
if(demo(int(input("Enter a number : ")))):print("Odd")
else:print("Even") |
1dd51c30c17143c7ecd61ae1125b7fd1c4dab7de | u101022119/NTHU10220PHYS290000 | /student/101022109/mydate.py | 1,529 | 3.921875 | 4 | class Date :
def __init__(self,x,y,z):
self.day = int(x)
self.month = int(y)
self.year = int(z)
def print_date(self):
print '{0} / {1} / {2}'.format(self.month,self.day,self.year)
def increment_date(self,n = 0):
x,y,z = self.day , self.month , self.year
x += n
ans = Date(x,y,z)
change = True
while change == True:
ans.print_date()
change = False
if y in {1,3,5,7,8,10,12}:
if x >= 31:
x,y = x - 31, y + 1
change = True
elif y in {4,6,9,11}:
if x >= 30:
x,y = x- 30, y + 1
change = True
elif y ==2:
if z%4 != 0:
leapyear = False
elif z%100 != 0:
leapyear = True
elif z%400 != 0:
leapyear = False
else:
leapyear = True
if leapyear == True:
if x >= 29:
x,y = x - 29, y + 1
change = True
elif leapyear == False:
if x >= 28:
x,y = x - 28,y + 1
change = True
if y > 12:
y,z = y - 12, z + 1
change = True
ans = Date(x,y,z)
return ans
print 'finish!'
D = Date(6,16,2014)
D.increment_date(500)
|
75613981f87492df53ecd826667419a8255f7477 | muffinsofgreg/mitx | /6.1/fibN.py | 341 | 4.15625 | 4 | from math import sqrt
N = int(input("\n List Fibonacci sequence to nth place.\n What is your n: "))
def fib(n): #Binet's formula
fib_list = []
root = sqrt(5)
phi = (1 + root) / 2
for n in range(0, n):
bin = str(round(phi ** n / root))
fib_list.append(bin)
return fib_list
print(fib(N))
|
436ec22015f1ccd88e286cf95e4adfbd727738ac | pyc-ycy/PycharmProjects | /untitled/类的特有方法/WeatherSearch.py | 1,629 | 3.609375 | 4 | #!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
# @Time : 2018/9/8 10:15
# @Author : 御承扬
# @Site :
# @File : WeatherSearch.py
# @Software: PyCharm
class WeatherSearch(object):
def __int__(self, input_daytime):
self.input_daytime = input_daytime
def search_visibility(self):
visible_leave = 0
if self.input_daytime == "daytime":
visible_leave = 2
elif self.input_daytime == "night":
visible_leave = 9
return visible_leave
def search_temperature(self):
temperature = 0
if self.input_daytime == "daytime":
temperature = 26
elif self.input_daytime == "night":
temperature = 16
return temperature
class OutAdvice(WeatherSearch):
def __init__(self, input_daytime):
WeatherSearch.__int__(self, input_daytime)
def search_temperature(self):
vehicle = " "
if self.input_daytime == "daytime":
vehicle = "bike"
if self.input_daytime == "night":
vehicle = "taxi"
return vehicle
def out_advice(self):
visible_leave = self.search_visibility()
if visible_leave == 2:
print("the weather is good ,suitable for use %s" % self.search_temperature())
elif visible_leave == 9:
print("the weather bad,you should use %s" % self.search_temperature())
else:
print("the weather is beyond my scope, I can not give you any advice")
a = input("请输入白天或黑夜(英文)")
check = OutAdvice(a)
check.out_advice()
d = OutAdvice("night")
d.out_advice() |
5ce92b5223a88d2961572192a10d9b13ead2ed39 | domagojeklic/lunchbot | /orders.py | 6,456 | 3.953125 | 4 | class Meal:
'''
Holds information about individual meal orders
'''
def __init__(self, name: str, price: float, user: str):
self.name = name
self.price = price
self.users = [user]
def add_user(self, user: str):
self.users.append(user)
def total_number(self) -> int:
return len(self.users)
def total_price(self) -> float:
return self.total_number() * self.price
class Restaurant:
'''
Holds information about orders from individual restaurant
'''
def __init__(self, name):
self.name = name
self.meals_dict = {}
self.price_multiplier = 1.0
def add_meal(self, meal: Meal):
self.meals_dict[meal.name] = meal
def add_order(self, meal_name: str, meal_price: float, from_user: str):
if meal_name in self.meals_dict:
meal = self.meals_dict[meal_name]
meal.add_user(from_user)
else:
meal = Meal(meal_name, meal_price, from_user)
self.add_meal(meal)
def summarize(self) -> str:
totalPrice = 0
summarized = '*{0}:*\n'.format(self.name)
for meal_name, meal in self.meals_dict.items():
totalPrice += meal.total_price() * self.price_multiplier
summarized += '_{0}_, *{1}kn* x{2}'.format(meal_name, meal.price * self.price_multiplier, meal.total_number())
summarized += ' ('
for i in range(len(meal.users)):
u = meal.users[i]
summarized += '<@{0}>'.format(u)
if not i == len(meal.users) - 1:
summarized += ', '
summarized += ')\n'
summarized += '\n_Total:_ *{0}kn*'.format(totalPrice)
return summarized
def all_users(self) -> {str}:
'''
returns the list of users that have ordered meal from the restaurant
'''
users = set()
for _, meal in self.meals_dict.items():
for user in meal.users:
users.add(user)
return users
def notify(self, message) -> str:
all_users = self.all_users()
final_message = message if message != None else self.name
for user in all_users:
final_message += ' <@{0}>'.format(user)
return final_message
def apply_discount(self, percentage) -> str:
'''
applies discount to all meal prices
'''
if percentage > 0 and percentage < 100:
self.price_multiplier = 1.0 - percentage / 100.0
return 'Discount applied'
else:
return 'Percentage should be between 0 and 100'
class Orders:
'''
Holds information about orders from all restaurants
'''
def __init__(self):
self.restaurants_dict = {}
def add_order(self, restaurant_name: str, meal_name: str, meal_price :float, from_user: str):
rest_name_lower = restaurant_name.lower()
if rest_name_lower in self.restaurants_dict:
restaurant = self.restaurants_dict[rest_name_lower]
restaurant.add_order(meal_name, meal_price, from_user)
else:
restaurant = Restaurant(rest_name_lower)
restaurant.add_order(meal_name, meal_price, from_user)
self.restaurants_dict[rest_name_lower] = restaurant
def clear_all(self):
'''
Clears all orders from every restaurant
'''
self.restaurants_dict.clear()
def clear_restaurant(self, restaurant_name) -> str:
'''
Clears all orders from restaurant
'''
rest_name_lower = restaurant_name.lower()
if rest_name_lower in self.restaurants_dict.keys():
del self.restaurants_dict[rest_name_lower]
return 'All orders from *{0}* cleared!'.format(restaurant_name)
else:
return 'There are no orders from *{0}*'.format(restaurant_name)
def cancel_orders(self, from_user: str):
'''
Clears all orders from a particular user
'''
delete_restaurants = []
for restaurant_name, restaurant in self.restaurants_dict.items():
delete_meals = []
for meal_name, meal in restaurant.meals_dict.items():
if from_user in meal.users:
meal.users.remove(from_user)
if len(meal.users) == 0:
delete_meals.append(meal_name)
for meal_name in delete_meals:
del restaurant.meals_dict[meal_name]
if len(restaurant.meals_dict) == 0:
delete_restaurants.append(restaurant_name)
for restaurant_name in delete_restaurants:
del self.restaurants_dict[restaurant_name]
def summarize(self, restaurant_name: str) -> str:
'''
Returns formated description of all orders from restaurant
'''
if restaurant_name == None:
return 'Please specify restaurant name or *summarize all* for all restaurants'
elif restaurant_name in self.restaurants_dict:
restaurant = self.restaurants_dict[restaurant_name]
return restaurant.summarize()
else:
return 'There are no orders from *{0}*'.format(restaurant_name)
def summarize_all(self) -> str:
'''
Returns formated description of all orders from all restaurants
'''
summarized = ''
for restaurant in self.restaurants_dict.values():
summarized += restaurant.summarize()
summarized += '\n-----------------------------------------------------\n'
return summarized if len(summarized) > 0 else 'There are no orders'
def notify_restaurant(self,restaurant_name, message) -> str:
if restaurant_name in self.restaurants_dict:
restaurant = self.restaurants_dict[restaurant_name]
return restaurant.notify(message)
else:
return 'There are no orders from *{0}*'.format(restaurant_name)
def apply_discount(self, restaurant_name, percentage) -> str:
if restaurant_name in self.restaurants_dict:
restaurant = self.restaurants_dict[restaurant_name]
return restaurant.apply_discount(percentage)
else:
return 'There are no orders from *{0}*'.format(restaurant_name) |
db76a6dd791a2fd8c487bd027286e32b5dee7570 | sidaker/dq | /python_ques/global_scope.py | 1,068 | 3.984375 | 4 | ## Question. What happens if you don't define a variable as global.
## Scopre can be
## - LOCAL(inside current function), Enclosing, GLOBAL, Built-in (LEGB)
## you bind a name to an object
## Name resolution to objects is manged by scopes and scoping rules.
# https://www.programiz.com/python-programming/namespace
lcount=0
gcount=0
#print(id(lcount))
#print(id(gcount))
def showcount():
# lcount += 1 ## UnboundLocalError: local variable 'lcount' referenced before assignment
print(lcount, ' and ' ,gcount )
def setcount(c):
global gcount
#print(id(gcount))
lcount = c # c is bind to a new name called lcount in the inner most name space
# a new variable lcount is created in local name space which shadows access to glabal variable with same name
gcount = c
print(dir()) # What objects are in local or function name namespace?
#print(id(lcount))
#print(id(gcount))
if __name__=='__main__':
showcount()
setcount(3)
showcount()
print(dir()) # What objects are in global or module name namespace?
|
7d232966299b1355d974d4395e58e40f2fcacc08 | jamil-said/code-samples | /Python/Python_code_challenges/digitsProduct.py | 826 | 3.765625 | 4 | """ digitsProduct
Given an integer product, find the smallest positive (i.e. greater than 0) integer the
product of whose digits is equal to product. If there is no such integer, return -1 instead.
Example
For product = 12, the output should be
digitsProduct(product) = 26;
For product = 19, the output should be
digitsProduct(product) = -1.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer product
Guaranteed constraints:
0 ≤ product ≤ 600.
[output] integer
"""
def digitsProduct(p):
if p < 2:
return 10 if p == 0 else 1
res = ''
for i in range(9, 1, -1):
while p % i == 0:
res += str(i)
p //= i
return int((res)[::-1]) if p == 1 else -1
print(digitsProduct(12)) # 26
print(digitsProduct(19)) # -1
|
1f91d44ec43d5038a0379e57dd79660fcc719f2f | baejinsoo/algorithm_study | /algorithm_study/DataStructure/07_스택_완전구현.py | 891 | 3.828125 | 4 | ## 함수 선언부
def isStackEmpty():
global stack, top, SIZE
if (top <= -1):
return True
else:
return False
def isStackFull():
global stack, top, SIZE
if (top >= SIZE - 1):
return True
else:
return False
def push(data):
global stack, top, SIZE
if (isStackFull()):
print('스택 꽉참!')
return
top += 1
stack[top] = data
def pop():
global stack, top, SIZE
if (isStackEmpty()):
print('스택 비어있음!')
return
data = stack[top]
stack[top] = None
top -= 1
return data
## 전역 변수부
SIZE = 5
stack = [None for _ in range(SIZE)]
top = -1
## 메인 코드부
if __name__ == '__main__':
push('a')
push('b')
push('c')
push('d')
push('e')
push(1)
print(stack)
pop()
pop()
pop()
pop()
pop()
pop() |
1acb2b936ee727d7bfa1062d299f1404488cb08a | lingdingjun/learngit | /fxxcx.py | 140 | 3.9375 | 4 | def f(x):
if x==0:
return x
else:
return f(x-1)*2+x*x
x = int(raw_input ('请输入x:')) #需要用int,否则为str
print f(x)
|
437b356a1b598f6dcb02fbf532b256162bf76e0e | DragonfireX/python-_exercises_and-notes | /range_over_looping.py | 591 | 4.375 | 4 | for num in range(1, 10):
print(num)
for num in range(1, 10, 2):
print(num)
"""
looping through ranges
set number of times you want to loop through the data set but limit it
the code on top
range takes 2 -3 arguments add the colon at the end
it iterates over the range and prints 1 2 3 4 5 6 7 8 9
a range works like grabbing and slicing items in a list (doesn't go to ten stops up to 10)
########################################
the code on bottom
what if you wanna skip values
1, 10, 2 still goes over the range but
instead incrementing by 1 it goes and skips everyother one
""" |
a08da175eea635569bafac40cbf8976825bbe6ce | arita37/eai-spellchecker | /spellchecker/helpers.py | 5,662 | 3.75 | 4 | import csv
import re
from os import path
from typing import List
def null_distance_results(string1, string2, max_distance):
"""Determines the proper return value of an edit distance function when
one or both strings are null.
"""
if string1 is None:
if string2 is None:
return 0
else:
return len(string2) if len(string2) <= max_distance else -1
return len(string1) if len(string1) <= max_distance else -1
def prefix_suffix_prep(string1, string2):
"""Calculates starting position and lengths of two strings such that
common prefix and suffix substrings are excluded.
Expects len(string1) <= len(string2)
"""
# this is also the minimun length of the two strings
len1 = len(string1)
len2 = len(string2)
# suffix common to both strings can be ignored
while len1 != 0 and string1[len1 - 1] == string2[len2 - 1]:
len1 -= 1
len2 -= 1
# prefix common to both strings can be ignored
start = 0
while start != len1 and string1[start] == string2[start]:
start += 1
if start != 0:
len1 -= start
# length of the part excluding common prefix and suffix
len2 -= start
return len1, len2, start
def to_similarity(distance, length):
return -1 if distance < 0 else 1.0 - distance / length
def try_parse_int64(string):
try:
ret = int(string)
except ValueError:
return None
return None if ret < -2 ** 64 or ret >= 2 ** 64 else ret
def parse_words(phrase, preserve_case=False):
"""create a non-unique wordlist from sample text
language independent (e.g. works with Chinese characters)
"""
# \W non-words, use negated set to ignore non-words and "_" (underscore)
# Compatible with non-latin characters, does not split words at
# apostrophes
if preserve_case:
return re.findall(r"([^\W_]+['’]*[^\W_]*)", phrase)
else:
return re.findall(r"([^\W_]+['’]*[^\W_]*)", phrase.lower())
def is_acronym(word):
"""Checks is the word is all caps (acronym) and/or contain numbers
Return:
True if the word is all caps and/or contain numbers, e.g., ABCDE, AB12C
False if the word contains lower case letters, e.g., abcde, ABCde, abcDE,
abCDe, abc12, ab12c
"""
return re.match(r"\b[A-Z0-9]{2,}\b", word) is not None
class SpaceDelimitedFileIterator:
"""
Iterator on a space delimited file. This class is limited to single term entries.
If you want to support entries with multiple terms, use the CsvFileIterator.
The file format is similar to
the 23135851162
of 13151942776
and 12997637966
to 12136980858
a 9081174698
in 8469404971
travelling 6271787 traveling
where one column contains the term to lookup, the number of occurrences in the
source corpus and the 'canonical utterance' of the term (e.g traveling is preferred over
travelling). The canonical utterance is optional.
"""
def __init__(self, corpus: str, term_index: int=0, count_index: int=1, canonical_term_index: int=None):
if not path.exists(corpus):
raise FileNotFoundError(f'Could not open file {corpus}')
self.term_index = term_index
self.count_index = count_index
self.canonical_term_index = canonical_term_index
self.f = open(corpus, 'r')
def __iter__(self):
return self
def __next__(self):
line = self.f.readline()
if line:
line_parts = line.rstrip().split(" ")
if len(line_parts) >= 2:
term = line_parts[self.term_index]
count = try_parse_int64(line_parts[self.count_index])
if count is not None:
canonical_term = line_parts[self.canonical_term_index] if self.canonical_term_index else None
return term, count, canonical_term
raise StopIteration
class CsvFileIterator:
"""
Iterate over a CSV file.
The file format must be similar to
the, 23135851162,
of, 13151942776,
and, 12997637966,
to, 12136980858,
a, 9081174698,
in, 8469404971,
travelling, 6271787, traveling
where the first column contains the term to lookup, the second column contains the number of
occurrences in the source corpus and the last column is the 'canonical utterance' of the term
(e.g traveling is preferred over travelling). The canonical utterance is optional.
"""
def __init__(self, corpus: str, term_col: str='term', count_col: str='count',
canonical_term_col: str='canonical_term'):
if not path.exists(corpus):
raise FileNotFoundError(f'Could not open file {corpus}')
self.f = csv.DictReader(open(corpus, 'r'))
self.term_col = term_col
self.count_col = count_col
self.canonical_term_col = canonical_term_col
def __iter__(self):
return self
def __next__(self):
line = next(self.f)
count = try_parse_int64(line[self.count_col])
if count is not None:
return line[self.term_col], \
count, \
line[self.canonical_term_col] if self.canonical_term_col in line else None
class ListIterator:
"""
Iterate over a list for the SymSpell load_dictionary function.
Args:
corpus: A list of string to load in the SymSpell instance.
"""
def __init__(self, corpus: List[str]):
self.f = corpus
def __iter__(self):
for word in self.f:
yield word.strip().lower(), 1, word
|
6b465f1a90aafe2bf3eaa9ee7ca4ec66cba18c09 | BrainLiang703/Python- | /Dict | 1,143 | 3.5625 | 4 | #!/usr/bin/env python
#coding:utf-8
a = {'name':'Brain','age':'4'}
print(len(a)) #len显示字典里元素的数量
b = a
print(b)
c = a.copy() # 效果和b = a 一样
print(c)
c.clear() # clear 把整个字典删除
print(c)
del c #删除整个字典,内存也释放。再调用这个元组就会报错
print(a.get("name")) # get通过键获取值,取不到值则返回空值,但是如果用a["name"],假如找不到值,会出现异常。
a.setdefault("Addr","HUIZHOU") #setdefault给字典添加值
print(a)
print(a.keys())
print(a.values())
a.pop("age") #POP删除字典中键对应的值。
print(a)
a.popitem() # 随机删除字典中的值
print(a)
a.update([("age","24"),("Addr","HUIZHOU")]) #update给字典加值,另外一种用法 a.update(字典b)
print(a)
for d in a.keys():
print(d)
测试结果:
2
{'name': 'Brain', 'age': '4'}
{'name': 'Brain', 'age': '4'}
{}
Brain
{'name': 'Brain', 'age': '4', 'Addr': 'HUIZHOU'}
dict_keys(['name', 'age', 'Addr'])
dict_values(['Brain', '4', 'HUIZHOU'])
{'name': 'Brain', 'Addr': 'HUIZHOU'}
{'name': 'Brain'}
{'name': 'Brain', 'age': '24', 'Addr': 'HUIZHOU'}
name
age
Addr
|
c3a5b3dc982e02d760d3eb979a23ee9f7f86fec7 | pb1729/differential-equations | /stringtofunc.py | 1,646 | 3.65625 | 4 | import math
'''
#testing code:
class dummy:
val = 0.0
def __init__(self, v):
self.val = v
print tofunction("( + ( sin a ) pi )")({"a":dummy(1)})
'''
def tofunction(s):
tokens = s.split()
return listtofunc(tokens, [])
def isnumber(s):
try:
a = float(s)
return True
except ValueError:
return False
def isvar(s):
c = ord(s[0])
return (c >= 65 and c < 91) or (c >= 97 and c < 123)
def listtofunc(tokens, stack):
if len(tokens) == 0:
return stack[0]
token = tokens.pop()
if token == ")":
stack.append(listtofunc(tokens, []))
elif token == "(":
return stack[0]
elif isnumber(token):
n = float(token)
stack.append((lambda vrs : n))
elif token == "sin":
f = stack.pop()
stack.append((lambda vrs : math.sin(f(vrs))))
elif token == "cos":
f = stack.pop()
stack.append((lambda vrs : math.sin(f(vrs))))
elif token == "pi":
stack.append((lambda vrs : 3.14159265358979))
elif token == "+":
f = stack.pop()
g = stack.pop()
stack.append((lambda vrs : f(vrs) + g(vrs)))
elif token == "*":
f = stack.pop()
g = stack.pop()
stack.append((lambda vrs : f(vrs) * g(vrs)))
elif token == "/":
f = stack.pop()
g = stack.pop()
stack.append((lambda vrs : f(vrs) / g(vrs)))
elif token == "-":
f = stack.pop()
g = stack.pop()
stack.append((lambda vrs : f(vrs) - g(vrs)))
elif isvar(token):
stack.append((lambda vrs : vrs[token].val))
return listtofunc(tokens, stack)
|
741cfac01914981433e664a2c58e4faf9970cfe3 | hyeinkim1305/Algorithm | /SWEA/D2/SWEA_5178_노드의합.py | 1,079 | 3.640625 | 4 | '''
10 5 2
8 42
9 468
10 335
6 501
7 170
'''
def nodesum(idx): # 후위방식
global tree
if idx <= N:
nodesum(idx * 2)
nodesum(idx * 2 + 1)
if idx * 2 + 1 <= N: # 자식 노드가 N안에 있으면
tree[idx] = tree[idx * 2] + tree[idx * 2 + 1]
if idx * 2 == N: # 자식 노드가 1개이면 (마지막 노드가 자식노드)
tree[idx] = tree[idx*2]
T = int(input())
for tc in range(1, T+1):
N, M, L = map(int, input().split())
tree = [0] * (N+1)
for i in range(M):
a, b = map(int, input().split())
tree[a] = b # 넣기
nodesum(1)
print('#{} {}'.format(tc, tree[L]))
'''
# sol2
def calc(l):
if l <= N:
if l in nodes:
return nodes[l]
return calc(2*l) + calc(2*l + 1)
return 0
for tc in range(1, int(input())+1):
N, M, L = map(int, input().split())
nodes = {}
for i in range(M):
node, value = map(int, input().split())
nodes[node] = value
print(f'#{tc} {calc(L)}')
''' |
90cf38209c965dba5aaf7c226f0ede2292af77b1 | Alf0nso/NN-Games | /NN/nn_sum_demo.py | 1,036 | 4.34375 | 4 | # Neural Network Demo
#
# @Author: Afonso Rafael & Renata
#
# Demo demonstrating neural network implementation
# learning how to sum two numbers, (exciting I know).
# Can be used to understand how can be used and
# altered to be able to map other functions.
import neural_net as nn
import numpy as np
from random import random
# Libraries necessary to perform the task.
##################################################
mlp = nn.MLP(2, [5], 1)
# [weights, activations, derivatives]
inputs = np.array([[random() /
2 for _ in range(2)]
for _ in range(3000)])
target = np.array([[i[0] + i[1]] for i in inputs])
##################################################
print(50*"-")
print("Training The Neural Network!")
print()
nn.train(mlp, inputs, target, 50, 1)
print()
print(50*"-")
print("Testing The Neural Network!")
print()
input = np.array([0.3, 0.2])
output = nn.forward_propagate(input, mlp[0], mlp[1])
print()
print("Prediction of {} + {} is {}".format(
input[0], input[1], output[0]))
|
c8875efdcd1664a5258c47d99d2c846fada728f7 | abrahamsk/ml_naive-bayes-classification | /src/naive_bayes.py | 6,001 | 3.90625 | 4 | #!/usr/bin/env python
# coding=utf-8
# Machine Learning 445
# HW 4: Naive Bayes Classification
# Katie Abrahams, abrahake@pdx.edu
# 2/25/16
from __future__ import division
from probabilistic_model import *
import math
import timing # time program run
"""
3.
Run Naïve Bayes on the test data.
- Use the Naïve Bayes algorithm to classify the instances in your test set,
using P(xi | cj)=N(xi;μi,cj,σi,cj )
where N(x;μ,σ)= [1/(sqrt(2π)σ)]*e^[−((x−μ)^2)/(2σ^2)]
Because a product of 58 probabilities will be very small, we will instead use the log of the product.
Recall that the classification method is:
classNB(x)=argmax[P(class)∏P(xi | class)]
Since
argmax f(z) = argmax log f(z)
we have:
classNB(x) = argmax[(class)∏P(xi | class)]
= argmax[log P(class)+log P(xi | class)+...+log P(xn | class)]
"""
###########
# functions
###########
def gaussian_probability(x, mean, std_dev):
"""
Use NB to classify instances in test set
using Gaussian normal distribution function N
N(x;μ,σ)= [1/(sqrt(2π)σ)]*e^[−((x−μ)^2)/(2σ^2)]
:param x:
:param mean:
:param std_dev:
:return:
"""
# catch div by zero errors
if std_dev == 0.0:
std_dev = .01
# avoid math domain errors by using log rule:
# log(a/b) == log(b)-log(a)
# math.exp(x) returns e**x.
exp = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(std_dev, 2))))
denominator = (math.sqrt(2 * math.pi) * std_dev)
# catch math domain errors
if exp == 0.0:
return exp - math.log(denominator)
else:
return math.log(exp) - math.log(denominator) * exp
def predict_all():
"""
Predict classes for test data
Use X_test_features, prior_prob_spam, prior_prob_not_spam
From input and probabilistic_model files
Calculate argmax for spam and not spam classes
:return list of class predictions:
"""
# use math.log (base e)
# use logs and sums rather than products when computing prediction:
# classNB(x) = argmax[(class)∏P(xi | class)]
# = argmax[log P(class)+log P(xi | class)+...+log P(xn | class)]
predictions = []
# predict class for each row in test features matrix
for row in range(len(X_test_features)):
probabilities_pos = []
probabilities_neg = []
# for each item in the instance row (for each feature), calculate gaussian probability using N function
for i in range(len(X_test_features[row])):
# log computations moved to inside gaussian_probability function
probability_log_pos = gaussian_probability(X_test_features[row,i], pos_means_training[i], pos_std_devs_training[i])
probabilities_pos.append(probability_log_pos)
probability_log_neg = gaussian_probability(X_test_features[row,i], neg_means_training[i], neg_std_devs_training[i])
probabilities_neg.append(probability_log_neg)
# get prediction for positive and negative classes
# by summing log of prior probability and sum of gaussian prob for each feature (computed above)
predict_spam = math.log(prior_prob_spam) + sum(probabilities_pos)
predict_not_spam = math.log(prior_prob_not_spam) + sum(probabilities_neg)
# assign class prediction based on argmax of positive (spam) and negative (not spam)
# the odds that the two probabilities will be equal is so small we'll disregard that case
if predict_spam > predict_not_spam:
# classify as spam if predict spam prob is larger
predictions.append(1.0)
else:
# else classify as not spam
predictions.append(0.0)
# return list of predictions for spam/not spam for all instances in test set
return predictions
def get_stats():
"""
Get stats for test data classifications
:return:
"""
# predict classes for spam test data
predictions = predict_all()
# collect and print stats for test data classification
true_pos = 0
true_neg = 0
false_pos = 0
false_neg = 0
correct_predictions = 0
# print [(i,j) for i,j in zip(X_test_classifier, predictions) if i != j]
# zip list of correct classifications and NB predictions
for i,j in zip(X_test_classifier, predictions):
# accuracy
if i==j:
correct_predictions += 1
# true positives
if i == 1.0 and j == 1.0:
true_pos += 1
# true negatives
if i == 0.0 and j == 0.0:
true_neg += 1
# false positives (classified pos, really negative)
if i == 0.0 and j == 1.0: # i = true value, j = prediction
false_pos += 1
# false negatives (classified neg, really pos)
if i == 1.0 and j == 0.0: # i = true value, j = prediction
false_neg += 1
# Accuracy = fraction of correct classifications on unseen data (test set)
accuracy = correct_predictions / len(X_test_features)
print "----- Accuracy across the test set -----\n", accuracy, "\nCorrect predictions / 2300 =", \
correct_predictions, "\n----------------------------------------"
# confusion matrix
print "\n----- Confusion matrix -----"
print " Predicted"
print "A Spam Not spam "
print "c _______________"
print "t Spam | ", true_pos," | ", false_neg, " | "
print "u |_______|_______|"
print "a Not | ", false_pos," | ", true_neg, " | "
print "l spam |_______|_______|"
print "----------------------------"
# Precision = TP/(TP+FP)
precision = true_pos / (true_pos+false_pos)
print "\n----- Precision -----\n", precision, "\n---------------------"
# Recall = TP / (TP+FN)
recall = true_pos / (true_pos+false_neg)
print "\n----- Recall -----\n", recall, "\n------------------"
#######################################################################
def main():
# get stats for test data
get_stats()
if __name__ == "__main__":
main()
|
3f8ae31e6c67fd1eb75d0023bbe97e6918649602 | rgeos/rss | /classRSS.py | 3,310 | 3.640625 | 4 | #!/usr/bin/env python
# _*_coding: utf-8 _*_
import feedparser as rss
import classRegex as reg
class classRSS(object):
"""
Retrieving some of the elements of an RSS feed
"""
def __init__(self):
self.urls = "" # the URLs will be in a string
self.feed = {} # a dictionary of feeds
self.remove = reg.classRegex() # regex to remove from string
def setURLs(self, newURLs):
"""
This function will set the RSS URLs in the
form of a string delimited by space
:param newURLs: String
:return: String
"""
self.urls = newURLs
def getURLs(self):
"""
A list of URLs formed by splitting a string on spaces
:return: List
"""
return [x.strip() for x in self.urls.split(" ")]
def getFeeds(self):
"""
This function will return a dictionary of RSS feeds
:return: Dictionary
"""
for i in range(len(self.getURLs())):
self.feed[i] = rss.parse(self.getURLs()[i])
return self.feed
def getFeedsLen(self):
"""
The length of the dictionary
:return: Integer
"""
return len(self.getFeeds())
def getFeed(self, feedId):
"""
Providing an ID, retrieve a feed with that ID
:param feedId: Integer
:return: String
"""
try:
return self.getFeeds()[feedId]
except Exception:
print "The ID %r doesn't exist." % feedId
def getFeedTitle(self, feedId):
"""
Providing an ID, retrieve the title of a feed with that ID
:param feedId: Integer
:return: String
"""
try:
return self.remove.getRegex(self.getFeed(feedId=feedId).feed.title)
except Exception:
print "The ID %r doesn't exist." % feedId
def getFeedLink(self, feedId):
"""
Providing an ID, retrieve the link of a feed with that ID
:param feedId: Integer
:return: String
"""
try:
return self.getFeed(feedId=feedId).feed.link
except Exception:
print "The ID %r doesn't exist." % feedId
def getFeedSubtitle(self, feedId):
"""
Providing an ID, retrieve the subtitle of a feed with that ID
:param feedId: Integer
:return: String
"""
try:
return self.remove.getRegex(self.getFeed(feedId=feedId).feed.subtitle)
except Exception:
print "The ID %r doesn't exist." % feedId
def getFeedLen(self, feedId):
"""
Providing an ID, retireve the length of a feed with that ID
:param feedId: Integer
:return: String
"""
try:
return len(self.getFeed(feedId=feedId).entries)
except Exception:
print "The ID %r doesn't exist." % feedId
def getFeedDatas(self, feedId):
"""
Retrieve all entries in a feed
:param feedId: Integer
:return: String
"""
try:
return self.getFeed(feedId=feedId).entries
except Exception:
print "The ID %r doesn't exist." % feedId
def getFeedData(self, feedId, entryId):
"""
This will return the summary and the title of a feed
At the same time it will remove the regex from the contets
:param feedId: Integer
:param entryId: Integer
:return: List
"""
try:
title = self.remove.getRegex(self.getFeedDatas(feedId=feedId)[entryId].title)
summary = self.remove.getRegex(self.getFeedDatas(feedId=feedId)[entryId].summary)
return [title.encode('utf-8'), summary.encode('utf-8')]
except Exception:
print "The ID %r, %r doesn't exist." % (feedId, entryId)
|
da1b95842fc8d3f7ddc782f47cfd01a0fb0097d6 | KJanmohamed/Year9DesignCS4-PythonKJ | /GUIRadioButtons.py | 767 | 3.59375 | 4 | import tkinter as tk
root = tk.Tk()
v = tk.IntVar()
tk.Label(root,
text="""Choose a
player:""",
justify = tk.LEFT,
padx = 20).pack()
tk.Radiobutton(root,
text="Player 1",
padx = 20,
variable=v,
value=1).pack(anchor=tk.W)
tk.Radiobutton(root,
text="Player 2",
padx = 20,
variable=v,
value=2).pack(anchor=tk.W)
tk.Radiobutton(root,
text="Player 3",
padx = 20,
variable=v,
value=3).pack(anchor=tk.W)
tk.Radiobutton(root,
text="Player 4",
padx = 20,
variable=v,
value=4).pack(anchor=tk.W)
root.mainloop() |
c5ea69cd9429b22a09ddc2f03d278659bb73ff3b | staryjie/Full-Stack | /test/score_demo.py | 361 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
score = int(input("Pls enter yur score: "))
if score > 100:
print("分数不能超过100!")
elif score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 60:
print("C")
elif score >= 40:
print("D")
elif score >=0:
print("E")
elif score < 0:
print("分数不能为负数!") |
fa4180706cff4f283bbfe228a12702eccc23c1ce | lsn199603/leetcode | /27-最小路径和.py | 946 | 3.640625 | 4 | """
给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
输入:grid = [[1,3,1],[1,5,1],[4,2,1]]
输出:7
解释:因为路径 1→3→1→1→1 的总和最小
四种情况:
1. i=0, j=0 dp[i][j] = grid[i][j]
2. i=0, j!=0 dp[i][j] = grid[i][j] + dp[i][j-1]
3. i!=0, j=0 dp[i][j] = grid[i][j] + dp[i-1][j]
3. i!=0, j!=0 dp[i][j] = min(grid[i][j-1], dp[i-1][j]) + grid[i][j]
"""
grid = [[1,3,1],[1,5,1],[4,2,1]]
for i in range(len(grid)):
for j in range(len(grid[0])):
if i==0 and j ==0 :
continue
elif i==0 and j !=0:
grid[i][j] = grid[i][j - 1] + grid[i][j]
elif i!=0 and j ==0:
grid[i][j] = grid[i-1][j] + grid[i][j]
else:
grid[i][j] = min(grid[i][j - 1], grid[i-1][j]) + grid[i][j]
print(grid[-1][-1]) |
905ff0c1ca0d7a4a47e94d6913486279ce35c2c4 | Benzsoft/Python-Stuff | /Apps/Mario_kart.py | 2,092 | 3.609375 | 4 | racers_list = [{'name': 'Peach', 'items': ['green shell', 'banana', 'green shell', ], 'finish': 3},
{'name': 'Bowser', 'items': ['green shell', ], 'finish': 1},
{'name': None, 'items': ['mushroom', ], 'finish': 2},
{'name': 'Toad', 'items': ['green shell', 'mushroom'], 'finish': 1}]
print(racers_list)
big_list = [{'name': 'Peach', 'items': ['green shell', 'banana', 'green shell'], 'finish': 3},
{'name': 'Peach', 'items': ['green shell', 'banana', 'green shell'], 'finish': 1},
{'name': 'Bowser', 'items': ['green shell'], 'finish': 1},
{'name': None, 'items': ['green shell'], 'finish': 2},
{'name': 'Bowser', 'items': ['green shell'], 'finish': 1},
{'name': None, 'items': ['red shell'], 'finish': 1},
{'name': 'Yoshi', 'items': ['banana', 'blue shell', 'banana'], 'finish': 7},
{'name': 'DK', 'items': ['blue shell', 'star'], 'finish': 1}]
def best_items(racers):
"""Given a list of racer dictionaries, return a dictionary mapping items to the number
of times those items were picked up by racers who finished in first place.
"""
winner_item_counts = {}
for i in range(len(racers)):
# The i'th racer dictionary
racer = racers[i]
# We're only interested in racers who finished in first
if racer['finish'] == 1:
for item in racer['items']:
# Add one to the count for this item (adding it to the dict if necessary)
if item not in winner_item_counts:
winner_item_counts[i] = 0
winner_item_counts[i] += 1
# Data quality issues :/ Print a warning about racers with no name set. We'll take care of it later.
if racer['name'] is None:
print("WARNING: Encountered racer with unknown name on iteration {}/{} (racer = {})".format(
i+1, len(racers), racer['name'])
)
return winner_item_counts
print(best_items(racers=racers_list))
print(best_items(racers=big_list))
|
c7c0d89415503cfed42baf4b8280e052a918f062 | MEng-Alejandro-Nieto/Python-for-Data-Science-and-machine-Learning-Udemy-Course | /15. E-commerce purchases Exercises with pandas.py | 2,240 | 4.28125 | 4 | import pandas as pd
table=pd.read_csv('/home/alejandrolive932/Desktop/Udemy_Data_Science_and_Machine_Learning/Refactored_Py_DS_ML_Bootcamp-master/04_Pandas_Exercises/Ecommerce Purchases')
print(table.info())
# 1. Check the head of the DataFrame
print(table.head())
# 2. How many columns and rows there are
print(f"the number of rows are : {table.index.nunique()}")
print(f"the number of columns are : {table.columns.nunique()}")
# 3. What is the average Purchase Price?
print(f"the average purchase price is : {table['Purchase Price'].mean()}")
# 4. What is the highest and lowest prices?
print(f"the highest price is: {table['Purchase Price'].max()}")
print(f"the lowest price is: {table['Purchase Price'].min()}")
# 5. How many people have English 'en' as their language of choice on the website
print(f"the number of people that have english as their language are: {sum(table['Language'].apply(lambda x:'en' in x.lower().split()))}")
# 6. How many people have the job title of 'Lawyer'
print(f"the number of people with 'Lawyer' as a title are: {sum(table['Job'].apply(lambda x:x=='Lawyer'))}")
print(f"{sum(table['Job']=='Lawyer')}")
# 7. How many people made the purchase during AM and PM
print(f"{table['AM or PM'].value_counts()}")
# 8. What are the five most common jobs Titles?
print(f"the five most common jobs are:\n{table['Job'].value_counts().head(5)}")
# 9. Someone made a purchase that came from Lot:'90 WT', what
# was the purchase Price for this transaction
print(f"the price for this transaction was: {table[table['Lot']=='90 WT']['Purchase Price']}\n")
# 10.What is the email of the person with the following Credit Card Number
print(table[(table['Credit Card']==4926535242672853)]['Email'])
# 11. How many people have american express as their credit
# card provider and a purchase above 95 dollars
print(len(table[(table['CC Provider']=='American Express') & (table['Purchase Price']>95)]))
# 12 How may people have credit card that expires in 2025
print(f"{sum(table['CC Exp Date'].apply(lambda x:'/25' in x))}\n")
# 13 What are the top 5 most popular email providers/host (e.g. gmail.com. yahoo.com etc)
print(table['Email'].apply(lambda x:x.split('@')[1]).value_counts().head(5)) |
95da4189cd1ddd2aaeee6737b2b3d93461d3dd92 | 01-Jacky/ConnectedEmployers | /connected_employer/sandbox.py | 657 | 4.03125 | 4 | class Data(object):
""" Data Store Class """
products = {
'milk': {'price': 1.50, 'quantity': 10},
'eggs': {'price': 0.20, 'quantity': 100},
'cheese': {'price': 2.00, 'quantity': 10}
}
def __get__(self, obj, klas):
print("(Fetching from Data Store)")
return {'products': self.products}
class TestObj:
a = 1
b = 2
def __init__(self, arg1, arg2):
self.a = arg1;
self.b = arg2;
class TestObj2:
def __init__(self, arg1=0, arg2=0):
self.a = arg1;
self.b = arg2;
if __name__ == '__main__':
myObj = TestObj()
print(myObj.a)
print(myObj.b)
|
71d6e4ceed4e2d2d56f3e758f3f1ff3adf22c002 | wallacewd/Brick-s-Instant-Messenger-v0.1 | /client.py | 1,479 | 3.546875 | 4 | """
Basic Instant Messaging Application Version 0.1
Author: Dan Wallace (danwallaceasu@gmail.com).
Creates a peer to peer connection on a local network allowing real-time chat.
Server.py must be running in order for both files to run.
Server.py creates a server that is only active when the code is running.
08/23/2020
"""
# Import socket is needed to interface with ports
import socket
import sys
import time
# Attaches socket (must have socket imported to do this) to variable so we can use rapidly
x = socket.socket()
# Find the local host name attached to the computer running server.py - you will use this to connect on server.py
host_name = input(str(" Enter the hostname of the server"))
# Establish port connection
# 8080 is standard
# If code fails to run, open firewall settings and allow port 8080
# Allow both incoming and outgoing connections to port 8080
# X.connect is searching for a host name matching the input set on "host_name"
# If host name matches active host and port, connection will establish
port = 8080
x.connect((host_name, port))
print("Connected to chat server")
# Similar to server 'while' statement
# Allows incoming messages, decodes and displays them
# Allows response message, encodes and sends it
while 1:
incoming_message = x.recv(1024)
incoming_message = incoming_message.decode()
print(" Server :", incoming_message)
message = input(str(">>"))
message = message.encode()
x.send(message)
print(" message has been sent...")
|
02f578deff28fa7b32125e550584a0a7d9f2a20b | suhas-nithyanand/Text-Summarization-MMR | /sentence.py | 842 | 3.75 | 4 | class sentence(object):
'''This module is a sentence data structure'''
def __init__(self, docName, stemmedWords, OGwords):
self.stemmedWords = stemmedWords
self.docName = docName
self.OGwords = OGwords
self.wordFrequencies = self.sentenceWordFreqs()
def getStemmedWords(self):
return self.stemmedWords
def getDocName(self):
return self.docName
def getOGwords(self):
return self.OGwords
def getWordFreqs(self):
return self.wordFrequencies
def sentenceWordFreqs(self):
wordFreqs = {}
for word in self.stemmedWords:
if word not in wordFreqs.keys():
wordFreqs[word] = 1
else:
wordFreqs[word] = wordFreqs[word] + 1
return wordFreqs
|
2e457180eb42bc06f9c4319b460fc36654cc0448 | Hunter-Dinan/cp1404practicals | /prac_09/sort_files_1.py | 1,416 | 4.15625 | 4 | """Program that sorts files into directories based on their file type."""
import os
import os.path
import shutil
FILE_TYPE_INDEX = 1
def main():
"""Program that creates directories for each file type and stores the corresponding files within it."""
os.chdir('FilesToSort')
file_names = os.listdir('.')
file_types = get_file_types(file_names)
create_directory_per_file_type(file_types)
move_files_to_dir_by_type(file_names)
def get_file_types(file_names: list):
"""Return a list of file_types."""
file_types = []
for file_name in file_names:
if not os.path.isdir(file_name):
file_name_parts = file_name.split('.')
file_type = file_name_parts[FILE_TYPE_INDEX]
if file_type not in file_types:
file_types.append(file_type)
return file_types
def create_directory_per_file_type(file_types: list):
"""Create directories for each file type in the list."""
for file_type in file_types:
try:
os.mkdir(file_type)
except FileExistsError:
pass
def move_files_to_dir_by_type(file_names: list):
"""Move files to directories based on their type."""
for file_name in file_names:
if not os.path.isdir(file_name):
file_name_parts = file_name.split('.')
shutil.move(file_name, file_name_parts[FILE_TYPE_INDEX] + '/' + file_name)
main()
|
dc42e33e5a831ab6b6fce6d6ad2e2199682d280d | ArnoutSchepens/Python_3 | /Oefeningen/OOP python/OOP 2/OnlyIntegers.py | 340 | 3.640625 | 4 |
from functools import wraps
def only_ints(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not all([isinstance(x, int) for x in args]):
return "Please only invoke with integers"
return fn(*args)
return wrapper
@only_ints
def add(x, y):
return x + y
print(add(1, 2))
print(add("1", "2")) |
5d9a500f7a7b95cf932827d5a9e271839cc26832 | nicoleorfali/Primeiros-Passos-com-Python | /p37.py | 619 | 3.890625 | 4 | # Cálculo de IMC
peso = float(input('Digite o seu peso (kg): '))
altura = float(input('Digite a sua altura (m): '))
imc = peso / (altura ** 2)
if imc <= 18.5:
print(f'O IMC é de {imc:.2f}\nVocê está Abaixo do Peso')
elif imc <= 25:
print(f'O IMC é de {imc:.2f} \nVocê está no Peso Ideal') # também dá para fazer: elif 18.5 <= imc < 25
elif imc <= 30:
print(f'O IMC é de {imc:.2f} \nVocê está com Sobrepeso')
elif imc <= 40:
print(f'O IMC é de {imc:.2f} \nVocê está com Obesidade')
else:
print(f'O IMC é de {imc:.2f} \nVocê está com Obesidade Mórbida. CUIDADO!!!')
|
e9ea3fdaa9b2b02622fd7a22f5b6e6afdaaef566 | Sergei-Morozov/Stanford-Algorithms | /NP-Complete/week12/tsp.py | 3,023 | 3.625 | 4 | """
Travelling salesman
input: complete undirected graph with nonnegative edge costs
output: a minimum cost tour that visit every vertex exactly once
"""
""" Build the graph
_____0____
/ | \
10C / |20C \ 15C
/ _____ 3____ \
/ /25C 30C\ \
1__/_____________\__2
35C
The minimum cost path is 0-1-3-2-0 = 10 + 25 + 30 + 15 = 80
"""
# a matrix representation of the graph
graph = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
from itertools import permutations
def tsp_brute(graph):
"""
- make all permutation of vertices O(N!)
- for each permutation calculate path O(N)
- return minimal O(1)
Total is O(N*N!)
"""
N = len(graph)
paths = list(permutations(list(range(0,N)), N))
minimum = float('inf')
for path in paths:
current = 0
# sum for each vertex in path
for i in range(len(path)-1):
current += graph[path[i]][path[i+1]]
# add final edge tail -> start
current += graph[path[-1]][path[0]]
if minimum > current:
minimum = current
print(minimum)
return minimum
# tsp_brute(graph)
N = len(graph)
memo = [ [-1 for _ in range(N)] for _ in range(1<<N)] # size [1 << N][N]
def tsp(bitmask, pos):
"""
Let dp[bitmask][vertex] represent the minimum cost
- bitmask 1 1 0 0 - represent visited vertex 3, 2 is equal 12
- dp[12][2] - min cost for visited edges 3,2 and path ended in 2
- number of possible sets = 2^(N-1) = 16777216
- number of possible j = N-1 = 24
- size of each element of A = 4 bytes = 32 bits (assuming float)
"""
min_cost = float('inf')
# All vertices have been explored 11111111
if bitmask == ((1<<N) - 1):
# cost to go back to 0 node
return graph[pos][0]
# if already computed
if memo[bitmask][pos] != -1:
return memo[bitmask][pos]
# For every vertex
for i in range(N):
# If the vertex has not been visited
if (bitmask & (1<<i)) == 0:
min_cost = min(min_cost, tsp(bitmask | (1 << i) , i) + graph[pos][i]) # Visit the vertex
memo[bitmask][pos] = min_cost
return min_cost
print(tsp(1, 0))
from collections import defaultdict
from math import sqrt
def get_distance(d1, d2):
return sqrt( (d1[0] - d2[0])**2 + (d1[1] - d2[1])**2)
def test_quiz3(input):
distances = defaultdict(dict)
with open(input) as file:
number = file.readline()
for idx, line in enumerate(file):
x, y = map(float, line.split())
distances[idx] = (x,y)
graph = [[get_distance(distances[i],distances[j]) for j in range(25)] for i in range(25)]
return graph
graph = test_quiz3('quiz1')
print('graph')
N = len(graph)
print('memo', 1<<N)
memo = [ [-1 for _ in range(N)] for _ in range(1<<N)] # size [1 << N][N]
print('tsp')
print(tsp(1, 0))
|
0fd7797f30a0630d047ba16c605bb8e6399d2246 | messerzen/Pythont_CEV | /aula06a.py | 179 | 3.828125 | 4 | n1=int(input('Digite um valor: '))
n2=int(input('Digite outro:'))
s=n1+n2
# print('A soma entre', n1, '+', n2, 'vale', s)
print('A soma entre {0} e {1} vale {2}'.format(n1,n2, s)) |
34cb9db96c2218f59f663f30a2f2e60936a6f047 | benoitmaillard/scallion-python-parser | /src/test/resources/input/pprint.py | 842 | 3.625 | 4 | async def f():
return 0
def f():
return 0
async for x in test:
print(x)
for x in test:
print(x)
for (x, y, z) in test:
print(x)
with test as f:
print(x)
async with test as f:
print(x)
if (x):
print(x)
x = [1, 2, 3]
try:
raise x
except D:
print(x)
except C:
print(x)
except B:
print(x)
x = [x, y, z]
(x, y, z)
x
x,
(1)
(1,)
[x for (x, y, z) in test if x > 0 for (a, b, c) in test2]
def main():
if (x > 1):
print(x)
else:
print(y)
[(x, y, z) for (x, y, z) in test]
x = {"test" : 1}
x = {1, 2, 3}
x = {x for x in test}
x = {**x, **y}
x = {1}
x ={1, 2}
call(x, y, *varargs, x=3, y=3, **kwargs)
class Test:
def __init__(self):
pass
def fun(x, y, *varargs, a, b, c, **kwargs):
return 0
(yield x)
x = lambda a: a + 1
b"test" b"test"
"test" |
5e4b4e3a5f4eed41df98ab83585e31a6bb505086 | johnfelipe/progress | /courses/cs101/lesson02/problem-set/median.py | 602 | 4.15625 | 4 | # Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.
# Make sure your procedure has a return statement.
def bigger(x, y):
if x > y:
return x
else:
return y
def biggest(x, y, z):
return bigger(x, bigger(y, z))
def median(x, y, z):
big = biggest(x, y, z)
if big == x:
return bigger(y, z)
if big == y:
return bigger(x, z)
else:
return bigger(x, y)
print(median(1, 2, 3))
#>>> 2
print(median(9, 3, 6))
#>>> 6
print(median(7, 8, 7))
#>>> 7 |
16818e23cb3a7eb9b8de66b5da352d78d96ea793 | goodday451999/Machine-Learning | /Linear Regression/ML_Linear_Regression.py | 495 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# read csv file
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2]
y = dataset.iloc[:, 2]
# linear regression classifier
from sklearn.linear_model import LinearRegression
linear_reg = LinearRegression()
linear_reg.fit(X, y)
# plot
plt.scatter(X, y, color='r')
plt.plot(X, linear_reg.predict(X), color='g')
plt.title('Linear Regression')
plt.xlabel('Position level')
plt.ylabel('Slary')
plt.show()
|
60691c9f1d8b93b3fdf063ec1be632a042a37ffa | dengyungao/python | /老男孩python全栈开发第14期/python基础知识(day1-day40)/python协程+多路复用机制/yield实现并发的假象.py | 1,171 | 4.0625 | 4 | import time
# 在单线程中,如果存在多个函数,如果有某个函数发生IO操作,我想让程序马上切换到另一个函数去执行
# 以此来实现一个假的并发现象。
# 总结:
# yield 只能实现单纯的切换函数和保存函数状态的功能
# 不能实现:当某一个函数遇到io阻塞时,自动的切换到另一个函数去执行
# 目标是:当某一个函数中遇到IO阻塞时,程序能自动的切换到另一个函数去执行
# 如果能实现这个功能,那么每个函数都是一个协程
#
# 但是 协程的本质还是主要依靠于yield去实现的。
# 如果只是拿yield去单纯的实现一个切换的现象,你会发现,根本没有程序串行执行效率高
def consumer():
while 1:
x = yield
print('第{0}次收到producer的值:{1}'.format(x+1,x))
def producer():
g = consumer()
next(g)
for i in range(100):
print('第{0}次传值给consumer'.format(i + 1))
g.send(i)#该行会将i送到consumer函数的这行:“x = yield”
if __name__ == '__main__':
start = time.time()
producer()
print('yield耗费时间', time.time() - start) |
8b12273e6c9944d2f390fc720ffd16d54f699a83 | mahmud-sajib/30-Days-of-Python | /L #24 - Inheritance & Super.py | 1,281 | 4.34375 | 4 | ## Day 24: Inheritance and Super
## Concept: Inheritance and Super
# Creating a Parent Class
class Music:
def __init__(self,band,genre):
self.band = band
self.genre = genre
def info(self):
print(f"{self.band} is my favorite band & they play {self.genre} music")
# Creating a Child Class
class Band(Music):
def __init__(self,band,genre,origin):
super().__init__(band,genre)
self.origin = origin
def bandInfo(self):
print(f"{self.band} is a {self.origin} band which play {self.genre} music")
"""
super() simply refers to the parent class.
super().__init__(band,genre)
This is simply calling the constructor of the parent class, in our case Music.
This is how we inherit all of the properties and methods in our Band child class.
"""
# Creating Objects
# instantiating parent class object
band1 = Music("The Beatles","rock")
band1.info()
# output: The Beatles is my favorite band & they play rock music
# instantiating child class object
band2 = Band("Lalon","folk","Bangladeshi")
# accessing parent class method
band2.info()
# output: Lalon is my favorite band & they play folk music
# accessing child class method
band2.bandInfo()
# output: Lalon is a Bangladeshi band which play folk music
|
762e58978d378b15d23d7425b461dbbfed10bd7f | danielsamfdo/twitter_topic_summarization | /misc/Programs/LR/parse json/subtopic detection.py | 1,134 | 3.5625 | 4 | import nltk
#-----------------------------------------
#global variables
stop=[]
#-----------------------------------------
def getstopwords():
file1=file("stop.txt","r");
lines=file1.readlines();
for line in lines:
print line
stop.append(line[:len(line)-1]);
print stop
print "import completed"
def removestopwords(words):
for x in words:
if(x in stop):
print '';
else:
print x;
print "##############"
#-----------------------------------------
getstopwords()
#-----------------------------------------
f = file("xxx.txt", "r")
lines = f.readlines()
for line in lines:
X=line.split(" ");
Set=set(X);
words=[];
for word in Set:
v='';
for charac in word:
if(charac.isalpha()):
v=v+charac;
else:
if(len(v)!=0):
words.append(v);
v='';
if(len(v)!=0):
words.append(v);
print words
removestopwords(words);
f.close();
|
315c96d894155072ce50dc7e0b6d0bc7d2700c77 | KaranMuggan/myGitRepo | /poly.py | 2,685 | 3.796875 | 4 | '''The following code displays a polynomial regression model which takes into
account employees salaries along with the number of years of experience they
have and shows us the relationship
'''
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
#Training set
x_train = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] #Number Of years
y_train = [[80000], [100000], [125000], [135000], [150000], [175000], [210000], [280000], [350000], [500000]] #Salary
#Testing set
x_test = [[2], [4], [6], [8] ,[10], [12]] #Number Of Years
y_test = [[110000], [130000], [160000], [280000], [3750000], [660000]] #Salary
# Train the Linear Regression model and plot a prediction
regressor = LinearRegression()
regressor.fit(x_train, y_train)
xx = np.linspace(0, 50, 100)
yy = regressor.predict(xx.reshape(xx.shape[0], 1))
plt.plot(xx, yy)
# Set the degree of the Polynomial Regression model
quadratic_featurizer = PolynomialFeatures(degree=2)
# This preprocessor transforms an input data matrix into a new data matrix of a given degree
x_train_quadratic = quadratic_featurizer.fit_transform(x_train)
x_test_quadratic = quadratic_featurizer.transform(x_test)
# Train and test the regressor_quadratic model
regressor_quadratic = LinearRegression()
regressor_quadratic.fit(x_train_quadratic, y_train)
xx_quadratic = quadratic_featurizer.transform(xx.reshape(xx.shape[0], 1))
# Visualizing the Linear Regression results
def viz_linear():
plt.scatter(x_test, y_test, c='red')
plt.plot(x_test, regressor.predict(x_test), color='blue')
plt.axis([0, 15, 0, 1000000])
plt.title('(Linear Regression)')
plt.xlabel('Experience level')
plt.ylabel('Salary')
plt.show()
return
viz_linear()
# Plotting the polynomial regression model
plt.plot(xx, regressor_quadratic.predict(xx_quadratic), c='r', linestyle='--')
plt.title('Salary of employees per years of experience - Polynomial regression')
plt.xlabel('Years of experience')
plt.ylabel('Salary In $')
plt.axis([0, 15, 0, 1000000])
plt.grid(True)
plt.scatter(x_test,y_test)
plt.show()
print(x_train)
print(x_train_quadratic)
print(x_test)
print(x_test_quadratic)
#In the below statement we can predict what salary to expect at certain experience
#levels using linear regression
print("Linear regression model prediction: ")
print(regressor.predict([[7.5]]))
#And in the following statement we can do the same and get a more accurate estimate
#of a salary at a certain experience level
print("Polynomial regression model prediction: ")
print(regressor_quadratic.predict(quadratic_featurizer.transform([[7.5]])))
|
bd013ca25eb6a37d1cdd08177ff6fa200a5ef11a | ZX1209/gl-algorithm-practise | /leetcode-gl-python/leetcode-30-串联所有单词的子串.py | 5,033 | 3.546875 | 4 | # leetcode-30-串联所有单词的子串.py
# 题目描述
# 提示帮助
# 提交记录
# 社区讨论
# 阅读解答
# 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
# 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
# 示例 1:
# 输入:
# s = "barfoothefoobarman",
# words = ["foo","bar"]
# 输出:[0,9]
# 解释:
# 从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" 。
# 输出的顺序不重要, [9,0] 也是有效答案。
# 示例 2:
# 输入:
# s = "wordgoodgoodgoodbestword",
# words = ["word","good","best","word"]
# 输出:[]
"""
思路:
单词重叠??
长度相同的words?
恰好可以由words中所有单词串联形成的子串?
长度就固定了.
找子串
子串符合一定规律
组合 再 查找?
"""
class Solution:
def findSubstring(self, s, words):
from collections import Counter
if not words or len(s)<len(words)*len(words[0]):
return []
wl = len(words[0])
i = 0
tmpset = Counter(words)
results = []
start = i
# 遍历 s
while i<len(s):
# 如果 这个单词 是需要的
if s[i:i+wl] in tmpset:
tmpset[s[i:i+wl]] -= 1
if tmpset[s[i:i+wl]]<=0:
del tmpset[s[i:i+wl]]
# 是否全部符合
if tmpset == Counter():
results.append(start)
tmpset = Counter(words)
i = start
start = i+wl
i+=wl
# 否则,找到需要的
else:
tmpset = Counter(words)
i = start+1
while i<len(s):
if i+wl<len(s) and s[i:i+wl] in words:
start = i
break
i+=1
return results
# 参考
# 滑动窗口?
class Solution:
def findSubstring(self, s, words):
from collections import Counter
if not words or len(s)<len(words)*len(words[0]):
return []
result = []
word_len = len(words[0])
for stripe in range(word_len): # each stripe starts at a different position in s, modulo word_len
i = stripe # the next index in s that we want to match a word
to_match = len(words) # number of words still to be matched
freq = Counter(words) # frequency of each words to be matched
while i+to_match*word_len<=len(s): #remainder fo s is long enough to hold remaining unmatched words
word = s[i:i+word_len] # next part of s attempting to be matched
if word in freq: # match, decrement freq count
freq[word]-=1
if freq[word]<=0:
del freq[word]
to_match -= 1
i+=word_len
if to_match == 0: # all matched
result.append(i-word_len*len(words))
elif to_match != len(words): # some words have been matched
nb_matches = len(words) - to_match
first_word = s[i-nb_matches*word_len:i-(nb_matches-1)*word_len]
freq.setdefault(first_word,0)
to_match+=1
else:
i+=word_len
return result
# 执行用时为 64 ms 的范例
class Solution:
def findSubstring(self, s, words):
if len(words) == 0:
return []
lens = len(s)
lenw = len(words[0])
lenws = lenw * len(words)
if lens < lenws:
return []
counter = {}
for i in range(len(words)):
if words[i] in counter:
counter[words[i]] += 1
else:
counter[words[i]] = 1
res = []
for i in range(min(lenw, lens-lenws + 1)):
s_pos = word_pos = i
d = {}
while s_pos + lenws <= lens:
# 截取单词
word = s[word_pos:word_pos + lenw]
# 移动到下一个单词
word_pos += lenw
if word not in counter:
s_pos = word_pos
d.clear()
else:
if word not in d:
d[word] = 1
else:
d[word] += 1
while d[word] > counter[word]:
d[s[s_pos:s_pos + lenw]] -= 1
s_pos += lenw
if word_pos - s_pos == lenws:
res.append(s_pos)
return res
if __name__ == '__main__':
s = "barfoothefoobarman"
words = ["foo","bar"]
test = Solution()
r = test.findSubstring(s,words)
print(r)
|
0acf6c68b2eac13d7b8f4ca6864d47731af913c8 | key1024/codelearn | /pythoncode/ds_reference.py | 267 | 4.03125 | 4 | print('Simple Assignment')
shoplist = ['apple', 'banana', 'carrot', 'mango']
mylist = shoplist
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
mylist = shoplist[:]
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist) |
3d2d68f95968be2ae00135dfb22e49b046ea0051 | jinwoo123/MyPython | /Ch01/Ex04.py | 194 | 3.6875 | 4 | import turtle
t = turtle.Turtle()
t.shape("turtle")
a=100
b=90
t.forward(a)
t.left(b)
t.forward(a)
t.right(b)
t.forward(a)
t.right(b)
t.forward(a)
t.left(b)
t.forward(a)
|
632020af0a08b3c4c572e7ad9d198410c31e773a | Sindhu9527/CoursePython | /mbox-short.py | 631 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 23:56:26 2019
@author: sindh
"""
#assignment 8.5
fname = input("Enter file name: ")
#if len(fname) < 1 : fname = "mbox-short.txt"
fd = open("C:\\Users\\sindh\\Desktop\\COURSERA\\PyDSC\\Asisgnment 8.4\\Assgnment 8.5\\mbox-short.txt")
count = 0
for line in fd:
line = line.rstrip()
if line == " " :
continue
if line.startswith('From') :
words = line.split()
if(len(words)) > 2:
print (words[1])
count = count + 1
print("There were", count, "lines in the file with From as the first word")
|
b8eb6cf7ce4b2f3993736c6ae0b698ed60b0b759 | saidrobley/Python_Challenges | /PalindromeNumber.py | 424 | 3.984375 | 4 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
class PalindromeNumber:
def isPalindrome(self, x: int) -> bool:
new_x = str(x)
i = 0
j = len(new_x) - 1
while i < j:
if new_x[i] == new_x[j]:
i += 1
j -= 1
else:
return False
return True
|
1f0ff92d240868394ff915f032f36eca7feb5a23 | cluntsao/python-learning | /ArithmeticProgression.py | 693 | 3.875 | 4 | from Progression import Progression
class ArithmeticProgression(Progression):
"""Iterator producing an arithmetic progression"""
def __init__(self, increment = 1, start = 0):
"""Create a new arithmetic progression
increment: the fixed constant to add to each term (default 1)
start: the first term of the progression (default 0)
"""
super().__init__(start)
self._increment = increment
def _advance(self):
"""Update current value by adding the fixed increment"""
self._current += self._increment
def main():
ap1 = ArithmeticProgression()
ap1.print_progression(10)
if __name__ == '__main__':
main()
|
4a336467effd5aa0dda4d9b4af845bf6ecd3ceb2 | ComplicatedBread/python-notes | /thing.py | 1,793 | 3.890625 | 4 | time = 1800
place_of_work = "Highview"
town_of_home = "Ramsbottom"
if time == 700:
print(town_of_home)
elif time == 900:
print(place_of_work)
else:
print("commuting")
password = "hi"
print (len(password))
if (len(password)) <8:
print("Password is too short")
else:
print(password)
num = 50
if num % 3 == 0 or num % 5 == 0:
print("This number is divisible by 3 or 5")
else:
print("This number is not divisible by 3 or 5")
num = 89
if num % 3 == 0:
print("fizz")
elif num % 5 == 0:
print("buzz")
elif num % 3 and num % 5: #this goes first
print("fizzbuzz")
else:
print(num)
num1 = 1
num2 = 3
if (num1 + num2) % 2 ==0:
print("success!")
else:
print("")
#copied
num = 1233321
num_string = str(num)
num_string_reversed = num_string[::-1]
if num_string == num_string_reversed:
print('{} is a Palindrome'.format(num_string))
else:
print('{} is a Not a Palindrome'.format(num_string))
def sandwich_order(top1, top2, top3, top4, top5):
print("Preparing order with {}, {}, {}, {} and {}")
for i in range(5):
print(i)
for i in range (9, -1, -1):
print(i)
fave_films = ["Legend of the guardians", "The hobbits", "HTTYD", "Lord of the rings", "Harry Potter"]
for i in range(len(fave_films)):
print(fave_films[i])
fav_films = [
"True Romance",
"The Descent",
"Ghost",
"Aliens",
"Scream"
]
fav_films.insert(4, "Scream 2")
fav_films.append("You're Next")
for film_index in fav_films:
print(film_index)
def film_check():
if fav_films[2] == "Ghostbusters":
print("Yay, it is Ghostbusters.")
else:
print("Boo, we would prefer Ghostbusters.")
film_check() |
ef56a4fbeee09889bcdaef580d997981880c2bac | rohanwarange/Python-Tutorials | /built_in_function/map_and_lamada.py | 263 | 3.515625 | 4 | # number=[1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,32,43,54,65,78,89,444,567]
# print(list(map(lambda a:a*a,number)))
n=int(input("Enter the Number"))
l=[]
for i in range(n):
a=list(map(int,input().strip().split()))
print(a)
l.append(a)
print(l)
|
e3d7a1d0530498c256133f36fe94b2189c8ab604 | Saurabh-Singh-00/data-structure | /sorting/quick_sort.py | 685 | 3.796875 | 4 | # Enter numbers space separated
array = list(map(int, input().split()))
def partition(array, start=0, end=0) -> int:
x = start
pivot = array[start]
for i in range(start+1, len(array)):
if pivot > array[i]:
x += 1
array[x], array[i] = array[i], array[x]
array[start], array[x] = array[x], array[start]
return x
def quick_sort(array, left=0, right=0):
if left >= right:
return
pivot_point: int = partition(array, start=left, end=right)
quick_sort(array, left=left, right=pivot_point-1)
quick_sort(array, left=pivot_point+1, right=right)
return array
print(quick_sort(array, left=0, right=len(array)))
|
7291965505d9d04537b9dca3ad53bcfd3ea76e0c | ShristiC/Python-Games | /BlackJackGame/Objects.py | 4,072 | 4.34375 | 4 | """
Objects File which has the initial OOP code for Card, Deck, and Player
Card Class: designates the card's rank, suit, and value
Deck Class: designated a deck of cards
Player Class: defines how the Player operates
"""
import random
# Program Constants
# dictionary of card value pairs
values = {
'Two' : 2,
'Three' : 3,
'Four' : 4,
'Five' : 5,
'Six' : 6,
'Seven' : 7,
'Eight' : 8,
'Nine' : 9,
'Ten' : 10,
'Jack' : 10,
'Queen' : 10,
'King' : 10,
'Ace' : [1,11]
}
# Has the card suit
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
# Orders the ranks of the cards
ranks = (
'Two' ,
'Three',
'Four' ,
'Five' ,
'Six' ,
'Seven',
'Eight',
'Nine' ,
'Ten' ,
'Jack' ,
'Queen',
'King' ,
'Ace'
)
# Defines the Cards in a Deck of Cards
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
self.faceup = True
def __str__(self):
return self.rank + " of " + self.suit
# Defines the Deck of Cards
class Deck:
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
self.all_cards.append(Card(suit, rank))
def shuffle(self):
''' intenral shuffling of the deck '''
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop()
# Defines the Player Class
class Player:
def __init__(self, name):
self.name = name
# default bet value of 2
self.bet = 2
self.hand = []
self.total = 0
def add_bet(self, bet):
self.bet = bet
def add_cards(self, new_cards):
if type(new_cards) == type([]):
# list of cards
self.hand.extend(new_cards)
else:
# single card
self.hand.append(new_cards)
def calculate_total(self):
# calculates the total of the current hand that the player has
total_value = 0
for card in self.hand:
if(card.rank == 'Ace'):
while True:
temp = int(input("Should this Ace be treated as a 1 or 11? "))
if temp != 1 or temp != 11:
print("Not a valid number, please try again")
continue
else:
total_value += temp
break
else:
total_value += card.value
print(f"current total: {total_value}")
self.total = total_value
return total_value
def print_hand(self):
# prints the current hand that the player has
for card in self.hand:
print(card.rank, end=" ")
print()
def __str__(self):
return f'Player {self.name} has {len(self.hand)} cards'
# Defines the Dealer Class
class Dealer:
def __init__(self):
self.player_bet = 2
self.hand = []
def add_bet(self, bet):
self.bet = bet
def add_cards(self, new_cards):
if type(new_cards) == type([]):
# list of cards
self.hand.extend(new_cards)
else:
# single card
self.hand.append(new_cards)
def calculate_total(self):
# calculates the current total of the hand the dealer has
total_value = 0
for card in self.hand:
if(card.rank == 'Ace'):
total_value += card.value[1]
else:
total_value += card.value
print(f"current total: {total_value}")
return total_value
def print_hand(self):
# prints the current hand of the dealer
for card in self.hand:
if card.faceup:
print(card.rank, end=" ")
else:
print("FACEDOWN", end=" ")
print()
def __str__(self):
return f'Dealer has {len(self.hand)} cards'
|
b6ab8044d9330b388e5c82016af90ff887b00116 | jwoojun/CodingTest | /src/main/python/study/boj/dp/BOJ-10422.py | 309 | 3.5 | 4 | import sys
import math
input = sys.stdin.readline
N = int(input())
def catal(N):
return math.factorial(2 * N) // (math.factorial(N) * math.factorial(N + 1))
for i in range(N):
number = int(input())
if number % 2 != 0:
print(0)
else:
print(catal(number // 2) % 1000000007)
|
a24133b2af89941f10a7d16f5e78e99f25455496 | rzhou10/Leetcode | /800/832.py | 339 | 3.609375 | 4 | '''
Flipping an Image
Runtime: 48 ms
'''
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
for i in A:
i.reverse()
for i in range(len(A)):
for j in range(len(A[i])):
A[i][j] = 1 if A[i][j] == 0 else 0
return A |
f480149cd8a229c9df936832df5e33f25083a22b | deeph4ze/ProjectEuler | /9.py | 592 | 3.765625 | 4 | # pythagorean triplet a < b < c where a**2 + b**2 = c**2
#
#find the only one for which a+b+c = 1000
#
#
#
import time
start = time.time()
def find_answer():
for a in range(1, 998):
for b in range(a+1,998):
for c in range(b+1,998):
if (a+b+c != 1000):
continue
else:
if (a**2 + b**2 == c**2):
print "final"
print a
print b
print c
now = time.time()-start
print "found in" + str(now)
return a*b*c
else:
print a
print b
print c
continue
print find_answer()
|
ff4c1c2688f18a0ac26a21d7d5290077c9f917d3 | jglantonio/learnPython | /scripts/ej_006_for.py | 351 | 4.125 | 4 | lista = ['perro','gato','conejo']
for elemento in lista :
print(elemento)
for x in range(0, 3):
print(x)
for elemento in range(1,11,1) :
print(elemento)
## CAPITALIZA UN ARRAY
lista = ['perro','gato','conejo']
aux = []
for elemento in lista :
aux.append(elemento.title())
print(aux)
print(list(range(4)))
print(list(range(0,-5))) |
be10e01d47657cd346cbdb7bc672ca53df670b3b | eant/PDD-MJ-N-287 | /Clase 02/norma_fechas.py | 437 | 3.5 | 4 | from datetime import datetime
#fecha salida = "13-02-2019"
fecha = '13/2/2019'
objeto_fecha = datetime.strptime(fecha, "%d/%m/%Y")
fecha_normalizada = datetime.strftime(objeto_fecha, "%d-%m-%Y")
print(fecha, objeto_fecha, fecha_normalizada)
fecha = '2/13/2019'
objeto_fecha = datetime.strptime(fecha, "%m/%d/%Y")
fecha_normalizada = datetime.strftime(objeto_fecha, "%d-%m-%Y")
print(fecha, objeto_fecha, fecha_normalizada) |
fe1b68c65834c99e21da6e2c75fe3bf68b059f7e | aasparks/cryptopals-py-rkt | /cryptopals-py/set5/c39.py | 4,058 | 3.96875 | 4 | """
**Challenge 39**
*Implement RSA*
There are two annoying things about implementing RSA. Both of them involve key
generation; the actual encryption/decryption in RSA is trivial.
First, you need to generate random primes. You can't just agree on a prime
ahead of time, like you do in DH. You can write this algorithm yourself, but I
just cheat and use OpenSSL's BN library to do the work.
The second is that you need an 'invmod' operation (the multiplicative inverse),
which is not an operation that is wired into your language. The algorithm is
just a couple lines, but I always lose an hour getting it to work.
I recommend you not bother with primegen, but do take the time to get your own
EGCD and invmod algorithm working.
Now:
* Generate 2 random primes. We'll use small numbers to start, so you can just
pick them out of a prime table. Call them 'p' and 'q'.
* Let n be p * q. You RSA math is modulo n.
* Let et be (p-1)*(q-1) (the "totient"). You need this value only for keygen.
* Let e be 3.
* Compute d=invmod(e, et). invmod(17, 3120) is 2753.
* Your public key is [e,n]. Your private key is [d,n].
* To encrypt: c = m**e % n. To decrypt: m = c**d % n
* Test this out with a number, like "42".
* Repeat with bignum primes (keep e = 3)
Finally, to encrypt a string, do something cheesy, like convert the string to
hex and put "0x" on the front of it to turn it into a number. The math cares
not how stupidly you feed it strings.
"""
from Crypto.Util import number
import unittest
import c36
def primegen(bit_len=2048):
"""
Generates a large prime number.
Args:
bit_len (integer : 2048): The bit length of the number you want
Returns:
A prime number of size bit_len bits
"""
return number.getPrime(bit_len)
def invmod(num, mod):
"""
Performs the multiplicative inverse. I originally wrote invmod (along with)
xgcd myself, but it was just from Rosetta Code, so what's the point?
Args:
num: The number for invert
mod: The modulus
Returns:
Inverse mod of num.
"""
return number.inverse(num, mod)
def rsa_primegen(e=3, bit_len=2048):
"""
Generates a large prime number for RSA. There is a restriction here such
that (p-1) % e != 0, so this function checks for that.
Args:
e: RSA exponent
Returns:
A large prime number for RSA.
"""
p = primegen(bit_len)
while (p-1) % e == 0:
p = primegen(bit_len)
return p
def rsa_keygen(e=3, bit_len=2048):
"""
Performs the RSA math and gives back the public and private keys.
Returns:
The pair (pub-key, priv-key).
"""
e = 3
p, q = rsa_primegen(e, bit_len), rsa_primegen(e, bit_len)
n = p * q
et = (p-1) * (q-1)
d = invmod(e, et)
pub = [e, n]
priv = [d, n]
return pub, priv
def rsa_encrypt(message, key):
"""
Performs encryption using an RSA key.
Args:
message (bytes): The message to encrypt
key (int,int): The RSA key as a pair
Returns:
The encrypted message
"""
m = number.bytes_to_long(message)
c = pow(m, key[0], key[1])
return number.long_to_bytes(c)
def rsa_decrypt(ctxt, key):
"""
Performs decryption using RSA.
Args:
ctxt (bytes): The encrypted message
key (int, int): The RSA key as a pair
"""
# It's the same math
return rsa_encrypt(ctxt, key)
class TestRSA(unittest.TestCase):
def test_invmod(self):
self.assertEqual(invmod(17, 3120), 2753)
self.assertEqual(invmod(42, 2017), 1969)
def test_rsa_encrypt(self):
pub, priv = rsa_keygen()
message = b'Attack at dawn!'
e_msg = rsa_encrypt(message, pub)
d_msg = rsa_decrypt(e_msg, priv)
self.assertEqual(d_msg, message)
def test_keygen(self):
pub, priv = rsa_keygen()
pub1, priv1 = rsa_keygen()
self.assertNotEqual(pub, pub1)
self.assertNotEqual(priv, priv1)
if __name__ == "__main__":
unittest.main()
|
5d5cc3f255d43c2f2fb507c794a70c7cd4c6bd89 | wangleixin666/Python2.7 | /test.py | 569 | 4.0625 | 4 | #!/usr/bin/env python # -*- coding: utf-8 -*
def binarysearch(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) / 2
# print mid
if list[mid] > item:
high = mid
# print 'big'
elif list[mid] < item:
low = mid + 1
# print 'small'
else:
return mid
# 返回索引
print 'end'
return None
# 也就是说上述while循环判断都没有的话,返回None
A = [1, 3, 4, 7, 9]
print binarysearch(A, 8)
|
3bb5a2369c5b73a569c03c31d76f1669667b4400 | Daithi303/finalProjectBlePeripheral | /firmata.py | 1,192 | 3.625 | 4 | # A simple loop that reads values from the analog inputs of an Arduino port.
# No Arduino code is necessary - just upload the standard-firmata sketch from the examples.
#This file is heavily based on code found online which can be found here:
#https://github.com/rolanddb/sensor-experiments/blob/master/firmata-read-analog.py
import pyfirmata
import signal
import sys
# Definition of the analog pins you want to monitor e.g. (1,2,4)
PINS = [0]
# Do a graceful shutdown, otherwise the program will hang if you kill it.
def signal_handler(signal, frame):
board.exit()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# Connect to the board
print "Setting up the connection to the board ..."
board = pyfirmata.Arduino('/dev/ttyACM0')
# Iterator thread is needed for correctly reading analog input
it = pyfirmata.util.Iterator(board)
it.start()
# Start reporting for defined pins
for pin in PINS:
board.analog[pin].enable_reporting()
# Loop that keeps printing values
while 1:
for pin in PINS:
print "%s" % (board.analog[pin].read())
fh = open("pressureData.txt","w")
fh.write("%s" % (board.analog[pin].read()))
fh.close()
board.pass_time(1)
|
8f3a25bc8a32cade82e06065607fe77bb4a9dfb6 | wangjiaxin24/youknow_whatiwant | /leet_code/do_it.py | 1,231 | 3.78125 | 4 | 1.两数求和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict_num = {}
for index,num in enumerate(nums):
target_num = target - num
if target_num in dict_num:
if index < dict_num[target_num]:
return [index,dict_num[target_num]]
else:
return [dict_num[target_num],index]
dict_num[num] = index
return None
2.两数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.