blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ea5783ee945864fdec93a2eb6f0068a2307dbd88 | bashby2/python_fundamentals | /python_fundamentals/odd_even.py | 333 | 4.46875 | 4 | # Create a function that counts from 1 to 2000. As it loops through each number, have your program generate the number and specify whether it's an odd or even number.
for i in range (1, 2001):
if i % 2 != 0:
print "Number is {}. The number is odd".format(i)
else:
print "Number is {}. The number is even.".format(i)
|
10784b07f768e6be23990a77ed9830e051b14406 | mcwhmm/Introduction_to_Algorithms | /chapter 2/selection sort E-2.2-2.py | 570 | 3.671875 | 4 | # -*- coding: utf-8 -*-:
import random
def selectionSort(x):
if type(x) == int:
x = list(str(x))
for n in range(len(x)-1):
current_val = x[n]
i = n
min = n
while i < len(x)-1:
if x[min] > x[i + 1]:
min = i + 1
i += 1
x[n] = x[min]
x[min] = current_val
return x
test_list = list(random.randint(1, 99) for i in range(10))
print('origion list: ',test_list)
print('sorted list: ',selectionSort(test_list))
# print('sorted list: ',selectionSort([8,10,6,2,7])) |
d4c91840dbbace778df4a5c2851e9ac8dd50b9b3 | nicholaspetru/ADTeach | /archive/tokenizer.py | 1,789 | 3.90625 | 4 | '''
This is a tokenizer in python for the language Racket
We will make this accept our language later...
'''
from linkedlist import checkType
def tokenize(expression):
expression += " "
tokenList = []
temp = ""
stringFlag = False
for i in range(len(expression)):
if expression[i] == '(':
if len(temp) == 0:
temp = '('
tokenList.append(temp)
temp = ""
else:
tokenList.append(temp)
temp = '('
tokenList.append(temp)
temp = ""
elif expression[i] == ')':
if len(temp) == 0:
temp = ')'
tokenList.append(temp)
temp = ""
else:
tokenList.append(temp)
temp = ')'
tokenList.append(temp)
temp = ""
elif expression[i] == ' ':
if stringFlag:
temp += ' '
elif len(temp) > 0:
tokenList.append(temp)
temp = ""
elif expression[i] == '\t':
if stringFlag:
temp += '\t'
elif len(temp) > 0:
tokenList.append(temp)
temp = ""
elif expression[i] == '\n':
if len(temp) > 0:
tokenList.append(temp)
temp = ""
elif expression[i] == ';':
return
else:
temp += expression[i]
for i in tokenList:
print i, checkType(i)
tokenize(raw_input("enter a line to tokenize: "))
inputt = "String myString = new Stack(String).push(\"hello\").push(\"world!\").pop()"
|
58e7b32475c36f868b2d08e6d5eab2900514174b | iceljc/Explainable-AI-LSTM | /test.py | 99 | 3.546875 | 4 | import numpy as np
x = np.array([1,2,3])
y = np.array([4,5,6])
for i,j in zip(x, y):
print(i, j) |
9de39812dfee79e606eede201bdbbf5174d982e7 | patorseing/10_Day_of_Statistics | /Day_7_Spearman_s_Rank_Correlation_Coefficient/Solution_py/Solution.py | 442 | 3.53125 | 4 | def getRank(X, n):
rank = dict((x, i+1) for i, x in enumerate(sorted(set(X))))
return [rank[x] for x in X]
def rxy(n, X, Y):
rx = getRank(X, n)
ry = getRank(Y, n)
d = [(rx[i] -ry[i])**2 for i in range(n)]
return round(1 - (6 * sum(d)) / (n * (n*n - 1)), 3)
if __name__ == "__main__":
n = int(input())
X = list(map(float, input().strip().split()))
Y = list(map(float, input().strip().split()))
print(rxy(n, X, Y))
|
f2cdb4598da3aa7c88a4aa8243cc19b96de2d199 | madhumithaasaravanan/madhumitha5 | /b104.py | 98 | 3.8125 | 4 | n=int(input("enter the number:"))
k=int(input("enter the number:"))
res=int(pow(n,k));
print(res)
|
2bf0a9f57235edce1effd7cf0b71a91d8535016c | wwken/Misc_programs | /leetcode/wildcard-matching/test_wildcard-matching.py | 5,227 | 4.09375 | 4 | import unittest
from Solution import Solution
# Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
#
# '?' Matches any single character.
# '*' Matches any sequence of characters (including the empty sequence).
# The matching should cover the entire input string (not partial).
#
# Note:
#
# s could be empty and contains only lowercase letters a-z.
# p could be empty and contains only lowercase letters a-z, and characters like ? or *.
# Example 1:
#
# Input:
# s = "aa"
# p = "a"
# Output: false
# Explanation: "a" does not match the entire string "aa".
# Example 2:
#
# Input:
# s = "aa"
# p = "*"
# Output: true
# Explanation: '*' matches any sequence.
# Example 3:
#
# Input:
# s = "cb"
# p = "?a"
# Output: false
# Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
# Example 4:
#
# Input:
# s = "adceb"
# p = "*a*b"
# Output: true
# Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
# Example 5:
#
# Input:
# s = "acdcb"
# p = "a*c?b"
# Output: false
class TestStringMethods(unittest.TestCase):
sol = Solution()
def test_required(self):
self.assertEqual(self.sol.isMatch('aa', 'a'), False)
self.assertEqual(self.sol.isMatch('aa', '*'), True)
self.assertEqual(self.sol.isMatch('cb', '?a'), False)
self.assertEqual(self.sol.isMatch('adceb', '*a*b'), True)
self.assertEqual(self.sol.isMatch('acdcb', 'a*c?b'), False)
def test_basic(self):
self.assertEqual(self.sol.isMatch('c', 'ca'), False)
def test_question_mark(self):
self.assertEqual(self.sol.isMatch('cb', 'c?'), True)
self.assertEqual(self.sol.isMatch('cb', '??'), True)
self.assertEqual(self.sol.isMatch('cb', '?b'), True)
self.assertEqual(self.sol.isMatch('cb', '?'), False)
self.assertEqual(self.sol.isMatch('cb', 'b'), False)
self.assertEqual(self.sol.isMatch('cb', 'cb?'), False)
self.assertEqual(self.sol.isMatch('??a?', 'bbab'), False)
def test_star_mark(self):
self.assertEqual(self.sol.isMatch('cac', 'c*'), True)
self.assertEqual(self.sol.isMatch('cac', 'c**'), True)
self.assertEqual(self.sol.isMatch('cac', 'c***'), True)
self.assertEqual(self.sol.isMatch('cac', 'c****'), True)
self.assertEqual(self.sol.isMatch('cac', 'c*****'), True)
self.assertEqual(self.sol.isMatch('cac', 'c*****c'), True)
self.assertEqual(self.sol.isMatch('cac', 'c*****ac'), True)
self.assertEqual(self.sol.isMatch('cac', 'c*****?c'), True)
self.assertEqual(self.sol.isMatch('cac', '*cac'), True)
self.assertEqual(self.sol.isMatch('cacc', '*cc'), True)
self.assertEqual(self.sol.isMatch('cacc', '*c'), True)
self.assertEqual(self.sol.isMatch('cacc', '*ca'), False)
self.assertEqual(self.sol.isMatch('cacc', '*cac'), False)
self.assertEqual(self.sol.isMatch('cacc', '*cacc'), True)
self.assertEqual(self.sol.isMatch('ba', '*a*'), True)
def test_tricky(self):
self.assertEqual(self.sol.isMatch('aaaa', '***a'), True)
def test_tricky2(self):
self.assertEqual(self.sol.isMatch('c', '*?*'), True)
def test_tricky3(self):
self.assertEqual(self.sol.isMatch('hi', '*?'), True)
def test_tricky4(self):
self.assertEqual(self.sol.isMatch('a', ''), False)
def test_tricky5(self):
self.assertEqual(self.sol.isMatch('abcde', '*?*?*?*?'), True)
def test_tricky6(self):
self.assertEqual(self.sol.isMatch('bbbab', '*??a?'), True)
def test_tricky7(self):
self.assertEqual(self.sol.isMatch('baabba', '?*?a??'), False)
def test_tricky8(self):
self.assertEqual(self.sol.isMatch('babbbbaabababaabbababaababaabbaabababbaaababbababaaaaaabbabaaaabababbabbababbbaaaababbbabbbbbbbbbbaabbb',
'b**bb**a**bba*b**a*bbb**aba***babbb*aa****aabb*bbb***a'), False)
def test_tricky9(self):
self.assertEqual(self.sol.isMatch('bba', '*a**'), True)
def test_tricky10(self):
self.assertEqual(self.sol.isMatch('aac', '*c****'), True)
def test_tricky11(self):
self.assertEqual(self.sol.isMatch('abbabaaabbabbaababbabbbbbabbbabbbabaaaaababababbbabababaabbababaabbbbbbaaaabababbbaabbbbaabbbbababababbaabbaababaabbbababababbbbaaabbbbbabaaaabbababbbbaababaabbababbbbbababbbabaaaaaaaabbbbbaabaaababaaaabb',
'**aa*****ba*a*bb**aa*ab****a*aaaaaa***a*aaaa**bbabb*b*b**aaaaaaaaa*a********ba*bbb***a*ba*bb*bb**a*b*bb'), False)
def test_tricky12(self):
self.assertEqual(self.sol.isMatch('mississippi',
'm??*ss*?i*pi'), False)
def test_tricky13(self):
self.assertEqual(self.sol.isMatch('aaababbbbabaaababbaaa',
'aaa*bba*aa*a*abb*a*a'), True)
self.assertEqual(self.sol.isMatch('abbbaaaaaaaabbbabaaabbabbbaabaabbbbaabaabbabaabbabbaabbbaabaabbabaabaabbbbaabbbaabaaababbbbabaaababbaaa',
'ab**b*bb*ab**ab***b*abaa**b*a*aaa**bba*aa*a*abb*a*a'), True)
|
b8e41431f1f499c8a998cb1967070db73347b21c | Strokov/PyRuletka | /ucheba.py | 1,899 | 3.625 | 4 | # coding: utf-8
# комментарий
import sys
import math
import datetime
import os
import psutil
import shutil
def Info_sys():
print('Вот, что я знаю о системе:')
print("Operating System: ", sys.platform)
print("Count of processes: ", psutil.cpu_count())
print("Текущая директория: ",os.getcwd())
print ('Текущий пользователь: ',os.getlogin())
return " ФОРМАТИРУЕМ ДИСК С!"
def double_files():
print("Дублирование файлов в текущей директории: ")
file_list = os.listdir()
i = 0
while i<len(file_list):
newfile = file_list[i]+".dubl"
shutil.copy(file_list[i],newfile)
i=i+1
def main():
print("I'm Python, HI!")
name = input("?? Your name: ")
print(name,", you wanna work? (Y/N)")
answer = input()
if answer == "Y" or answer =="y" or answer =="yes" or answer =="YES" or answer =="ye":
print("Good! Take a gift!")
print ("[1] - Close the application!")
print ("[2] - information about your system!")
print ("[3] - files in this directory!")
print ("[4] - duplicate files in this directory!")
print ("[5] - !")
do = int(input())
if do == 1:
print("Close the application!")
sys.exit()
elif do == 2:
Info_sys()
elif do == 3:
print("3 maybe: ", math.log10(1000))
print(os.listdir())
elif do == 4:
double_files()
else:
print("I do not understand what you want!")
elif answer == "N" or answer == "No":
print("Die! fucker!")
elif answer == "n" or answer == "no":
print("Die! fucker!")
else:
print ("Stupid men, buy-buy!!!")
if __name__=="__main__":
main() |
f57a9b529348d90ffaa09d873c2c077d20da1ea1 | yhytoto12/advent-of-code | /2021/DAY12/main.py | 1,435 | 3.5 | 4 | from itertools import count
import numpy as np
import networkx as nx
G = nx.Graph()
S = 'start'
T = 'end'
with open('input.txt', 'r') as f:
lines = f.readlines()
edges = [line[:-1].split('-') for line in lines]
G.add_edges_from(edges)
def countPath1(curr, visited):
if curr == T:
return 1
num_path = 0
for next in G.neighbors(curr):
if next[0].isupper() or visited[next] == 0:
visited[next] += 1
num_path += countPath1(next, visited)
visited[next] -= 1
return num_path
def Part1():
visited = dict(zip(G.nodes(), [0] * G.number_of_nodes()))
visited[S] = 1
return countPath1(S, visited)
def countPath2(curr, visited, twice_visited):
if curr == T:
return 1
num_path = 0
for next in G.neighbors(curr):
if next[0].isupper() or visited[next] == 0:
visited[next] += 1
num_path += countPath2(next, visited, twice_visited)
visited[next] -= 1
elif visited[next] == 1 and not twice_visited and next != T:
visited[next] += 1
num_path += countPath2(next, visited, True)
visited[next] -= 1
return num_path
def Part2():
visited = dict(zip(G.nodes(), [0] * G.number_of_nodes()))
visited[S] = 2
visited[T] = 0
return countPath2(S, visited, False)
print('Part1 :', Part1())
print('Part2 :', Part2())
|
f0a9c4fa420573bc7ace1cfd871f955d8b95b36a | chiache1999/1st-PyCrawlerMarathon | /hw1.py | 1,769 | 3.703125 | 4 | #簡答題
'''檔案、API、爬蟲的不同:
1. 檔案資料會包成檔案提供下載,格式可能包含常⽤用的標準格式,例例如「CSV」、「JSON」等等通⽤用的格式。
2. 開放接口(API)提供程式化的連接的接口,讓工程師/分析師可以選擇資料中要讀取的特定部分,⽽而不需要把整批資料事先完整下載回來
3. 網頁爬蟲資料沒有以檔案或 API 提供,但出現在網⾴頁上。可以利用爬蟲程式,將網頁的資料解析所需的部分。
前兩者是資料擁有者主動提供,後者則是被動'''
#實作
#根據需求引入正確的Libary
from urllib.request import urlretrieve
import os,sys
#下載檔案到data資料夾,存檔為homework.txt
try:
os.makedirs('./Data/',exist_ok=True)
urlretrieve("https://www.w3.org/TR/PNG/iso_8859-1.txt", "./Data/Homework.txt")
except:
print('error')
#確認Data資料夾中有Homework.txt的檔案
files = []
dirs = os.listdir('./')
for file in dirs:
files.append(file)
if 'Homework.txt' in files:
print('[O] 檢查 Data 資料夾是否有 Homework.txt 檔名之檔案')
else:
print('[X] 檢查 Data 資料夾是否有 Homework.txt 檔名之檔案')
#將'hello world'字串填寫到檔案中
f =''
with open("./Data/Homework.txt", "w") as fh:
f = fh.write('Hello World')
try:
with open("./Data/Homework.txt","r") as fh:
f = fh.read()
print(f)
except EnvironmentError:
pass
#檢查檔案字數是否符合hello world
if len('Hello World') == len(f):
print('[O] 檢查 Homework.txt 檔案字數是否符合 Hello World 字數')
else:
print('[X] 檢查 Homework.txt 檔案字數是否符合 Hello World 字數')
|
c35ec8df64c057205fcc78430c9a247cc707ffa7 | devchoplife/DataScience-Python | /src/corrstats.py | 375 | 3.84375 | 4 | import pandas as pd
#we want to lool at the correlation between horsepower and car price
#Scipy is used for this purpose
pearson_coef, pvalue = stats.pearsonr(df["horsepower", df["price"]])
#the result will be the correlation coefficient and the p value
#We can also create a correlation heatmap
plt.pcolor (pearson_coef, pvalue, cmap='RdBu')
plt.colorbar()
plt.show()
|
fac6f49684d612f887e06801b5c0fc42b4aad6eb | Saber-f/code | /other/实验报告/NCM/Least_squares.py | 2,492 | 3.640625 | 4 | # 最小二乘法,矩阵及平方和解
from numpy import *
from sympy import *
x = symbols('x')
# 获取数据
def get_data():
E = input("请输入表达式::").split()
i = 0
while i < len(E):
E[i] = eval(E[i])
i += 1
X = input("请输入x::").split()
i = 0
while i < len(X):
X[i] = eval(X[i])
i += 1
while True:
Y = input("请输入y::").split()
if len(X) == len(Y):
break
i = 0
while i < len(Y):
# Y[i] = float(log(eval(Y[i])))
Y[i] = eval(Y[i])
i += 1
return (E, X, Y)
# 矩阵求解
def Matrix_solution(E, X, Y):
A = mat(random.rand(len(X), len(E)))
B = mat(random.rand(len(Y),1))
i = 0
while i < len(X):
j = 0
B[i,0] = Y[i];
while j < len(E):
if type(E[j]) == int or type(E[j]) == float:
A[i,j] = E[j]
else:
A[i,j] = E[j].subs(x,X[i])
j += 1
i += 1
return (A, B, (A.T * A).I * A.T * B)
# 平方和解法
def Square_sum_solution(X, Y, E):
# 加入符号系数
i = 0
a = []
while i < len(E):
a.append(symbols('a'+str(i)))
i += 1
Q = 0
i = 0
while i < len(X):
j = 0
t = 0
while j < len(E):
if type(E[j]) == int or type(E[j]) == float:
t += E[j] * a[j]
else:
t += E[j].subs(x,X[i]) * a[j]
j += 1
t -= Y[i]
Q += t**2
i += 1
A = mat(random.rand(len(E),len(E)+1))
i = 0
print('\nQ::',expand(Q),'\n')
while i < len(E):
q = diff(Q,a[i])
print('dQ/d'+str(a[i]),q,' = 0')
j = len(E)
while j >= 0:
t = q
k = 0
while k < len(E):
if k == j:
t = t.subs(a[k],1)
else:
t = t.subs(a[k],0)
k += 1
if j == len(E):
A[i,j] = -t
else:
A[i,j] = t + A[i,len(E)]
j -= 1
i += 1
return A[:,0:len(E)].I*A[:,len(E)]
# dedaowucha
def get_e(A, B, a):
t = A*a - B
return t.T * t
# 主函数
def main():
(E, X, Y) = get_data()
(A, B, a) = Matrix_solution(E, X, Y)
print('\nA::\n',A,'\n\nB::\n',B,'\n\na::\n',a,'\n\ne:',get_e(A, B, a),'\n\n\n')
a = Square_sum_solution(X, Y, E)
print('\na::\n',a,'\n\ne:',get_e(A, B, a))
main()
|
2a04510c95a39effef766fa96a87524643ce5bfe | andrzeji-oss/kursp | /dzien3/dzien3_3.py | 736 | 3.5 | 4 | # wygeneruj 100 elementową tablice z randomowymi wartościami 1-100
# utwórz listę wartości
import random
randomList = []
count = 0
liczba = int(input("Podaj liczbę z zakresu 1-10:" ))
for i in range(100):
randomList.append(random.randint(1,10))
print(randomList)
if(liczba not in randomList):
print("Element %i nie występuje w liście" % liczba)
else:
for index, value in enumerate(randomList):
if(value == liczba):
print("Element %i znajduje się na indeksie %i" % (liczba, index))
break
#sprawdz ile razy dany elemtent wystepuje na liście
for liczba in randomList:
if(value == liczba):
count += 1
print("Element %i występuję w liście %i razy" % (value, count)) |
9e07b525252b053cc540144f7df16ef52fbdb92e | menard-noe/LeetCode | /Maximum Depth of N-ary Tree.py | 889 | 3.78125 | 4 | # Definition for a binary tree node.
import math
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root is None:
return 0
def util(node: Node) -> int:
if not node:
return 0
if not node.children:
return 1
depth = max(util(child) for child in node.children) + 1
return depth
return util(root)
if __name__ == "__main__":
# execute only if run as a script
tree = Node(1)
tree_a = Node(3)
tree_b = Node(2)
tree_c = Node(4)
tree_a_a = Node(5)
tree_a_b = Node(6)
tree.children = [tree_a, tree_b, tree_c]
tree_a.children = [tree_a_a, tree_a_b]
solution = Solution()
print(solution.maxDepth(tree))
|
69fd86cf88f26831c549d7919adcde0c3d907c02 | juliovt-07/FechamentoDeConta | /main.py | 2,391 | 3.640625 | 4 | import time
escolha = 1
cont = 0
v = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
while escolha == 1:
print("[codigo] nome")
print("[ 10 ] Produto 1")
print("[ 11 ] Produto 2")
print("[ 12 ] Produto 3")
print("[ 13 ] Produto 4")
print("[ 14 ] Produto 5")
print("[ 15 ] Produto 6")
codigo = int(input("Codigo: "))
if codigo <= 0:
print("codigo invalido!")
elif codigo == 10:
valorEmpresa = 91
valorSalao = valorEmpresa+(valorEmpresa*0.40)
print("Valor (empresa): {} R$".format(valorEmpresa))
print("Valor da venda: {} R$".format(valorSalao))
#print("Dizimo: {}".format((valorSalao-valorEmpresa)*0.10))
print("Ganho: {} R$".format(valorSalao-valorEmpresa))
elif codigo == 11:
valorEmpresa = 24
valorSalao = valorEmpresa+(valorEmpresa*0.40)
print("Valor (empresa): {} R$".format(valorEmpresa))
print("Valor da venda: {} R$".format(valorSalao))
#print("Dizimo: {}".format((valorSalao-valorEmpresa)*0.10))
print("Ganho: {} R$".format(valorSalao-valorEmpresa))
elif codigo == 12:
valorEmpresa = 130
valorSalao = valorEmpresa+(valorEmpresa*0.40)
print("Valor (empresa): {} R$".format(valorEmpresa))
print("Valor da venda: {} R$".format(valorSalao))
#print("Dizimo: {}".format((valorSalao-valorEmpresa)*0.10))
print("Ganho: {} R$".format(valorSalao-valorEmpresa))
elif codigo == 13:
valorEmpresa = 65
valorSalao = valorEmpresa+(valorEmpresa*0.40)
print("Valor (empresa): {} R$".format(valorEmpresa))
print("Valor da venda: {} R$".format(valorSalao))
#print("Dizimo: {}".format((valorSalao-valorEmpresa)*0.10))
print("Ganho: {} R$".format(valorSalao-valorEmpresa))
elif codigo == 14:
valorEmpresa = 48.50
valorSalao = valorEmpresa+(valorEmpresa*0.40)
print("Valor (empresa): {} R$".format(valorEmpresa))
print("Valor da venda: {} R$".format(valorSalao))
#print("Dizimo: {}".format((valorSalao-valorEmpresa)*0.10))
print("Ganho: {} R$".format(valorSalao-valorEmpresa))
time.sleep(1)
print("|"*35)
v[cont] = valorSalao-valorEmpresa
#print(cont)
#print(v[:(cont+1)])
cont = cont+1
time.sleep(1)
escolha = int(input("[Codigo]\n[ 1 ] Adicionar Produto\n[ 2 ] Mostrar Valor Total\n- "))
GanhoTotal = (v[0]+v[1]+v[2]+v[3]+v[4]+v[5]+v[6]+v[7]+v[8]+v[9]+v[10]+v[11]+v[12])
print("Ganho Total: {} R$".format(GanhoTotal)) |
b3d5210421adaec5a6b3b6fe688728d5db23f9d1 | ezequiasOR/Exercicios-LP1 | /unidade8/cocktail_sort.py | 709 | 3.71875 | 4 | #coding: utf-8
#UFCG - Programação I - 2018.1
#Aluno: Ezequias Rocha
#Questão: Cocktail Sort - Unidade 8
lista = [3, 4, 2, 0, 5, 6, 7,1]
def cocktailSort(lista):
lista_saida = []
lista_aux = []
lista_aux += lista
lista_saida.append(lista_aux)
trocou = True
while trocou:
trocou = False
lista_aux = []
for i in range(len(lista)-1):
if lista[i] > lista[i+1]:
lista[i], lista[i+1] = lista[i+1], lista[i]
trocou = True
for j in range(len(lista)-1, 0, -1):
if lista[j] < lista[j-1]:
lista[j], lista[j-1] = lista[j-1], lista[j]
trocou = True
lista_aux += lista
lista_saida.append(lista_aux)
lista_saida.pop(-1)
return lista_saida
print cocktailSort(lista)
|
bcf982d063f36f2538ee4e73ecad8a5fa01fb64c | jonatanbedoya/ST0245-Eafit | /proyecto/CodigoYaEmpezado/decision_tree.py | 1,628 | 3.6875 | 4 | """
Module containing the necessary classes and functions to build a CART Decision Tree.
"""
from utilities.utils import class_counts
from utilities.math import find_best_split, partition
class Leaf:
"""
A leaf node classifies data.
It holds a dictionary of class -> number of times it appears in the rows
from the training data that reached the leaf.
"""
class DecisionNode:
"""
A decision node asks a question.
It holds a reference to a question and to the two child nodes.
"""
def build_tree(rows, headers):
"""
Builds the tree following this rules:
1. Believe that it works.
2. Start by checking for the base case (no further info gain).
3. Prepare for giant stack traces.
"""
def classify(row, node):
""" Classify a given input on a given tree. """
def print_tree(node, spacing=""):
""" Print the tree to the standard output. """
# base case: we've reached a leaf.
if isinstance(node, Leaf):
print(spacing + "Predict", node.predictions)
return
# print the question at the current node
print(spacing + str(node.question))
# call this function recursively on the true and false branches
print(spacing + "--> True:")
print_tree(node.true_branch, spacing + " ")
print(spacing + "--> False:")
print_tree(node.false_branch, spacing + " ")
def print_leaf(counts):
""" A nicer way to print the predictions at a leaf. """
total = sum(counts.values()) * 1.0
probs = {}
for lbl in counts.keys():
probs[lbl] = str(int(counts[lbl] / total * 100)) + '%'
return probs
|
4891db9dbcb0b863349fd06ca4c66dda5e3851a7 | ZHKO1/leetcode | /74.py | 552 | 3.515625 | 4 | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
nums = []
for i in matrix:
nums = nums + i
low = 0
high = len(nums) - 1
while (low <= high):
mid = (low + high) // 2
if (target == nums[mid]):
return True
if (target > nums[mid]):
low = mid + 1
else:
high = mid - 1
return False |
bd01f579669f737061837f6fcdf3aadc3e519586 | Beelzebub0/PY4E | /10th.py | 409 | 3.984375 | 4 |
fname = input("Enter file name: ")
try:
fh = open(fname)
except:
print("can't open", fname)
quit()
count = 0
for line in fh:
line = line.rstrip()
if not line.startswith("From") : continue
if line.startswith("From:") : continue
words = line.split()
print(words[1])
count = count+1
print("There were", count, "lines in the file with From as the first word")
|
a1de5ae5e046ba45bd8ed366115bb2b94e6a7aaa | hao44le/CS410-MPS | /MP2-FA19_part1/scraper_code/scraper.py | 5,489 | 3.53125 | 4 | from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import re
import urllib.request
root_dir = "https://engineering.purdue.edu/Engr/People/ptDirectory"
faculty_letters = ["A",'B','C']
BIO_URLS_FILE_LOCATION = "../bio_urls.txt"
BIOS_FILE_LOCATION = "../bios.txt"
TIMEOUT = 30
MINIMUM_BIO_REQUIREMENT = 10
''' More tidying
Sometimes the text extracted HTML webpage may contain javascript code and some style elements.
This function removes script and style tags from HTML so that extracted text does not contain them.
'''
def remove_script(soup):
for script in soup(["script", "style"]):
script.decompose()
return soup
#uses webdriver object to execute javascript code and get dynamically loaded webcontent
def get_js_soup(url,browser):
soup = None
try:
browser.get(url)
res_html = browser.execute_script('return document.body.innerHTML')
soup = BeautifulSoup(res_html,'html.parser') #beautiful soup object to be used for parsing html content
soup = remove_script(soup)
except:
soup = None
return soup
# Helper Funciton: Get faculties for letter
def get_faculty_for_letter(browser, letter):
url = "{}?letter={}".format(root_dir,letter)
# print(url)
soup = get_js_soup(url, browser) #get html code
# Get faculty-ids
links = []
people_rows = soup.find("div", class_="people-list").find_all("div",class_="col-8 col-sm-9 list-info")
for row in people_rows:
a = row.find("a")['href']
# print(a)
links.append(a)
return links
# Scrapy the lists of faculty links
def get_list_of_faculty_links(browser):
faculty_links = []
for letter in faculty_letters:
links = get_faculty_for_letter(browser, letter)
faculty_links += links
print(letter + " " + str(len(links)))
return faculty_links
#tidies extracted text
def process_bio(bio):
bio = bio.encode('ascii',errors='ignore').decode('utf-8') #removes non-ascii characters
bio = re.sub('\s+',' ',bio) #repalces repeated whitespace characters with single space
return bio
#Checks if bio_url is a valid faculty homepage
def is_valid_homepage(link):
try:
#sometimes the homepage url points to the faculty profile page
#which should be treated differently from an actual homepage
code = urllib.request.urlopen(link, timeout = TIMEOUT).getcode()
return code == 200
except:
return False
# Process each specific faculty link
def process_specific_faculty_link(browser, link):
if not is_valid_homepage(link): return ("", "")
soup = get_js_soup(link, browser) #get html code
if soup is None: return ("", "") #sometimes the page does not exist or wait longer than 30 seconds, then we consider it as invalid
# Check if the HOMEPAGE exist, if then parse the homepage. else just parse the current page
homepage_url = ""
bio = ""
all_ths = soup.find_all('th')
for index, th in enumerate(all_ths):
if th.text.lower() == "homepage:":
# find homepage, try to get the homepage url
homepage_url = all_ths[index+1].find("a")['href']
break
if "purdue.edu" not in homepage_url: homepage_url = "" #if we can't find purdue.edu in the homepage_url, we treat it as invalid. and use the default option
if homepage_url == "": #homepage_url does not exist, we treat current page as the homepage:
homepage_url = link
main_content = soup.find("div", class_='content col-md-9') #we only interested in this part of the page
bio = process_bio(main_content.get_text(separator=' '))
else: #homepage_url does exist,
homepage_soup = get_js_soup(homepage_url, browser)
if homepage_soup is None: return ("", "") #sometimes the directed page does not exist or wait longer than 30 seconds, then we consider it as invalid
#get all the text from homepage(bio) since there's no easy to filter noise like navigation bar etc
bio = process_bio(homepage_soup.get_text(separator=' '))
# print(homepage_url)
# print(bio)
if len(bio) < MINIMUM_BIO_REQUIREMENT: return ("", "") #if the len of bio is less than 10, we consider it as invalid
return (homepage_url, bio)
# Helper function to write array to local file
def write_array_to_local_text_file(file_name, array):
with open(file_name,'w') as f:
for l in array:
f.write(l)
f.write('\n')
if __name__ == '__main__':
#create a webdriver object and set options for headless browsing
options = Options()
# options.headless = True
browser = webdriver.Chrome(options=options)
browser.set_page_load_timeout(TIMEOUT)
faculty_links = get_list_of_faculty_links(browser) #Get lists of faculty links
#loop through the faculty links, and process each one by one
bio_urls = []
bios = []
for index, link in enumerate(faculty_links):
print("{}/{}".format(index, len(faculty_links)))
homepage_url, bio = process_specific_faculty_link(browser, link)
if homepage_url == "" or bio == "":
print("not valid! {}".format(link))
continue
bio_urls.append(homepage_url)
bios.append(bio)
#Write the data to local file system
write_array_to_local_text_file(BIO_URLS_FILE_LOCATION, bio_urls)
write_array_to_local_text_file(BIOS_FILE_LOCATION, bios)
|
b7eb9327b50f31af1a2552c9e954429926e870d8 | xccane/coursera_1 | /3_week_(float numbers)/3.3_lection_lib.py | 1,121 | 4.125 | 4 | import math # импортируется библиотека math
print(int(2.5)) # округляет в сторону нуля (отбрасывет дробную часть)
print(round(2.5)) # округляет до ближайшего целого, если дробная часть равна 0.5, то к ближайшему чётному
# перед каждым вызовом функции из библиотеки нужно писать слово ''math.'', а затем имя функции:
print(math.floor(2.5)) # округляет в меньшую сторону
print(math.ceil(2.5)) # округляет в большую сторону
print(math.trunc(2.5)) # работает аналогично int
# можно из библиотеки импортировать некоторые функции и доступ к ним можно получить без написания ''math.'':
from math import floor, ceil
print(floor(2.5)) # округляет в меньшую сторону
print(ceil(2.5)) # округляет в большую сторону
|
1e569fab695a2dcef4a3aa26efdfbc6db4b5f94b | hansrajdas/random | /max_even_length_string.py | 443 | 3.8125 | 4 | # Fractal Analytics
def longestEvenWord(sentence):
sentence = sentence.split(' ')
max_len_word = '00'
for word in sentence:
if not (len(word) % 2) and (len(max_len_word) < len(word) or max_len_word == '00'):
max_len_word = word
return max_len_word
print longestEvenWord('It is a pleasant day today')
print longestEvenWord('time to write great code')
print longestEvenWord('codes for man')
print longestEvenWord('co fo ma')
|
ac4935cd3266d77cd917b42e5843b56f0c2d9e25 | YoonKyoungTae/Algorithm | /sort/sort_heap.py | 897 | 4.0625 | 4 | # coding=utf-8
"""
[힙정렬]
주어진 배열을 힙트리에 정리 한 후
정렬을 맥스힙(인덱스 0)과 마지막 인덱스의 위치를 교체한다.
"""
def get_array():
return [10, 2, 5, 4, 7, 6, 8, 9, 3, 1]
def make_heap(arr, arr_size):
for i in range(1, arr_size):
child = i
while child != 0:
parent = (child - 1) / 2
if arr[parent] < arr[child]:
change(arr, parent, child)
child = parent
def change(arr, first, second):
temp = arr[first]
arr[first] = arr[second]
arr[second] = temp
def sort(arr):
count = len(arr) - 1
while count != 0:
change(arr, 0, count)
make_heap(arr, count)
count -= 1
array = get_array()
size = len(array)
print '정렬 전 : ' + array.__str__()
make_heap(array, size)
sort(array)
print '정렬 후 : ' + array.__str__()
|
a6a58dcf8bc96ab1276cb497d80d2fe5e15f2bd7 | cookm353/Calculator | /calculator.py | 2,956 | 4.34375 | 4 | # !usr/bin/env python3
OPERATORS = ['+', '-', '*', '/']
def get_input():
"""Obtain input from user"""
operation = input()
return operation
def clean_input(operation):
"""Handle whitespace, convert numbers to floats, and append to list"""
num = ''
statement = []
for element in operation:
if element.isnumeric():
num += element
elif element in OPERATORS:
statement.append(float(num))
statement.append(element)
num = ''
statement.append(float(num))
return statement
def initialize_total(statement):
"""Inititalize total based on operators"""
if '*' in statement or '/' in statement:
total = 1
else:
total = 0
return total
def find_operands(statement, index):
op1 = float(statement[index - 1])
op2 = float(statement[index + 1])
return op1, op2
def remove_and_replace(statement, index, result):
"""Remove the operator and the operands, then insert result of operation"""
del statement[index - 1: index + 2]
statement.insert(index - 1, result)
return statement
def multiply_divide(statement):
"""Perform multiplication and division then simplify statement"""
# Filter for * and / in the statement and find the first element's index
operators = list(filter(lambda x: x in ('*', '/'), statement))
index = statement.index(operators[0])
# Find operands
op1, op2 = find_operands(statement, index)
# Perform operation
if operators[0] == '*':
result = op1 * op2
elif operators[0] == '/':
result = op1 / op2
# Replace operators and operands with result
remove_and_replace(statement, index, result)
return statement
def add_subtract(statement):
"""Perform addition and subtraction then simplify statement"""
operators = list(filter(lambda x: x in ('+', '-'), statement))
index = statement.index(operators[0])
# Find operands
op1, op2 = find_operands(statement, index)
# Perform operation
if operators[0] == '+':
result = op1 + op2
elif operators[0] == '-':
result = op1 - op2
# Replace operator and operands with result
remove_and_replace(statement, index, result)
return statement
def perform_operations(statement):
"""Evaluate the statement"""
while statement.count('*') >= 1 or statement.count('/') >= 1:
statement = multiply_divide(statement)
while statement.count('+') >= 1 or statement.count('-') >= 1:
statement = add_subtract(statement)
return statement[0]
def main():
# statement = get_input()
statement = "6 + 3 * 4 - 9"
statement = clean_input(statement)
result = perform_operations(statement)
print(result)
if __name__ == "__main__":
# pass
main() |
e8a37bd9326978c9b21c2221b37e01981c7d058c | sujeongcha/Coderbyte-Python-Practice | /Easy Difficulty/8. Check Nums.py | 385 | 4.1875 | 4 | #Have the function CheckNums(num1,num2) take both parameters being passed and
#return the string true if num2 is greater than num1, otherwise return the string false.
#If the parameter values are equal to each other then return the string -1.
#My Solution
def CheckNums(num1,num2):
if num2 == num1:
return '-1'
elif num2 > num1:
return 'true'
else:
return 'false'
|
2ea9f4ea1daff8adff8fa71a5953840169b7d6c8 | AlexanderOrloff/AlexanderOrloff | /hwPython1/python1.py | 372 | 3.875 | 4 | a = int(input('введи а'))
b = int(input('введи b'))
c = int(input('введи с'))
if a / b == c:
print('а разделить на b равно с')
else:
print('а разделить на b не равно с')
if a ** b == c:
print(' а в степени b равно c')
else:
print(' а в степени b не равно с')
|
57abf06b9bf7b038965d934ba0f4b7b085ea8e2f | gaurav93d/Python | /interchange_first_last_list.py | 382 | 3.796875 | 4 |
def swapNum(newlist):
print(newlist)
a=newlist.pop()
b=newlist.pop(0)
newlist.append(b)
newlist.insert(0,a)
print(newlist)
return newlist
my = [1,2,3,4,5]
swapNum(my)
#2nd approch:
def swapNum(newlist):
print(newlist)
get = newlist[0],newlist[-1]
newlist[-1],newlist[0] = get
print(newlist)
my = [1,2,3,4,5]
swapNum(my)
|
2573731b2cae4526bbfb90ddf0c2b57850d299ff | nikmalviya/Python | /Practical 9/prac9_2_complex.py | 902 | 3.921875 | 4 | class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def add(self, other):
self.real += other.real
self.imaginary += other.imaginary
def sub(self, other):
self.real -= other.real
self.imaginary -= other.imaginary
def mul(self, other):
real = (self.real * other.real) - (self.imaginary * other.imaginary)
self.imaginary = (self.real * other.imaginary) + (self.imaginary * other.real)
self.real = real
if __name__ == '__main__':
c1 = Complex(*map(int, input('Enter Complex No1: ').split()))
c2 = Complex(*map(int, input('Enter Complex No2: ').split()))
c1.add(c2)
print(f'Addition : {c1.real}+{c1.imaginary}j')
c1.sub(c2)
print(f'Subtraction : {c1.real}+{c1.imaginary}j')
c1.mul(c2)
print(f'Multiplication : {c1.real}+{c1.imaginary}j')
|
cd2522e3c3d3a80b7d039499d0db0c980a13e8ef | alexprengere/PythonExercises | /05/runner.py | 1,857 | 4.375 | 4 | #!/usr/bin/env python
"""
Implentation of Runner class.
>>> from runner import Runner
>>> r = Runner('Sara', run_speed=20) # km/h
>>> r.run(distance=10) # distance is km, result in hours
0.5
"""
class Runner(object):
"""A runner
"""
def __init__(self, name, run_speed):
self.name = name
self.run_speed = run_speed
def run(self, distance):
return distance / float(self.run_speed)
def __str__(self):
return "I am %s, I run at %d km/h" % (self.name, self.run_speed)
def __cmp__(self, other):
"""
Here we just use the __cmp__ function of the run_speed attribute.
This only works for Python2. Python3 removes the support for __cmp__,
and forces to implement __lt__, __le__, __gt__, __ge__ (<, <=, >, >=).
However in Python3, the total_ordering decorator helps you do that,
you can implement one of the above and __eq__ (==), then the rest
will be automatically implemented.
```
from functools import total_ordering
@total_ordering
class Runner(object):
...
```
"""
return self.run_speed.__cmp__(other.run_speed)
if __name__ == '__main__':
# First runner
sara = Runner(name='Sara', run_speed=20)
print sara
# Second runner
alex = Runner(name='Alex', run_speed=18)
print alex
# Testing run function
d = 10 # km
print "%s takes %.2f hours to run %dkm" % (sara.name, sara.run(d), d)
# Testing comparison functions
print 'alex < sara: ', alex < sara
print 'alex <= sara: ', alex <= sara
print 'alex == sara: ', alex == sara
print 'alex >= sara: ', alex >= sara
print 'alex > sara: ', alex > sara
# Playing
print '\nTraining time!'
sara.run_speed += 1
print sara
|
4e75a22edf32ec64b5ee86d8636d3ed45cc7db1b | vridecoder/Python_Projects | /Factorial/fact.py | 241 | 3.78125 | 4 | class Factorial:
def __init__(self, n):
self.num = n
self.fact = 1
def factorial(self):
for i in range(1, self.num+1):
self.fact= self.fact*i
print(self.fact)
__all__ = ['Factorial'] |
787af7e8416bee081cb332f9e72a7ffa65dd7426 | DidiMilikina/DataCamp | /Data Engineer with Python/03. Software Engineering for Data Scientists in Python/04. Maintainability/06. Refactoring for readability.py | 1,704 | 4.59375 | 5 | '''
Refactoring for readability
Refactoring longer functions into smaller units can help with both readability and modularity. In this exercise, you will refactor a function into smaller units. The function you will be refactoring is shown below. Note, in the exercise, you won't be using docstrings for the sake of space; in a real application, you should include documentation!
def polygon_area(n_sides, side_len):
"""Find the area of a regular polygon
:param n_sides: number of sides
:param side_len: length of polygon sides
:return: area of polygon
>>> round(polygon_area(4, 5))
25
"""
perimeter = n_sides * side_len
apothem_denominator = 2 * math.tan(math.pi / n_sides)
apothem = side_len / apothem_denominator
return perimeter * apothem / 2
Instructions
100 XP
Move the logic for calculating the perimeter into the polygon_perimeter function.
Complete the definition of the polygon_apothem function, by moving the logic seen in the context. The math module has already been imported for you.
Utilize the new unit functions to complete the definition of polygon_area.
Use the more unitized polygon_area to calculate the area of a regular hexagon with legs of size 10.
'''
SOLUTION
def polygon_perimeter(n_sides, side_len):
return n_sides * side_len
def polygon_apothem(n_sides, side_len):
denominator = 2 * math.tan(math.pi / n_sides)
return side_len / denominator
def polygon_area(n_sides, side_len):
perimeter = polygon_perimeter(n_sides, side_len)
apothem = polygon_apothem(n_sides, side_len)
return perimeter * apothem / 2
# Print the area of a hexagon with legs of size 10
print(polygon_area(n_sides=6, side_len=10)) |
d92f27e2609a7a94d43dc564616379ba0cc37eee | rajatgirotra/study | /interview/algorithms/sortings/merge_sort.py | 1,069 | 3.890625 | 4 | import os
import sys
def merge(arr, p, q, r):
left_arr = arr[p:q+1]
right_arr = arr[q+1:r+1]
left_index = 0
right_index = 0
for k in range(p, r+1):
if left_index >= len(left_arr):
arr[k] = right_arr[right_index]
right_index = right_index + 1
elif right_index >= len(right_arr):
arr[k] = left_arr[left_index]
left_index = left_index + 1
elif left_arr[left_index] <= right_arr[right_index]:
arr[k] = left_arr[left_index]
left_index = left_index + 1
else:
arr[k] = right_arr[right_index]
right_index = right_index + 1
def merge_sort(arr, p, r):
if p < r:
q = int((p+r)/2)
merge_sort(arr, p, q)
merge_sort(arr, q+1, r)
merge(arr, p, q, r)
if __name__ == "__main__":
# prepare input
#arr = [5, 2, 4, 7, 1, 3, 2, 6]
arr = [3, 41, 52, 26, 38, 57, 9, 49]
print('un-sorted array: {}'.format(arr))
merge_sort(arr, 0, len(arr)-1)
print('sorted array: {}'.format(arr))
|
616269df750b2a63b507921baf0c10347d995927 | evaldojr100/Python_Lista_4 | /15_temperatura_media.py | 836 | 4.1875 | 4 | '''Faça um programa que receba a temperatura média de cada mês do ano e armazene-as
em uma lista. Em seguida, calcule a média anual das temperaturas e mostre a média calculada
juntamente com todas as temperaturas acima da média anual, e em que mês elas ocorreram
(mostrar o mês por extenso: 1 – Janeiro, 2 – Fevereiro, . . . ).'''
meses=("Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro")
temp=[]
for i in range(12):
temp.append(float(input("Digite a media de temperatura de %s: "%(meses[i]))))
media_anual=sum(temp)/len(temp)
print("A media anual de temperatura é de :",media_anual)
print("Os meses que tivertam temperatura acima disso foram:\n")
for i in range(12):
if temp[i]>=media_anual:
print("Mes de",meses[i],"com media de",temp[i])
|
c86048ad1bafcb6014c34d0d9bf0eb2d900abfce | AlexisLeon/challanges | /pascal.py | 439 | 3.703125 | 4 | def triangle(n):
arr = [[1],[1,1]]
for i in range(1,n):
line = []
[line.extend([ arr[i][j] + arr[i][j+1] ]) for j in range(0,len(arr[i])-1)]
arr.append([1] + line + [1])
return arr
def diagonal(n, p):
return sum([x[p] for x in triangle(n) if p <= len(x)-1])
print( 'result: ', diagonal(20, 4), '20349' )
print( 'result: ', diagonal(20, 5), '54264' )
print( 'result: ', diagonal(20, 15), '20349' ) |
bc754ac190d328f48e9c039802dbd1192a378925 | limebell/GEOREUM | /tests/georeum/source/source.py | 202 | 3.609375 | 4 | def echo(a):
a = a+1
return a
def get_pow(a):
return a*a
def get_abs(a):
if a > 0:
return a
else:
return a*-1
def fun01(a, b):
return get_pow(a)+get_abs(b)
|
a2eda1df0d71afff6aab764bf6aeda7e3003f583 | iliankostadinov/hackerrank-python | /deque.py | 1,042 | 3.796875 | 4 | #!/usr/bin/env python3
from collections import deque
def pilingUp(q):
if len(d) > 1:
value = "Yes"
currentEl = 0
if d[0] > d[-1]:
currentEl = d[0]
d.popleft()
else:
currentEl = d[-1]
d.pop()
for _ in range(len(d) - 1):
if d[0] > d[-1] and d[0] <= currentEl:
d.popleft()
else:
if d[-1] <= currentEl:
d.pop()
else:
value = "No"
break
else:
value = "Yes"
return value
if __name__ == "__main__":
# number of testcases
t = int(input())
results = []
for _ in range(t):
d = deque()
# number of cubes
n = int(input())
# side lenght of each cube
row_of_cubes = map(int, input().split())
# put elements in deque
for e in row_of_cubes:
d.append(e)
results.append(pilingUp(d))
for i in results:
print(i)
|
17130f11792d59f869c82469aaf680c8883f7a3f | AdrianB1995/FunctionalBST | /pyBST.py | 5,485 | 4.25 | 4 | '''Provides basic operations for Binary Search Trees using
a tuple representation. In this representation, a BST is
either an empty tuple or a length-3 tuple consisting of a data value,
a BST called the left subtree and a BST called the right subtree
'''
def is_bintree(T):
if type(T) is not tuple:
return False
if T == ():
return True
if len(T) != 3:
return False
if is_bintree(T[1]) and is_bintree(T[2]):
return True
return False
def bst_min(T):
if T == ():
return None
if not T[1]:
return T[0]
return bst_min(T[1])
def bst_max(T):
if T == ():
return None
if not T[2]:
return T[0]
return bst_max(T[2])
def is_bst(T):
if not is_bintree(T):
return False
if T == ():
return True
if not is_bst(T[1]) or not is_bst(T[2]):
return False
if T[1] == () and T[2] == ():
return True
if T[2] == ():
return bst_max(T[1]) < T[0]
if T[1] == ():
return T[0] < bst_min(T[2])
return bst_max(T[1]) < T[0] < bst_min(T[2])
def bst_search(T,x):
if T == ():
return T
if T[0] == x:
return T
if x < T[0]:
return bst_search(T[1],x)
return bst_search(T[2],x)
def bst_insert(T,x):
if T == ():
return (x,(),())
elif x < T[0]:
return (T[0],bst_insert(T[1],x),T[2])
else:
return (T[0],T[1],bst_insert(T[2],x))
def delete_min(T):
if T == ():
return T
if not T[1]:
return T[2]
else:
return (T[0],delete_min(T[1]),T[2])
def bst_delete(T,x):
assert T, "deleting value not in tree"
if x < T[0]:
return (T[0],bst_delete(T[1],x),T[2])
elif x > T[0]:
return (T[0],T[1],bst_delete(T[2],x))
else:
# T[0] == x
if not T[1]:
return T[2]
elif not T[2]:
return T[1]
else:
return (bst_min(T[2]),T[1],delete_min(T[2]))
def print_bintree(T,indent=0):
if not T:
print('*')
return
else:
print(T[0])
print(' '*(indent + len(T[0])-1)+'---', end = '')
print_bintree(T[1],indent+3)
print(' '*(indent + len(T[0])-1)+'---', end = '')
print_bintree(T[2],indent+3)
def print_func_space(x):
print(x,end=' ')
def inorder(T,f):
if not is_bst(T):
return
if not T:
return
inorder(T[1],f)
f(T[0])
inorder(T[2],f)
# Programming project: provide implementations for the functions below,
# i.e., replace all the pass statements in the functions below.
# Then add tests for these functions in the block
# that starts "if __name__ == '__main__':"
def preorder(T,f):
if not is_bst(T):
return
if not T:
return
f(T[0])
preorder(T[1],f)
preorder(T[2],f)
def postorder(T,f):
if not is_bst(T):
return
if not T:
return
postorder(T[1],f)
postorder(T[2],f)
f(T[0])
def tree_height(T):
# Empty tree has height -1
if T == ():
return -1
if T[0] is not None and T[1] == () and T[2] == ():
return 0
return 1 + max(tree_height(T[1]), tree_height(T[2]))
def balance(T):
# returns the height of the left subtree of T
# minus the height of the right subtree of T
# i.e., the balance of the root of T
if T == ():
return 0
else:
return tree_height(T[1]) - tree_height(T[2])
def minBalance(T):
# returns the minimum value of balance(S) for all subtrees S of T
if not is_bst (T):
return 1
if not T:
return 0
if not T[1] and not T[2]:
return balance(T)
else:
return min(balance(T), minBalance(T[1]), minBalance(T[2]))
def maxBalance(T):
# returns the maximum value of balance(S) for all subtrees S of T
if not is_bst (T):
return 1
if not T:
return 0
if not T[1] and not T[2]:
return balance(T)
else:
return max(balance(T), maxBalance(T[1]), maxBalance(T[2]))
def is_avl(T):
# Returns True if T is an AVL tree, False otherwise
# Hint: use minBalance(T) and maxBalance(T)
if -1 <= maxBalance(T) <= 1 and -1 <= minBalance(T) <= 1:
return True
else:
return False
# Add tests for the above seven functions below
if __name__ == '__main__':
K = ()
for x in ['Joe','Bob', 'Phil', 'Paul', 'Marc', 'Jean', 'Jerry', 'Alice', 'Anne']:
K = bst_insert(K,x)
print('\nTree elements in sorted order\n')
inorder(K,print_func_space)
print()
print('\nPrint full tree\n')
print_bintree(K)
print("\nDelete Bob and print tree\n")
K = bst_delete(K,'Bob')
print_bintree(K)
print()
print("\nPrint subtree at 'Phil'\n")
print_bintree(bst_search(K,'Phil'))
print()
# TEST CODE FOR THE FUNCTIONS YOU IMPLEMENTED GOES BELOW:
print('\nTree elements in preorder sorted\n')
preorder(K,print_func_space)
print()
print('\nTree elements in postorder sorted\n')
postorder(K,print_func_space)
print()
print('\nTree height\n')
height = tree_height(K)
print(height)
print('\nTree Balance on root\n')
bal = balance(K)
print(bal)
print('\nMin Balance for all subtrees S of T\n')
minBal = minBalance(K)
print(minBal)
print('\nMax Balance for all subtrees S of T\n')
maxBal = maxBalance(K)
print(maxBal)
print('\nAVL TEST\n')
test = is_avl(K)
print(test)
|
189efc826835b39f57d8ef17693ac4f5c0b50fea | anyl92/ALGORITHM | /swea/4839_binarysearch.py | 776 | 3.671875 | 4 | import sys
sys.stdin = open('binarysearch_input.txt', 'r')
def binarysearch(n):
start = 1
end = len(pages)
count = 0
middle = (start + end) // 2
while middle != n:
count += 1
middle = (start + end) // 2
if pages[middle] == n:
return count
elif pages[middle] > n:
end = middle
elif pages[middle] < n:
start = middle
T = int(input())
for tc in range(1, T+1):
a = list(map(int, input().split()))
pages = [0] * a[0]
for i in range(a[0]):
pages[i] = i
if binarysearch(a[1]) < binarysearch(a[2]):
print('#%d %s' % (tc, 'A'))
elif binarysearch(a[1]) > binarysearch(a[2]):
print('#%d %s' % (tc, 'B'))
else:
print('#%d 0' % (tc)) |
06f7b06b9027b9b09134e14acd3f43d88f2eaeff | vhsw/Advent-of-Code | /2019/Day 15/oxygen_system.py | 3,657 | 3.6875 | 4 | """Day 15 Answers"""
from typing import Dict, NamedTuple
import networkx as nx
from intcode_v15 import Intcode
INPUT = "2019/Day 15/input"
class Point(NamedTuple):
"""2D Point"""
x: int
y: int
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
class Maze:
def __init__(self, robot: Intcode):
self.robot = robot
self.pos = Point(0, 0)
self.ship: Dict[Point, int] = {}
self.graph = nx.Graph()
self.graph.add_node(self.pos)
dpos = {
Point(-1, 0): 1,
Point(1, 0): 2,
Point(0, -1): 3,
Point(0, 1): 4,
}
self.dpos: Dict[Point, int] = dpos
self.rdpos: Dict[int, Point] = {v: k for k, v in dpos.items()}
def move(self, direction):
res = self.robot.evaluate(direction)
new_pos = self.pos + self.rdpos[direction]
assert new_pos not in self.ship
self.ship[new_pos] = res
if res > 0:
self.graph.add_edge(self.pos, new_pos)
self.pos = new_pos
self.ship[new_pos] = 2 + direction
return res
def search(self, pos: Point, state):
oxy = None
for direction in (1, 2, 3, 4):
new_pos = pos + self.rdpos[direction]
if new_pos in self.ship:
continue
self.pos = pos
self.robot = state.save_state()
result = self.move(direction)
if result == 2:
return self.pos
if result == 1:
if not oxy:
oxy = self.search(new_pos, self.robot.save_state())
return oxy
def findall(self, pos: Point, state):
for direction in (1, 2, 3, 4):
new_pos = pos + self.rdpos[direction]
if new_pos in self.ship:
continue
self.pos = pos
self.robot = state.save_state()
result = self.move(direction)
if result > 0:
self.findall(new_pos, self.robot.save_state())
def __str__(self):
minx = min((k.x for k in self.ship), default=0)
maxx = max((k.x for k in self.ship), default=0)
miny = min((k.y for k in self.ship), default=0)
maxy = max((k.y for k in self.ship), default=0)
result = []
for x in range(minx, maxx + 1):
line = []
for y in range(miny, maxy + 1):
tile = "#.O^v<> "[self.ship.get((x, y), 7)]
if (x, y) == (0, 0):
tile = "X"
if (x, y) == self.pos:
tile = "D"
line.append(tile)
result.append("".join(line))
return "\n".join(result)
def part1():
"""Part 1 answer"""
with open(INPUT) as data:
data = data.read().strip().split(",")
code = [int(d) for d in data]
robot = Intcode(code)
maze = Maze(robot)
oxy = maze.search(Point(0, 0), maze.robot.save_state())
return nx.shortest_path_length(maze.graph, Point(0, 0), oxy)
def part2():
"""Part 2 answer"""
with open(INPUT) as data:
data = data.read().strip().split(",")
code = [int(d) for d in data]
robot = Intcode(code)
maze = Maze(robot)
oxy = maze.search(Point(0, 0), maze.robot.save_state())
robot = Intcode(code)
maze = Maze(robot)
maze.findall(Point(0, 0), maze.robot.save_state())
return max(nx.single_source_shortest_path_length(maze.graph, oxy).values())
if __name__ == "__main__":
ANSWER1 = part1()
print(f"Part 1: {ANSWER1}")
ANSWER2 = part2()
print(f"Part 2: {ANSWER2}")
|
5167451f9c5f7c7c460b8f9f51df40a05f2fa8a9 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/be5baac8abe94e97b4982cac8fa966c3.py | 202 | 3.625 | 4 | def hey(s):
if s.isspace():
return "Fine. Be that way!"
if (s.upper() == s and s.upper() != s.lower()):
return 'Whoa, chill out!'
if (s[-1] == '?'):
return 'Sure.'
else:
return 'Whatever.'
|
17cb4c10939273784b4bc7e09d69d6c71f540eca | WenhaoChen0907/Python_Demo | /01_hellopython/hn_11_sum.py | 262 | 3.640625 | 4 | # 计算 0 ~ 100 之间所有数字的累计求和结果
result = 0 # 保存求和结果
i = 0 # 定义计数器
while i <= 100:
result += i # 求和
i += 1 # 处理计数器
print("0 ~ 100 之间所有数字的累计求和结果: %d " % result) |
cc574805d0fd6f33305e1ad6a6419c207ca46afb | regynald/Project-Euler-Solutions | /Python/020.py | 262 | 3.84375 | 4 | """
Project Euler Problem 20
========================
n! means n * (n - 1) * ... * 3 * 2 * 1
Find the sum of the digits in the number 100!
"""
import math
def run():
n = math.factorial(100)
sum = 0
for i in str(n):
sum += int(i)
return sum
print run() |
850d4d09bd68d64ae5cb1d3d80d9e42c60fb269d | gcavalcantes/100ProgrammingChallenges | /100PCpython/age_calculator/age_calc.py | 2,078 | 4.125 | 4 | '''
Program to calculate a person's age
by Gabriel Cavalcante
'''
from datetime import datetime
class Calc_age:
def calc_age():
print("===================================================")
print("Program to calculate a person's age or the year they were born.")
exit = False
while not exit:
# Offers the options finding out a person's age or the year they were born.
# Makes sure that the option is not in capital letters
opt: str = input(
"Would you like to find out a person's age (a) or the year they were born (b) ?\n").lower()
# If option 'a' is chosen
if opt == "a":
person_age = age()
print(
"This person is between {} and {} years of age.".format(person_age-1, person_age))
# If option 'b' is chosen
elif opt == "b":
born_year = year()
print("This person was born in {}n".format(born_year))
# If the input is incorrect
else:
print("Option unavailable.")
question: str = input(
"Would you like to continue to calculate someone's age? (y/n) \n").lower()
if question == "n" or question == "no":
exit = True
print("End of the program...\n===================================================")
# Function to calculate a person's age.
def age():
year_born: int = int(
input("What year was this person born in? \n"))
full_date = datetime.now()
year = int(full_date[0])
years_old = int(year - year_born)
return years_old
# Function to calculate the year of birth.
def year():
age = input(input("Whats the person's age? \n"))
full_date = datetime.now()
year = int(full_date[0])
born_in = int(year - int(age))
return born_in
# Calls the main function
calc_age()
# New instance of the Calc_age class
calculate_age = Calc_age()
calculate_age()
|
4430456aa1f2f3369338a6b5976fdc7170817495 | dmitrygost/python-base | /lesson-1/task4.py | 381 | 3.796875 | 4 | for n in range(0, 22):
num = n % 10
if n == 0:
print(n, 'процентов')
elif num == 0:
print(n, 'процентов')
elif n >= 11 and n <= 14:
print(n, 'процентов')
elif num == 1:
print(n, 'процент')
elif num >= 5:
print(n, 'процентов')
else:
print(n, 'процента')
|
78928c3fa5f0200737a04782390f46f3dadf6da2 | AvanthaDS/PyLearn_v_1_0 | /function.py | 1,322 | 4.1875 | 4 | __author__ = 'Avantha'
def avantha():
print('My first function - Multiply by 12')
def mcal(av):
amnt=av*12
return amnt # returns the answer to the equation when the function is called
#print(amnt)
avantha()
a_av = int(input('please enter the number you want to multiply by 12: '))
av_ans = mcal(a_av)
print('you entered:', a_av)
print('when multiplied by 12 the answer is:', av_ans)
# this is to show how the default values can be stored in a function
def mynum(ads='Unknown'):
if ads is 'Y':
ads = 'correct'
elif ads is 'N':
ads = 'Incorrect'
print(ads)
mynum('Y') # These lines will print the function with the defined value 'Y'
mynum('N') # These lines will print the function with the defined value 'Y'
mynum() # These lines will print the function when there is nothing defined in the function value
#--------------------------------
a = 20 # to access a variable by a function the variable has to be defined outside the function
def xl():
#a = 20 defining the variable here wont work
print(a)
# a = 20 defining the variable here will also work
def xy():
print(a)
xl()
xy()
#---------------------------------------------
def myfn(a=0,b=0,c=0):
out = a+b+c
return out
#print(out)
print('my functiona calculation is (a+b+c): ',myfn(2,3,5))
|
65741848f34ac57544e21f345eb9127283930e4e | deyuwang/pisio | /src/link.py | 758 | 3.578125 | 4 | import Tkinter
class Link(object):
""
def __init__(self, fromNode, toNode, text="", color="black", textColor="black", width=1):
self.fromNode = fromNode
self.toNode = toNode
self.text = text
self.color = color
self.textColor = textColor
def cx(self):
return (self.fromNode.cx() + self.toNode.cx()) / 2
def cy(self):
return (self.fromNode.cy() + self.toNode.cy()) / 2
def paint(self, g):
x1 = self.fromNode.cx()
y1 = self.fromNode.cy()
x2 = self.toNode.cx()
y2 = self.toNode.cy()
g.create_line(x1, y1, x2, y2, fill=self.color)
g.create_text(self.cx(), self.cy(), text=self.text, fill=self.textColor, anchor=Tkinter.CENTER)
|
d7e504811a1e05497b0198a944b5f8f49cfe7f5e | toladata-ce/IATI | /percentage_recipient_country.py | 1,126 | 3.5 | 4 | #This function allows to fill in the Recipient Country Percentage column in the csv file
#For one given activity, we must have the list of the distinct countries and their percentage
def percentage_recipient_country(countries,ID):
#get an array of #of rows for each activities
count_ID=[]
for i in range(len(ID)):
if(ID[i]!=''):
j=1
while(i+j<len(ID) and ID[i+j]==''):
j=j+1
count_ID.append(j)
#setting the countries and the percentage for each activity
k=0
percentage=[]
sorted_countries=[]
for count in count_ID:
tab = countries[k:k+count]
k=k+count
tab2=set(tab)
for c in tab2:
sorted_countries.append(c)
percent = 0
for c2 in tab:
if (c==c2):
percent=percent+1
percent = round(percent/count*100,2)
percentage.append(percent)
for i in range(count-len(tab2)):
sorted_countries.append('')
percentage.append('')
#k=k+count
return (sorted_countries,percentage)
|
a4667728ff41bc999f0ffcb8671ef3963b37d0fe | zhouf1234/untitled3 | /函数编程函数15LEGB.py | 1,005 | 4.40625 | 4 | #LEGB是Python中名字(变量)的查找顺序
#LEGB 代表名字查找顺序: locals -> enclosing function -> globals -> __builtins_
#locals 是函数内的名字空间,包括局部变量和形参 本作用域(名字空间)
#enclosing 外部嵌套函数的名字空间(闭包中常见) 上层作用域(名字空间)
#globals 全局变量,函数定义所在模块的名字空间 全局作用域(名字空间)
#builtins 内置模块的名字空间
name = '100'
age = 16
add = '上海'
def demo():
name = '200'
age = 20
int = 1
def fn():
name = '300'
print(name) #使用的是本作用域额变量:显示300
print(age) #上层作用域 :20
print(add) #全局作用域的变量1 :上海
print(int) #不给int赋值,也可的
fn()
demo()
print()
#列表去重
list = [1,2,3,4,5,62,3,2,1]
#print(list(set(list)))会报错,因为内层已经变set,所以外层不能list显示 |
c3fd5ac39accf39dc9fef868d2833499e9ae1b7b | messersm/sudokutools | /sudokutools/analyze.py | 3,865 | 3.78125 | 4 | """Rate and check sudokus.
Functions defined here:
* find_conflicts(): Check sudoku for conflicting fields.
* is_solved(): Check, if a sudoku is solved.
* is_unique(): Check if a sudoku has exactly one solution.
* rate(): Return an integer representation of the difficulty of a sudoku.
* score(): Return an integer representation of the work required to solve
a sudoku.
"""
from sudokutools.solve import dlx
from sudokutools.solvers import CalculateCandidates, \
NakedSingle, NakedPair, NakedTriple, NakedQuad, NakedQuint, \
HiddenSingle, HiddenPair, HiddenTriple, HiddenQuad, HiddenQuint, \
PointingPair, PointingTriple, \
XWing, Swordfish, Jellyfish, \
Bruteforce, \
solve
RATINGS = {
CalculateCandidates: 0,
NakedSingle: 1,
HiddenSingle: 1,
NakedPair: 2,
HiddenPair: 2,
NakedTriple: 2,
HiddenTriple: 2,
NakedQuad: 3,
HiddenQuad: 3,
NakedQuint: 3,
HiddenQuint: 3,
PointingPair: 4,
PointingTriple: 4,
XWing: 5,
Swordfish: 6,
Jellyfish: 7,
Bruteforce: 10
}
def rate(sudoku):
"""Rate the difficulty of a sudoku and return 0 <= rating <= 10.
Args:
sudoku (Sudoku): The sudoku to rate.
Returns:
(int): The rating (a value inclusive between 0 and 10).
Note:
Only completely solved sudokus get a rating of 0.
"""
steps = []
solve(sudoku, steps.append)
# max() raises a ValueError, if the list is empty.
try:
return max([RATINGS[step.__class__] for step in steps])
except ValueError:
return 0
def score(sudoku):
"""Return a score for the given sudoku.
The score depends on the number of empty field as well as
which solve methods must be used to solve the sudoku.
Args:
sudoku (Sudoku): The sudoku to score.
Returns:
(int): The score (a value between 0 and empty * 10,
where empty is the number of empty fields in the sudoku).
"""
steps = []
solve(sudoku, steps.append)
return sum([RATINGS[step.__class__] for step in steps])
def is_solved(sudoku):
"""Check, if the sudoku is solved.
Args:
sudoku (Sudoku): The :class:`Sudoku` instance to check.
Returns:
bool: Whether or not the sudoku is solved.
"""
return not list(sudoku.empty()) and not list(find_conflicts(sudoku))
def is_unique(sudoku):
"""Check if sudoku has exactly one solution.
Args:
sudoku (Sudoku): The :class:`Sudoku` instance to check.
Returns:
bool: Whether or not the sudoku is unique.
"""
solutions = dlx(sudoku)
# If we have no solutions return False.
try:
next(solutions)
except StopIteration:
return False
# If we have two (or more solutions return False
# otherwise return True.
try:
next(solutions)
return False
except StopIteration:
return True
def find_conflicts(sudoku, *coords):
"""Yield conflicts in sudoku at coords.
If coords is empty all possible coordinates will be searched.
Args:
sudoku (Sudoku): The :class:`Sudoku` instance to check.
coords (iterable of (int, int)): The coordinates to search within.
Yields:
((int, int), (int, int), int): tuple of coordinate pairs and the
offending value.
E.g.: ((2, 3), (2, 6), 2) indicates, that there is a conflict for
the fields (2, 3) and (2, 6) because both of them contain a 2.
"""
if not coords:
coords = list(sudoku)
for row, col in coords:
value = sudoku[row, col]
if not value:
continue
else:
for (i, j) in sudoku.surrounding_of(row, col, include=False):
if sudoku[i, j] == value:
yield ((row, col), (i, j), value) |
9106c4b8585655fa1694e847888b55e2bf6fe80b | XrossFox/nltk_tests | /Py4Engineer/0/test02.py | 1,077 | 3.609375 | 4 | import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.corpus import wordnet
"""Stopwords, son palabras que ofrecen poco o nulo valor, pero son muy comunes. Toman una gran parte
de la oracion, pero no agregan contexto o informacion. NLTK tiene una lista de stopwords para los principales lenguajes"""
"""Primeras 16 stopwords"""
#print(stopwords.words('english')[:16])
"""Oracion original"""
para = ("The program was open to all women between the ages of 17 and 35, in good health, " +
"who had graduated from an accredited high school. ")
words = word_tokenize(para)
#print(words)
"""Oracion sin stopwords"""
useful_words = [word for word in words if word not in stopwords.words("english")]
#print(useful_words)
"""Las 20 palabras mas comunes en el data set de movie reviews, de las cuales, la mayoria son stopwords"""
all_words = movie_reviews.words()
freq_dist = nltk.FreqDist(all_words)
print(freq_dist.most_common(20)) |
9e14ab009ef4f20ab8f3d987f5a81ee12bfa7b42 | CodeKul/Python-Dec-2018-CrashCourse | /Inheritance.py | 1,185 | 3.8125 | 4 | class Polygon:
sides = []
def __init__(self,n):
super().__init__()
self.n = n
def inputSides(self):
for n in range(self.n):
side = input("Enter {} side: ".format(n))
self.sides.append(side)
def displaySides(self):
for side in self.sides:
print(side)
# p = Polygon(5)
# p.inputSides()
# p.displaySides()
class Triangle(Polygon):
def __init__(self):
super().__init__(3)
# t = Triangle()
# t.inputSides()
# t.displaySides()
class Rectangle(Polygon):
def __init__(self):
super().__init__(4)
def inputSides(self):
length = input("Enter Length: ")
breadth = input("Enter Breadth: ")
for n in range(self.n):
if n % 2 == 0:
self.sides.append(length)
else:
self.sides.append(breadth)
# r = Rectangle()
# r.inputSides()
# r.displaySides()
class Square(Rectangle):
# def __init__(self):
# super().__init__()
def inputSides(self):
side = input("Enter side: ")
for n in range(self.n):
self.sides.append(side)
s = Square()
s.inputSides()
s.displaySides()
|
d90895ac92e2e10b648f389c1ef0ed5f174cce3d | luislama/algoritmos_y_estructuras_de_datos | /algoritmos/24_jose_javier_villena_sort/jose_javier_villena_sort.py | 1,759 | 3.65625 | 4 | '''
24_jose_javier_villena_sort
Recorrer el arreglo buscando las posiciones de los numeros mayor y menor
Al finalizar cada iteracion colocar los numeros al principio y al final, intercambiando los numeros
Luego de cada vuelta, las posiciones a recorrer disminuyen en 2, puesto que los extremos ya han sido examinados
[2,7,1,5,0,4,3,8,-1,2,4]
r1: [-1,7,1,5,0,4,3,4,2,2,8]
r2: [-1,0,1,5,2,4,3,4,2,7,8]
r3: [-1,0,1,2,2,4,3,4,5,7,8]
r4: [-1,0,1,2,2,4,3,4,5,7,8]
r5: [-1,0,1,2,2,3,4,4,5,7,8]
'''
elements = [2,7,1,5,0,4,3,8,-1,2,4]
num_elements = len(elements)
def jose_javier_villena_sort(arreglo):
ordered = False
result = arreglo
ronda = 1
i = 0
j = len(result) - 1
while i < j - 1:
min = i
max = j
for k in range(i, j):
if result[k] < result[min]:
min = k
if result[k] > result[max]:
max = k
if min != i or max != j:
if min == j and max == i:
result[i], result[j] = result[j], result[i]
elif max == i and min != j:
result[i], result[min], result[j] = result[min], result[j], result[i]
elif max != i and min == j:
result[i], result[max], result[j] = result[j], result[i], result[max]
elif max != i and min != j:
result[i], result[min], result[j], result[max] = result[min], result[i], result[max], result[j]
else:
pass
print("".join(["ronda ", str(ronda), ":"]))
print(result)
print('\n')
i += 1
j -= 1
ronda += 1
print("arreglo: ")
print(elements)
print("\n")
ordered_elements = jose_javier_villena_sort(elements) |
3ceee6b801ba0f690094d025137a90baaec1b029 | DenBlacky808/Algo | /Lesson_1/Task_6.py | 131 | 3.5 | 4 | print('Введите номер буквы в алфавите ')
n = int(input('n = '))
n = n + 96
char_1 = chr(n)
print(char_1)
|
88d613585fcf483c124dcbac9d41e9d540f85c55 | czs108/LeetCode-Solutions | /Medium/151. Reverse Words in a String/solution (2).py | 975 | 3.8125 | 4 | # 151. Reverse Words in a String
# Runtime: 40 ms, faster than 55.52% of Python3 online submissions for Reverse Words in a String.
# Memory Usage: 14.3 MB, less than 67.77% of Python3 online submissions for Reverse Words in a String.
from collections import deque
class Solution:
# Deque of Words
def reverseWords(self, s: str) -> str:
left, right = 0, len(s) - 1
# Remove leading spaces.
while left <= right and s[left] == " ":
left += 1
# Remove trailing spaces.
while left <= right and s[right] == " ":
right -= 1
deq, word = deque(), []
# Push word by word in front of deque.
while left <= right:
if s[left] == " " and word:
deq.appendleft("".join(word))
word = []
elif s[left] != " ":
word.append(s[left])
left += 1
deq.appendleft("".join(word))
return " ".join(deq) |
f9da4cd7e82accc93fa614d1299ff7476fdb5267 | t-suzuki/cubic_eigen_test | /cubic_eigen.py | 4,063 | 3.8125 | 4 | #!env python
# https://en.wikipedia.org/wiki/Eigenvalue_algorithm
# https://en.wikipedia.org/wiki/Cubic_function#Roots_of_a_cubic_function
# https://en.wikipedia.org/wiki/Eigenvalue_algorithm
import matplotlib.pyplot as plt
import numpy as np
def cubic_eigen(m):
# det(x I - m) = 0
# <=> x**3 - x**2 * tr(m) - x/2*(tr(m**2) - tr(m)**2) - det(m) = 0
# <=> x**3 + a x**2 + b x + c = 0
a = -np.trace(m)
b = -0.5*(np.trace(np.dot(m, m)) - a*a)
c = -np.linalg.det(m)
# f(x) = x**3 + a x**2 + b x + c
def f(x): return x**3 + a*x**2 + b*x + c
# f'(x) = 3x**2 + 2ax + b
def fprime(x): return 3*x**2 + 2*a*x + b
# f'(x) = 0
p = (-a + np.sqrt(a*a - 3*b))/3.0
q = (-a - np.sqrt(a*a - 3*b))/3.0
# starting point for Newton's method
r, s, t = p + (p - q), (p + q)/2, q - (p - q)
def newton(x, n=4):
for i in range(n):
x = x - f(x)/fprime(x)
return x
# climb to the root.
x_rst = map(newton, (r, s, t))
f_rst = map(f, x_rst)
print f_rst
# plot
fig, axs = plt.subplots(1, 1)
xs = np.linspace(-10, 10, 100)
axs.plot(xs, f(xs))
axs.plot(x_rst, f_rst, 'o', color='yellow')
axs.axhline(y=0)
axs.axvline(x=p, color='red')
axs.axvline(x=q, color='red')
axs.axvline(x=r, color='green')
axs.axvline(x=s, color='green')
axs.axvline(x=t, color='green')
axs.set_ylim(sorted(map(lambda x: f(x)*2, [p, q])))
return sorted(x_rst)
def cubic_eigen_2phase(m):
a = -np.trace(m)
b = -0.5*(np.trace(np.dot(m, m)) - a*a)
c = -np.linalg.det(m)
# f(x) = x**3 + a x**2 + b x + c
def f(x): return x**3 + a*x**2 + b*x + c
# f'(x) = 3x**2 + 2ax + b
def fprime(x): return 3*x**2 + 2*a*x + b
# find two local minima/maxima by f'(x) = 0. let the solutions be p < q.
# note that f(q) <= 0 <= f(p).
p = (-a - np.sqrt(a*a - 3*b))/3.0
q = (-a + np.sqrt(a*a - 3*b))/3.0
# one "good" root of f(x) = 0 can be found at left(right) of p(q) if q(p) is near the multiple root, respectively.
# q is near the multiple root
# ~ f(p) > -f(q)
# <=> f((p + q)/2) > 0
# <=> f(-a/3) > 0
# then, first solve f(x) = 0 using Newton's method at left.
# starting point: the opposite side of multiple root.
if f(-a/3) > 0:
start = p + (p - q)
print 'left', f(p), f(q)
else:
start = q - (p - q)
print 'right', f(p), f(q)
def newton(x, n=4):
for i in range(n):
x = x - f(x)/fprime(x)
return x
# climb to the "good" root.
x_hat = newton(start)
# let the root be x_hat and factorize f(x).
# f(x) = (x - x_hat)(x**2 + alpha*x + beta)
# a = alpha - x_hat, b = beta - alpha*x_hat, c = -beta*x_hat.
# => alpha = a + x_hat, beta = b + a*x_hat + x_hat**2
alpha = a + x_hat
beta = b + alpha*x_hat
# solve g(x) = x**2 + alpha*x + beta = 0
# root r, s (r < s)
r = (-alpha - np.sqrt(alpha**2 - 4*beta))/2.0
s = (-alpha + np.sqrt(alpha**2 - 4*beta))/2.0
t = x_hat
# t can be either side! r <= s <= t or t <= r <= s
x_rst = [r, s, t]
f_rst = map(f, x_rst)
print f_rst
# plot
fig, axs = plt.subplots(1, 1)
xs = np.linspace(-10, 10, 100)
axs.plot(xs, f(xs))
axs.plot([r, s], map(f, [r, s]), 'o', color='yellow')
axs.plot([t], [f(t)], 'o', color='red')
axs.axhline(y=0)
axs.axvline(x=p, color='red')
axs.axvline(x=q, color='red')
axs.axvline(x=start, color='green')
axs.set_ylim(sorted(map(lambda x: f(x)*2, [p, q])))
return sorted(x_rst)
def cubic_eigen_ref(m):
a, b = np.linalg.eigh(m)
return sorted(a)
if __name__=='__main__':
A = np.random.randn(3, 3)
A = A + A.T # symmetrize
print A
e_ref = cubic_eigen_ref(A)
e_my = cubic_eigen(A)
e_my2 = cubic_eigen_2phase(A)
print 'ref', e_ref
print 'my', e_my
print 'my2', e_my2
print 'diff', np.abs(np.array(e_ref) - np.array(e_my))
print 'diff2', np.abs(np.array(e_ref) - np.array(e_my2))
plt.show()
|
97359cd4e3741a12a40c443d4a99cd5e2edfc3ab | google-code/a398t672-cs580-sp2015-svn | /test1(2)practise.py | 227 | 3.609375 | 4 | import string
def main():
inuser = input("Enter a string:")
message = ""
for b in inuser:
message = b + message
print(message)
//addind this just to be able to create a conflict
main()
|
8bf36162eca279f2ed3d0cfbc66a19cc12a2b39c | guozhaoxin/leetcode | /num101_200/num151_160/num160.py | 1,986 | 4 | 4 | #encoding:utf8
__author__ = 'gold'
'''
Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
aL = 0 #a链表的长度
bL = 0 #b链表的长度
nodeA = headA
while nodeA:
aL += 1
nodeA = nodeA.next
if not aL:
return None
nodeB = headB
while nodeB:
bL += 1
nodeB = nodeB.next
if not bL:
return None
nodeA = headA
nodeB = headB
stepDiff = abs(bL - aL)
if aL > bL:
culStep = 0
while culStep != stepDiff:
culStep += 1
nodeA = nodeA.next
elif bL > aL:
culStep = 0
while culStep != stepDiff:
culStep += 1
nodeB = nodeB.next
while nodeB != nodeA:
nodeA = nodeA.next
nodeB = nodeB.next
if not nodeA or not nodeB:
return None
return nodeB |
2d660f284a94b1f1b2f843ef5de96356b4ea4062 | nithinprasad94/Coding-Problems | /2 Linked Lists/3_delete_middle_node.py | 2,189 | 4.1875 | 4 | #Author: Nithin Prasad
#Date Created: 30/09/2019
#Program Name: delete_middle_node.py
#Program Description: this program allows one to delete A middle node in a
# linked list, given ONLY that deletable node!
class LL_Node:
val = None
nxt = None
def __init__(self,input_val, next_node):
self.val = input_val
self.nxt = next_node
def create_LL(inp_list):
if inp_list == None:
return None
len_list = len(inp_list)
if len_list == 0:
return None
head = LL_Node(inp_list[0],None)
curr = head
if len_list > 0:
for i in range(1,len_list):
new_node = LL_Node(inp_list[i],None)
curr.nxt = new_node
curr = new_node
return head
def print_LL(head):
if (head == None):
print("<Empty Linked List>")
return
curr = head
str_LL = ""
while curr != None:
str_LL += str(curr.val)
if curr.nxt != None:
str_LL += " -> "
curr = curr.nxt
print(str_LL)
return
#NOTE: O(1) time and space complexity!
def delete_middle_node(del_node):
if del_node == None:
return
#if not the last node in the list ..... (list of length 1 OR
# of length 2 with this as the second node)
if del_node.nxt != None:
del_node.val = del_node.nxt.val
del_node.nxt = del_node.nxt.nxt
return
def delete_middle_node_test(func):
print("Testing function: ", func.__name__)
head = create_LL(None)
print_LL(head)
func(head)
print_LL(head) #None
head = create_LL([1])
print_LL(head)
func(head)
print_LL(head) #[1] (unchanged)
head = create_LL([1,2])
print_LL(head)
func(head.nxt)
print_LL(head) #[1,2] (unchanged)
head = create_LL([1,2,3,4,5])
print_LL(head)
func(head.nxt.nxt)
print_LL(head) #[1,2,4,5]
head = create_LL([1,2,3,4,5,6])
print_LL(head)
func(head.nxt.nxt.nxt)
print_LL(head) #[1,2,3,5,6]
if __name__ == "__main__":
delete_middle_node_test(delete_middle_node)
|
605b37d888ffd97c3a83be52271822e7ac0f02ab | meena5/Python_training | /python_classes.py | 1,787 | 4.34375 | 4 | # A Sample class with init method
class sample:
# init method or constructor
def __init__(self, var):
self.var = var
# Sample Method
def print(self):
print('variable value is', self.var)
s = sample(100)
s.print()
#class method
'''Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called.
Because the class method only has access to this cls argument, it can’t modify object instance state.
That would require access to self. However, class methods can still modify class state that applies across all instances of the class.'''
#Instance method
'''Through the self parameter, instance methods can freely access attributes and other methods on the same object.
This gives them a lot of power when it comes to modifying an object’s state.
Not only can they modify object state, instance methods can also access the class itself through the self.__class__ attribute.
This means instance methods can also modify class state.'''
#Static method
'''This type of method takes neither a self nor a cls parameter (but of course it’s free to accept an arbitrary number of other parameters).
Therefore a static method can neither modify object state nor class state.
Static methods are restricted in what data they can access - and they’re primarily a way to namespace your methods.'''
class MyClass:
def method(self):
return 'instance method called', self
@classmethod
def classmethod(cls):
return 'class method called', cls
@staticmethod
def staticmethod():
return 'static method called'
a=MyClass()
print(a.classmethod())
print(a.staticmethod())
print(a.method())#instance method
|
f6dd5c7d63fee6092acec6b0f0b154f2f4676512 | djuanbei/AutoInput | /python/randvalue.py | 1,281 | 3.90625 | 4 | # -*- coding: utf-8 -*-
import random
from random import randint
import string
class RandChar(object):
def __init__(self, a=-1, b=-1):
self.low=a
self.high=b
def nextElem(self):
if type(self.low) ==type(1) and self.low==-1: # all char
return str(random.randint(string.ascii_letters))
if type(self.low) ==type(1) and self.low==-2: # all lower char
return str(random.randint(string.ascii_lowercase))
if type(self.low) ==type(1) and self.low==-3: # all upper char
return str(random.randint(string.ascii_uppercase))
if type(self.high) ==type(1) and self.high==-1: # one char in set
return str(random.choice(self.low))
else:
return str(chr(random.randint(ord(self.low), ord(self.high))))
def __str__(self):
return self.nextElem()+""
class RandInt(object):
def __init__(self, a=0, b=0):
self.low=a
self.high=b
def nextElem(self):
if self.low==0 and self.high==0:
return random.randint(0,200)
elif self.low> self.high:
return random.randint(-200,0)
else:
return random.randint(self.low, self.high)
def __str__(self):
return self.nextElem()+""
|
b6cde917a7c9cd53a7ceb9a80eaf6f8acba6e71f | bazenkov/multitransmitter-RL | /Neuron_modul.py | 5,502 | 3.5625 | 4 | import numpy as np
def get_burst_limits(activation_sequence, time):
"""Finds time limits of each burst.
Iterates through every neighboring pair of elements in binary activation sequence of a neuron and finds the time
of each activity change (from 1 to 0 and inverse).
:param list activation_sequence: Binary sequence of activation function values of a neuron.
:param list time: Sequence of float numbers defining the time of an event occurrence.
:return: List of two-element lists where the first and the second elements are the the onset and
the offset times of the burst respectively.
:rtype: list
"""
burst_limits = []
for i, (preceding, sequent) in enumerate(zip(activation_sequence[:-1], activation_sequence[1:])):
if (preceding == 0 and sequent == 1) or (i == 0 and preceding == 1):
burst_limits.append([time[i + 1]])
elif preceding == 1 and sequent == 0:
burst_limits[-1].append(time[i + 1])
if burst_limits and len(burst_limits[-1]) == 1:
burst_limits[-1].append(time[-1])
return burst_limits
class Neuron:
def __init__(self, values):
keys = (
'name', 'u_th', 'u_max', 'u_0', 'u_min', 'u_reb',
'v_00', 'v_01', 'v_10', 'v_11', 'v_reb', 'u', 'd',
'wv', 'wwv', 'wd')
self.__dict__.update(zip(keys, values))
self.u_rate_end = 0
def update_wv(self, ecs):
new_wv = []
for wv in self.wv:
new_wv.append(wv + np.sum(np.array(self.wwv) * ecs[0].cons))
return np.array(new_wv)
def update_d(self, ecs):
new_d = []
for d in self.d:
new_d.append(d + np.sum(np.array(self.wd) * ecs[0].cons))
return np.array(new_d) * self.update_activation()
def u_rate(self, ecs, time, potentials):
impact = np.sum(self.update_wv(ecs) * ecs[0].cons)
u_rate_reb = 0
if self.v_01 >= 0:
if abs(self.u - self.u_0) < 5e-06 and potentials[-2] >= self.u_0:
self.u_rate_end = self.v_01
elif abs(self.u - self.u_th) < 5e-06 and potentials[-2] < self.u_th - 5e-06 and self.u >= self.u_th:
self.u_rate_end = self.v_11
elif abs(self.u - self.u_max) < 5e-06 and potentials[-2] >= self.u_th - 5e-06:
self.u_rate_end = self.v_10
elif potentials[-2] >= self.u_th - 5e-06 and self.u_0 + 5e-06 < self.u < self.u_th:
self.u_rate_end = self.v_00
elif self.v_01 < 0:
if abs(self.u - self.u_0) < 5e-06:
if impact == 0:
self.u_rate_end = 0
elif impact > 0:
self.u_rate_end = self.v_01
elif impact < 0:
self.u_rate_end = (-1) * self.v_01
elif self.u_0 - self.u > 5e-06:
self.u_rate_end = (-1) * self.v_01
elif self.u - self.u_0 > 5e-06 > potentials[-2] - self.u_0:
self.u_rate_end = self.v_01
elif abs(self.u - self.u_th) < 5e-06 and potentials[-2] < self.u_th - 5e-06 and self.u >= self.u_th:
self.u_rate_end = self.v_11
elif abs(self.u - self.u_max) < 5e-06 and potentials[-2] >= self.u_th - 5e-06:
self.u_rate_end = self.v_10
elif potentials[-2] >= self.u_th - 5e-06 and self.u_0 + 5e-06 < self.u < self.u_th:
self.u_rate_end = self.v_00
if abs(self.u - self.u_reb) < 5e-06:
u_rate_reb = self.v_reb
elif abs(self.u - self.u_th) < 5e-06 and u_rate_reb == self.v_reb:
u_rate_reb = 0
if time[-1] == 0:
u_rate_reb = 0
self.v = impact + self.u_rate_end + u_rate_reb
return impact + self.u_rate_end + u_rate_reb
def residual_time(self, u_rate):
residual_time = 9999
if self.v_01 < 0 and self.v_10 < 0 and self.u < self.u_0 - 5e-06 and u_rate > 0:
residual_time = (self.u_0 - self.u) / u_rate
elif self.u_max >= self.u > (self.u_th + 5e-06) and u_rate < 0:
residual_time = -(self.u - self.u_th + (2e-06)) / u_rate
elif (self.u_max - 5e-06) > self.u >= self.u_th and u_rate > 0:
residual_time = (self.u_max - self.u) / u_rate
elif (self.u_0 + 5e-06 < self.u <= self.u_th) and u_rate < 0:
residual_time = -(self.u - self.u_0) / u_rate
elif self.u < self.u_th - 5e-06 and u_rate > 0:
residual_time = (self.u_th - self.u) / u_rate
elif self.u_reb >= self.u_min and (self.u_reb < self.u < self.u_th) and u_rate < 0:
residual_time = -(self.u - self.u_reb) / u_rate
return residual_time
def update_potential(self, time, u_rate, u_last):
flag = 0
zero_time = 0
if zero_time == 0 and flag == 'u_max':
self.u = self.u_max
elif zero_time == 0 and flag == 'u_min':
self.u = self.u_0
else:
self.u = u_last + (time[-1] - time[-2]) * u_rate
if self.u > self.u_max:
self.u = self.u_max
elif self.u < self.u_min:
self.u = self.u_min
if abs(self.u - self.u_th) < 5e-07:
self.u = self.u_th
if abs(self.u - self.u_reb) < 5e-07:
self.u = self.u_reb
return self.u
def update_activation(self):
return int(self.u > self.u_th or self.u == self.u_th and self.v > 0)
|
863525265bfefe9fa1353f0a6cf7491289d584c7 | YuliiaShalobodynskaPXL/IT_essentials | /uHasselt/21.09.18zelfstudy/2.7.py | 151 | 3.671875 | 4 | print("enter X")
x = str(input())
for i in range(11):
lengt_max = len(10*x)
l = lenght_max - len(i)
print(x, " times ", i, " = ",""*l, i*x) |
be5c6e4ebcfddbdf19777c0d8c4391be497d1978 | sashakrasnov/datacamp | /28-machine-learning-for-time-series-data-in-python/4-validating-and-inspecting-time-series-models/08-bootstrapping-a-confidence-interval.py | 1,556 | 4.375 | 4 | '''
Bootstrapping a confidence interval
A useful tool for assessing the variability of some data is the bootstrap. In this exercise, you'll write your own bootstrapping function that can be used to return a bootstrapped confidence interval.
This function takes three parameters: a 2-D array of numbers (data), a list of percentiles to calculate (percentiles), and the number of boostrap iterations to use (n_boots). It uses the resample function to generate a bootstrap sample, and then repeats this many times to calculate the confidence interval.
'''
import numpy as np
'''
INSTRUCTIONS
* The function should loop over the number of bootstraps (given by the parameter n_boots) and:
* Take a random sample of the data, with replacement, and calculate the mean of this random sample
* Compute the percentiles of bootstrap_means and return it
'''
from sklearn.utils import resample
def bootstrap_interval(data, percentiles=(2.5, 97.5), n_boots=100):
'''Bootstrap a confidence interval for the mean of columns of a 2-D dataset.
'''
# Create our empty array to fill the results
bootstrap_means = np.zeros([n_boots, data.shape[-1]])
for ii in range(n_boots):
# Generate random indices for our data *with* replacement, then take the sample mean
random_sample = resample(data)
bootstrap_means[ii] = random_sample.mean(axis=0)
# Compute the percentiles of choice for the bootstrapped means
percentiles = np.percentile(bootstrap_means, percentiles, axis=0)
return percentiles |
7ae420f61e005fb9bbaf88fde64b6c8afc62f562 | Nedlloyd1990/Assignments_ML | /multiplicationTable- Assignment1.py | 188 | 3.78125 | 4 | count=20
def multiplicationTable(x):
value=x
for i in range(0 , count+1):
print('2 x {}= {}'.format(i, (x*i)))
multiplicationTable(4) # enter the value here |
57c5f37cd37c18c493ff6f8f41a4506044d59677 | AbuAbir/Python_Task | /task_5.py | 2,900 | 4.15625 | 4 | # TASK FIVE: HIGHER ORDER FUNCTIONS, GENERATORS, LIST COMPREHENSION AND DECORATOR
# 1.
# Write a program to Python find the values which is not divisible 3 but is should be a multiple of 7.
# Make sure to use only higher order function.
numbers = filter(lambda x: x%3 != 0 and x%7 == 0, range(10000))
print(next(numbers))
# 2.
# Write a program in Python to multiply the element of list by itself using a traditional function
# and pass the function to map to complete the operation.
def multiply(x):
return x*x
result = map(multiply, range(1,10))
print(next(result))
# 3.
# Write a program to Python find out the character in a string which is uppercase using list comprehension.
string="abUaBiR"
print([i for i in string if i.isupper() is True])
# 4.
# Write a program to construct a dictionary from the two lists containing the names of students and their
# corresponding subjects. The dictionary should maps the students with their respective subjects.
# Let’s see how to do this using for loops and dictionary comprehension. HINT-Use Zip function also
# Student = ['Smit', 'Jaya', 'Rayyan']
# Capital = ['CSE', 'Networking', 'Operating System']
print({name:subject for name, subject in zip(Student, Capital)})
# 5.
# Learn More about Yield, next and Generators
# Learned
# 6.
# Write a program in Python using generators to reverse the string. Input String = “Consultadd Training”
def gen(n):
for i in n:
yield i
res = gen('Consultadd Training')
reverse=""
while True:
try:
reverse = next(res) + reverse
except StopIteration:
break
print(reverse)
# 7.
# Write any example on decorators.
# The following example would modify the functionality if divisor is a zero
def checkIfZero(original_func):
def inside(a,b):
if b == 0:
print("can't divide by zero")
exit()
return original_func(a,b)
return inside
@checkIfZero
def division(a,b):
return a/b
print(division(2,3))
print(division(2,0))
# 8.
# Learn about What is FRONT END and its Technologies and Tools
# Make sure to mention at least 5 top notch technologies of Frontend.
# Also mention the name of companies using those 5 technologies individually
React.js - Airbnb, Dropbox, BBC, Facebook, New York Times, and Reddit are some of the prominent
websites and web apps built with React.
Angular.js - Netflix, Upwork, IBM, Goodfilms, and Freelancer are some of the renowned websites built with Angular. Gmail, Paypal, and The Guardian
are some of the well-known applications built with Angular.
Vue.js - 9gag, Nintendo, GitLab, Behance, and Laravel
Flutter - Google ads, Alibaba, Birch Finance, Cryptograph, and Hookle are
some of the applications powered by Flutter.
Ionic - National Health Service, GE Transportation, Market Watch,
and Amtrak are some of the examples of business built on Ionic.
|
1e3a564230ea5ff0c9413c227cce24297d5595ff | bobo137950263/pythoncode | /汉诺塔.py | 391 | 3.5 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
def MoveHannuo(n,A,B,C):
source = A
destination = C
if n == 1:
pass
print("from %s to %s"%(source,destination))
else:
MoveHannuo(n-1,A,C,B)
MoveHannuo(1,A,B,C)
MoveHannuo(n-1,B,A,C)
A="A"
B="B"
C="C"
# MoveHannuo(1,A,B,C)
# MoveHannuo(2,A,B,C)
# MoveHannuo(3,A,B,C)
MoveHannuo(4,A,B,C)
|
de805f12e0930431b57ad8b35c4e956ed3c914bc | x4Cx58x54/rubik-image | /svg.py | 2,867 | 3.578125 | 4 | """
Generates SVG patterns.
@author Li Xiao-Tian
"""
def str_round3(x):
'''
Round x to at most 3 decimal places and convert to string.
'''
if isinstance(x, float):
if abs(round(x, 0)-x) < 0.001:
y = str(int(x))
elif abs(round(x, 1)-x) < 0.001:
y = '%.1f'%x
elif abs(round(x, 2)-x) < 0.001:
y = '%.2f'%x
else:
y = '%.3f'%x
else:
y = str(x)
return y
def element(elem, **kwargs):
"""
Generates SVG text.
<*elem* *key*="*value*"/>
'rotate' and 'd' parameters are specially treated.
"""
svg_str = '\n<' + elem
for key, value in kwargs.items():
if key == 'd':
pathd = ' d="'
for i in value:
pathd += str_round3(i) + ' '
svg_str += pathd.rstrip() + '"'
elif key == 'rotate':
if isinstance(value, int):
angle = str_round3(value)
rotate_x = '285' # opll_common.VIEWBOX_SIZE / 2
rotate_y = '285'
elif isinstance(value, tuple):
if len(value) == 3: # for rotations specifying centres
angle = str_round3(value[0])
rotate_x = str_round3(value[1])
rotate_y = str_round3(value[2])
elif len(value) % 3 == 0: # for multiple rotations
svg_str += ' transform="'
for j in range(len(value)//3):
angle = str_round3(value[3*j])
rotate_x = str_round3(value[3*j+1])
rotate_y = str_round3(value[3*j+2])
if angle not in ('-360', '0', '360'):
svg_str += 'rotate(%s,%s,%s)'%(angle, rotate_x, rotate_y)
svg_str += '"'
continue
else:
raise Exception('Rotate tuple length error!')
else:
raise Exception('Rotate arguments type error!')
if angle not in ('-360', '0', '360'):
svg_str += ' transform="rotate(%s,%s,%s)"'%(angle, rotate_x, rotate_y)
else:
svg_str += ' %s="%s"'%(key.replace('_', '-'), str_round3(value))
svg_str += '/>'
return svg_str
def head(width, height, viewBoxWidth, viewBoxHeight):
head_str = """<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="%dpx" height="%dpx" viewBox="0 0 %d %d" preserveAspectRatio="xMidYMid meet">
<metadata> Created by Rubik Image Generator, written by Li Xiao-Tian. </metadata>
"""
return head_str%(width, height, viewBoxWidth, viewBoxHeight)
TAIL = '\n</svg>' |
fe103a16101a059189cd2754cf7f564ef25c7867 | Aly622/Python | /test2.py | 893 | 4.125 | 4 | 向量化运算
#生成一个整数的等差序列,局限:只能用于遍历
r1_10 = range(1,10,2)
for i in r1_10:
print(i)
r1_10 = range(0.1,10,2)
#生成一个小数的等差序列
import numpy
numpy.arange(0.1,0.5,0.01)
r = numpy.arange(0.1, 0.5 ,0.01)
r
#向量化计算,四则运算
r+r
r-r
r*r
r/r
#函数式的向量化计算
numpy.power(r,5)
#向量化运算,比较运算
r>0.3
#结合过滤进行使用
r[r>0.3]
#矩阵运算
numpy.dot(r, r.T)
sum(r*r)
from pandas import DataFrame
df = DataFrame({
'column1':numpy.random.randn(5),
'column2':numpy.random.randn(5)})
df
#一列一列比
df.apply(min, axis=0)
#一行一行比
df.apply(min, axis=1)
#判断每个列,值是否都大于0
df.apply(
lambda x : numpy.all(x>0),
axis = 1
)
#结合过滤
df[df.apply(
lambda x : numpy.all(x>0),
axis=1
)] |
655b66d08764a4242da4c16255828d2c4f7cc419 | TKdevlop/python- | /rangesfun.pyw | 319 | 3.515625 | 4 | lis=[5,20,5,4,100]
def div5(x):
if x%5==0:
return True
else:
return False
xyz=(i for i in lis if div5(i))# use same logic as down in one line
#xyz=[]
#for i in lis:
# if div5(i):
# xyz.append(i)
for i in xyz:
print(i)
[print(e) for e in range(5)]
|
c6a9d92b4b01763d62b73d07bf73c208a4a4d5df | FalsePsyche/Uni_pythonprog | /Homework02/recomend.py | 6,858 | 3.671875 | 4 | """A Yelp-powered Restaurant Recommendation Program"""
from abstractions import *
#from data import ALL_RESTAURANTS, CATEGORIES, USER_FILES, load_user_file
from utils import distance, mean, zip, enumerate, sample, key_of_min_value
##################################
# Phase 2: Unsupervised Learning #
##################################
def find_closest(location, centroids):
"""Return the centroid in centroids that is closest to location. If
multiple centroids are equally close, return the first one.
>>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
[2.0, 3.0]
"""
# BEGIN Question 3
closest = min(centroids, key=lambda x: distance(location, x)) # get smallest distance from location in x of centroids
return closest
# END Question 3
def group_by_first(pairs):
"""Return a list of pairs that relates each unique key in the [key, value]
pairs to a list of all values that appear paired with that key.
this documentation should state why this should normally be used; what should this func normally be used for?
Arguments:
pairs -- a sequence of pairs
>>> example = [ [1, 2], [3, 2], [2, 4], [1, 3], [3, 1], [1, 2] ]
>>> group_by_first(example)
[[2, 3, 2], [2, 1], [4]]
"""
keys = []
for key, _ in pairs:
if key not in keys:
keys.append(key)
return [[y for x, y in pairs if x == key] for key in keys]
def group_by_centroid(restaurants, centroids):
"""Return a list of clusters, where each cluster contains all restaurants
nearest to a corresponding centroid in centroids. Each item in
restaurants should appear once in the result, along with the other
restaurants closest to the same centroid.
>>> r1 = make_restaurant('A', [-10, 2], [], 2, [make_review('A', 4), ])
>>> r2 = make_restaurant('B', [-9, 1], [], 3, [make_review('B', 5), make_review('B', 3.5), ])
>>> r3 = make_restaurant('C', [4, 2], [], 1, [make_review('C', 5)])
>>> r4 = make_restaurant('D', [-2, 6], [], 4, [make_review('D', 2)])
>>> r5 = make_restaurant('E', [4, 2], [], 3.5, [make_review('E', 2.5), make_review('E', 3), ])
>>> c1 = [0, 0]
>>> c2 = [3, 4]
>>> groups = group_by_centroid([r1, r2, r3, r4, r5], [c1, c2])
>>> [list(map(lambda r: r['name'], c)) for c in groups]
[['A', 'B'], ['C', 'D', 'E']]
"""
# BEGIN Question 4
return_list = [] # will contain lists with the centroid as the first value and then the restaurant. the centroid will be the closest of that restaurant
for rest in restaurants:
closest = find_closest(rest['location'], centroids) # find the closest centroid for each restaurant
return_list.append([closest, rest]) # append to list with closest centroid for group_by_first to organize
answer = group_by_first(return_list)
return answer
# END Question 4
def find_centroid(cluster):
"""Return the centroid of the locations of the restaurants in cluster.
>>> cluster1 = [
... make_restaurant('A', [-3, -4], [], 3, [make_review('A', 2)]),
... make_restaurant('B', [1, -1], [], 1, [make_review('B', 1)]),
... make_restaurant('C', [2, -4], [], 1, [make_review('C', 5)]),
... ]
>>> find_centroid(cluster1) # should be a pair of decimals
[0.0, -3.0]
"""
# BEGIN Question 5
positions = [rest['location'] for rest in cluster] # get list of positions of restaurants
x = mean([pos[0] for pos in positions]) # get the mean of the x positions
y = mean([pos[1] for pos in positions]) # get the mean of the y positions
return [x, y]
# END Question 5
def k_means(restaurants, k, max_updates=100):
"""Use k-means to group restaurants by location into k clusters."""
assert len(restaurants) >= k, 'Not enough restaurants to cluster'
old_centroids, n = [], 0
# Select initial centroids randomly by choosing k different restaurants
centroids = [restaurant_location(r) for r in sample(restaurants, k)]
while old_centroids != centroids and n < max_updates:
old_centroids = centroids
# BEGIN Question 6
"*** REPLACE THIS LINE ***"
# END Question 6
n += 1
return centroids
################################
# Phase 3: Supervised Learning #
################################
def find_predictor(user, restaurants, feature_fn):
"""Return a rating predictor (a function from restaurants to ratings),
for a user by performing least-squares linear regression using feature_fn
on the items in restaurants. Also, return the R^2 value of this model.
Arguments:
user -- A user
restaurants -- A sequence of restaurants
feature_fn -- A function that takes a restaurant and returns a number
"""
reviews_by_user = {review_restaurant_name(review): review_rating(review)
for review in user_reviews(user).values()}
xs = [feature_fn(r) for r in restaurants]
ys = [reviews_by_user[restaurant_name(r)] for r in restaurants]
# BEGIN Question 7
"*** REPLACE THIS LINE ***"
b, a, r_squared = 0, 0, 0 # REPLACE THIS LINE WITH YOUR SOLUTION
# END Question 7
def predictor(restaurant):
return b * feature_fn(restaurant) + a
return predictor, r_squared
def best_predictor(user, restaurants, feature_fns):
"""Find the feature within feature_fns that gives the highest R^2 value
for predicting ratings by the user; return a predictor using that feature.
Arguments:
user -- A user
restaurants -- A list of restaurants
feature_fns -- A sequence of functions that each takes a restaurant
"""
reviewed = user_reviewed_restaurants(user, restaurants)
# BEGIN Question 8
"*** REPLACE THIS LINE ***"
# END Question 8
def rate_all(user, restaurants, feature_fns):
"""Return the predicted ratings of restaurants by user using the best
predictor based a function from feature_fns.
Arguments:
user -- A user
restaurants -- A list of restaurants
feature_fns -- A sequence of feature functions
"""
predictor = best_predictor(user, ALL_RESTAURANTS, feature_fns)
reviewed = user_reviewed_restaurants(user, restaurants)
# BEGIN Question 9
"*** REPLACE THIS LINE ***"
# END Question 9
def search(query, restaurants):
"""Return each restaurant in restaurants that has query as a category.
Arguments:
query -- A string
restaurants -- A sequence of restaurants
"""
# BEGIN Question 10
"*** REPLACE THIS LINE ***"
# END Question 10
def feature_set():
"""Return a sequence of feature functions."""
return [restaurant_mean_rating,
restaurant_price,
restaurant_num_ratings,
lambda r: restaurant_location(r)[0],
lambda r: restaurant_location(r)[1]] |
eb0f78c036060812d10d274fef2f1495f5140cbe | AlbertoAlfredo/exercicios-cursos | /Curso-em-video/Python/aulas-python/Desafios/desafio024.py | 119 | 3.6875 | 4 | cidade = str(input("Digite a cidade que você nasceu: ")).strip()
cidade = cidade.lower()
print(cidade[:5] == "santo")
|
f01e962fd84e8e2d5022900e7d67ea00eeb9e32a | opencbsoft/kids-worksheet-generator | /application/core/generators/simple_math_addition.py | 1,283 | 3.5625 | 4 | import itertools
import random
from core.utils import Generator
class Main(Generator):
name = 'Simple math addition'
years = [4, 5]
icons_folder = ['food', 'animals']
directions = 'Aduna imaginile si scrie rezultatul in casuta.'
template = 'generators/simple_math_addition.html'
def generate_data(self):
if self.extra:
max_number = int(self.extra)
if max_number > 10:
max_number = 10
else:
max_number = 5
numbers = []
for i in range(1, max_number+1):
numbers.append(i)
result = []
for subset in itertools.combinations(numbers, 2):
if subset[0] + subset[1] <= max_number:
result.append({'no1': subset[0], 'no2': subset[1], 'icon': random.choice(self.icons), 'range1': range(subset[0]), 'range2': range(subset[1])})
result.append({'no2': subset[0], 'no1': subset[1], 'icon': random.choice(self.icons), 'range2': range(subset[0]), 'range1': range(subset[1])})
self.data = result
return result
def get_context_data(self, iteration):
context = super(Main, self).get_context_data(iteration)
context['items'] = random.sample(context['items'], 4)
return context
|
ca6bc2ff25a83b19e38fbf2579ab69140ad78bbb | benxiao/python-dynamic-programming | /bisort/bisort.py | 933 | 3.65625 | 4 | """
Binary Insertion sort is a special type up of Insertion sort which uses binary search algorithm to find out the correct position of the inserted element in the array.
Insertion sort is sorting technique that works by finding the correct position of the element in the array and then inserting it into its correct position.
Binary search is searching technique that works by finding the middle of the array for finding the element.
As the complexity of binary search is of logarithmic order, the searching algorithm’s time complexity will also decrease to of logarithmic order.
Implementation of binary Insertion sort. this program is a simple Insertion sort program but instead of the standard searching technique binary search is used.
"""
import bisect
def bisort(lst):
for i in range(1, len(lst)):
v = lst[i]
j = bisect.bisect_right(lst, v, 0, i)
lst[j+1:i+1] = lst[j:i]
lst[j] = v
|
4d83a2c0727afc90044d2aa807b02e12fc1b654a | apjemran/PythonLearning | /basics/range_and_enumerate.py | 345 | 3.84375 | 4 | '''
Created on 22-Sep-2020
@author: mohd.e.khan
'''
range1 = range(10)
for i in range(10):
print(i)
for i in range(5,10):
print(i)
print("*" * 10)
for i in range(0,100,10):
print(i)
lst = list(range(10,20))
print(lst)
# Enumerate to get index
t = [1,2,4,5,7,3]
for i in enumerate(t):
print(i) |
94e45c4b31b0013f6e9da8a9afaf633fcfecd2a5 | engineer135/coding_test | /DFS&BFS/queue.py | 240 | 3.921875 | 4 | """
큐=대기 줄이랑 같음
선입선출
"""
from collections import deque
queue = deque()
queue.append(5)
queue.append(2)
queue.append(3)
queue.popleft() #5제거
queue.append(1)
print(queue)
queue.reverse() #뒤집기
print(queue) |
3aae5b783f3687c94b4d748bce1724306b6d54e0 | nomadae/tareas | /computo_movil/crypt.py | 2,007 | 4.03125 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Programa de encripción
# Gilberto Domínguez
def cambiar_letras(step,):
alfabeto = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
crypt = {}
decrypt = {}
for x in alfabeto:
new_pos = alfabeto.index(x) + step
if new_pos >= len(alfabeto):
new_pos = new_pos % len(alfabeto)
# print(new_pos)
crypt[x] = alfabeto[new_pos]
for key,value in crypt.items():
decrypt[value] = key
return crypt, decrypt
def encriptar_msg(cadena, crypt):
s = ''
for letra in cadena:
s += crypt[letra]
return s
def desencriptar_msg(digest, crypt):
s = ''
for letra in digest:
s += decrypt[letra]
return s
if __name__ == '__main__':
option = int(input("Seleccione una opción:\n\t1) encriptar\n\t2) desencriptar\n\t3) una corrida completa\n> "))
if option == 1:
steps = int(input("Diga el numero de corrimientos: "))
cadena = input("ingrese su cadena: ").lower()
crypt, decrypt = cambiar_letras(steps)
digest = encriptar_msg(cadena, crypt)
print('Su mensaje encriptado es: {}'.format(digest))
elif option == 2:
steps = int(input("Diga el numero de corrimientos: "))
digest = input('Digite su mensaje encriptado: ')
crypt, decrypt = cambiar_letras(steps)
msg = desencriptar_msg(digest, decrypt)
print('su mensaje desencriptado es: {}'.format(msg))
else:
steps = int(input("Diga el numero de corrimientos: "))
cadena = input("ingrese su cadena: ").lower()
crypt, decrypt = cambiar_letras(steps)
digest = encriptar_msg(cadena, crypt)
print('Su mensaje encriptado es: {}'.format(digest))
msg = desencriptar_msg(digest, decrypt)
print('su mensaje desencriptado es: {}'.format(msg))
#print(cadena)
|
d1bebb763b591e045b3a78133a5c7104ceeb4c2e | MichaelAntropov/python-masterclass | /Functions_Intro/functions.py | 1,577 | 4.40625 | 4 | import re
def multiply(a: float, b: float) -> float:
"""
Multiply two arguments and return the result.
:param a: The first argument.
:param b: The second argument.
:return: The result of multiplication.
"""
result = a * b
return result
def is_palindrome(string: str) -> bool:
"""
Checks if the string (word) is a palindrome.
Will return true if given string (word) is a palindrome,
otherwise returns false. Check is case insensitive.
:param string: Sting to check on.
:return: Boolean result.
"""
# backwards = string[::-1]
# return backwards == string
string_simplified = string.casefold()
return string_simplified[::-1] == string_simplified
def is_palindrome_sentence(string: str) -> bool:
"""
Checks if the string is a palindrome.
Will return true if given string is a palindrome,
otherwise returns false. Check is case insensitive,
and will ignore any non-alphanumeric characters.
:param string: Sting to check on.
:return: Boolean result.
"""
string_simplified = re.sub(r"[^a-zA-Z0-9]", "", string)
return is_palindrome(string_simplified)
def fibonacci(n: int) -> int:
"""Return the `n` th Fibonacci number, for positive `n`."""
if 0 <= n <= 1:
return n
n_minus1, n_minus_2 = 1, 0
result = None
for f in range(n - 1):
result = n_minus1 + n_minus_2
n_minus_2 = n_minus1
n_minus1 = result
return result
for i in range(36):
print(i, fibonacci(i))
p = is_palindrome_sentence("ggg")
|
d9c783038988b38e7fe1ba9b276f55726e8f58d0 | cisco-iamit/spacex-api-home-project | /main.py | 826 | 3.5625 | 4 | """
Print the total number of launches
and summary of last n launches.
"""
# you can import local modules, too. see spacex.py
from spasex import get_launches, recent_launches
launches = get_launches()
n_launches = len(launches)
print(f"SpaceX has launched {n_launches} rockets!")
n_recent_launches = int(input("How many recent launches do you want to see: "))
# scan the list of recent launches, one by one
for launch in recent_launches(n=n_recent_launches,
launches=launches):
# assign text value based on a boolean value
successful = "Yes" if launch['launch_success'] else "No"
print(f"Mission name: {launch['mission_name']}\n"
f"Date: {launch['launch_date_utc']}\n"
f"Rocket: {launch['rocket']['rocket_name']}\n"
f"Successful: {successful}\n\n")
|
6cbfcf079647b026427132205a1fa6ba87fc3967 | wittawas19/Python-Lab | /Chapter2/63010885_Lab02_03.py | 816 | 3.671875 | 4 |
def range(*arg) :
myList = list(map(float,arg))
ansList = []
nyFormat = "{0:.3f}"
if len(arg) == 1 :
end = myList[0]
start = 0.0
while end > 0 :
ansList.append(start)
start += 1.0
end -= 1
elif len(arg) == 2 :
start = myList[0]
end = myList[1]
while start < end :
ansList.append(start)
start += 1
elif len(arg) == 3 :
start = myList[0]
end = myList[1]
step = myList[2]
while start < end:
ansList.append(float(nyFormat.format(start)))
start += step
return tuple(ansList)
print("*** New Range ***")
n = input("Enter Input : ").split()
print(range(*n))
|
6e59bf3b6576bc8c9b697ce6bd9ee0860ddaeaa7 | jsaraviab12/Exercism-Python | /isogram/isogram.py | 236 | 4.09375 | 4 | def is_isogram(string):
string = string.lower()
for letter in string:
if letter == "-" or letter == " ":
continue
if (string.count(letter) > 1):
return False
return True
|
f003a4afcbc169135b7a8095eaac525670041b89 | sbolla27/python-examples | /class2/factorial.py | 162 | 3.921875 | 4 | # a = 1
# for i in range(1,5):
# a*=i
#
# print(a)
def factorial(num):
if num == 1:
return 1
return num*factorial(num-1)
print(factorial(5)) |
207dc4ef98e7b1a731a50c5bd2ede75cb0967175 | pankaj7822/sell_old | /api/serializers.py | 2,064 | 3.5625 | 4 | '''
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes
that can then be easily rendered into JSON, XML or other content types.
Serializers also provide deserialization, allowing parsed data to be converted back into complex types,
after first validating the incoming data.
we can create and Update through serializers. Delete via serializers does not make any sense. we can delete directly python objects.
Creating Object using serializers
data={"title":"Abc","description:"asdfsa","price":789}
serialized_data=Adserializer(data)
serialized_data.is_valid()
seriaized_data.save()
Please Note that save() can only be called once is_valid() is called and it had returned true
Updating Object using serializers
data={"title":"XYZ"}
obj=Ad.objects.first()
serialized_data=Adserializer(obj,data)
serialized_data.is_valid()
seriaized_data.save()
Please Note you need to send all the fields for which blank is set false in model.
'''
from rest_framework import serializers
from .models import Ad
class Adserializer(serializers.ModelSerializer):
class Meta:
model=Ad
fields=["title","description","price","images","subcatagory"]
def validate_title(self,value): #For Validating Particular Field syantax: validate_<fieldname>(self,value):
if len(value)<=10:
raise serializers.ValidationError("Title too short!!")
return value
def validate(self,data): #For Validating Entire serializer object syntax validate(self,data):
price=data.get("price",0)
if(price<=0):
raise serializers.ValidationError("Price Must be greater than 0")
images=data.get("images",[])
if(len(images)==0):
raise serializers.ValidationError("No Images Provided")
else:
for img in images:
if(not (img.startswith("http://") or img.startswith("https://") ) ):
raise serializers.ValidationError("One or More Invalid Image URL")
return data |
2d343ffaee9ba6c0891c8a5d3a69f9cc7a5cea9e | warrenwrate/python_scripts | /groupby.py | 1,274 | 3.984375 | 4 |
from itertools import groupby
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
#tells the group by to use the first value as the grouping key
#shows complete grouping
for key, group in groupby(things, lambda x: x[0]):
print('this is the group by key', key,list(group),'\n')
#splits out by group
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
for key, group in groupby(things, lambda x: x[0]):
for thing in group:
print( "A %s is a %s." % (thing[1], key))
print(" ")
# Place data into a Dictionary
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
d = {}
for key, group in groupby(things, lambda x: x[0]):
d[key] = []
for thing in group:
d[key].append(thing[1])
print(d)
thinglst = [["animal", "bear"], ["animal", "duck"], ["plant", "cactus"], ["vehicle", "speed boat"], ["vehicle", "school bus"]]
#tells the group by to use the first value as the grouping key
#shows complete grouping
for key, group in groupby(thinglst, lambda x: x[0]):
print('this is the group by key', key,list(group),'\n')
|
2d0772c74c48eb27a466eeb83eb9b40c9a451edf | SyedaSamia/Hackerrank-30-days-challenge | /day30_bigSorting.py | 186 | 3.609375 | 4 |
if __name__ == '__main__':
x = list()
t = int(input())
for i in range(t):
x.append(input())
x.sort(key=lambda i: (len(i), i))
for i in x:
print(i)
|
0405d5d1b151298a976389ff4dea254ccff54c26 | SophieEchoSolo/PythonHomework | /Lesson6/solo06_morsecode.py | 2,831 | 4.59375 | 5 | """
Author: Sophie Solo
Course: CSC 121
Assignment: Lesson 06 - Morse Code
Description: solos06_morsecode.py - This program is suppossed to ask the user to input a string and it will return the morse code version of that string
"""
# function to compare letters in the string to morse code characters
# this function uses the .upper statement to eliminate the issue with case sensitivity
def convert_letter_to_morse(letter):
"""
Function to return the morse code version of each letter.
"""
if letter.upper().startswith('A'):
letter = '.-'
elif letter.upper().startswith('B'):
letter = '-...'
elif letter.upper().startswith('C'):
letter = '-.-.'
elif letter.upper().startswith('D'):
letter = '-..'
elif letter.upper().startswith('E'):
letter = '.'
elif letter.upper().startswith('F'):
letter = '..-.'
elif letter.upper().startswith('G'):
letter = '--.'
elif letter.upper().startswith('H'):
letter = '....'
elif letter.upper().startswith('I'):
letter = '..'
elif letter.upper().startswith('J'):
letter = '.---'
elif letter.upper().startswith('K'):
letter = '-.-'
elif letter.upper().startswith('L'):
letter = '.-..'
elif letter.upper().startswith('M'):
letter = '--'
elif letter.upper().startswith('N'):
letter = '-.'
elif letter.upper().startswith('O'):
letter = '---'
elif letter.upper().startswith('P'):
letter = '.--.'
elif letter.upper().startswith('Q'):
letter = '--.-'
elif letter.upper().startswith('R'):
letter = '.-.'
elif letter.upper().startswith('S'):
letter = '...'
elif letter.upper().startswith('T'):
letter = '-'
elif letter.upper().startswith('U'):
letter = '..-'
elif letter.upper().startswith('V'):
letter = '...-'
elif letter.upper().startswith('W'):
letter = '.--'
elif letter.upper().startswith('X'):
letter = '-..-'
elif letter.upper().startswith('Y'):
letter = '-.--'
elif letter.upper().startswith('Z'):
letter = '--..'
return letter
# main method that asks for user input and then loops through the string to return the morse code
def main():
"""
Main method that asks for input and returns the result of the conversion
"""
# asks for user input
word = input("Enter a string and I will convert it to morse code: ")
# initializes empty string
new_morse = ""
# loops through the string and calls the conversion statement
for letter in word:
result = convert_letter_to_morse(letter)
new_morse = new_morse + result
# prints the result
print(new_morse)
# calls the main method
if __name__ == "__main__":
main()
|
2a6c34312b6d42e6006fb791c9d6a73b851c01c6 | Ze1al/Algorithm-Python | /LeetCode/20.py | 626 | 3.671875 | 4 | # -*- coding:utf-8 -*-
"""
author = zengjinlin
"""
"""
有效括号
输入: "()[]{}"
输出: true
"""
class Solution:
def isValid(self, s: str):
if len(s) % 2 == 1:
return False
# 维护一个栈
stack = []
pair = {
"]": "[",
"}": "{",
")": "("
}
for i in s:
if i in pair:
if not stack or stack[-1] == pair[i]:
return False
stack.pop()
else:
stack.append(i)
if stack:
return False
return True |
31ab489878e25522029654c2b91e29ab64d68455 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3_neat/16_0_3_supermanwonderwoman_jam3.py | 1,421 | 3.59375 | 4 | import random
from math import sqrt
from itertools import count, islice
def isPrime(n):
if n < 2: return False
for number in islice(count(2), 9999999):
if not n%number:
return number
return False
jamcoins = []
def coin_tester(num):
divisors = []
multipliers = [31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0]
for x in range(2,11):
digits = str(num)
basex = 0
for digit in range(0,32):
basex += (int(digits[digit])*(x**multipliers[digit]))
primers = isPrime(basex)
if primers != False:
divisors.append(primers)
else:
return False
return divisors
def jamcoin_generator():
print("Case #1:")
jam = ['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1','0','1','0','1','0','1','0','1','0','1','1','1','1']
while len(jamcoins) < 500:
for x in range(1,31):
jam[x] = str(random.randint(0,1))
generated = int("".join(jam))
if generated not in jamcoins:
savejam = coin_tester(generated)
if savejam != False:
jamcoins.append(generated)
print(generated, end="")
for x in savejam:
print("",x, end="")
print()
|
26e6cec9360e81d5157fb92530bf0ba749dd00c0 | ankuarya/python_programs | /word_calc.py | 399 | 3.890625 | 4 | sentence = input('Please enter a sentence : ')
words=sentence.split(' ')
char_count_dict={}
for word in words :
characters = list(word)
for char in characters :
if char in char_count_dict :
char_count_dict[char] += 1
else:
char_count_dict[char] = 1
sorted_keys = sorted(char_count_dict.keys())
for key in sorted_keys:
value = char_count_dict[key]
print('found:',key,value,'times')
|
77f44086e6ddbdd980d51244a7068c01e7be7c3d | catherinenofail/Implementation_Proj | /ConvexHull.py | 2,657 | 3.625 | 4 | import math
import random
import timeit
def makeRandomData(numPoints):
#"Generate a list of random points within a unit circle."
# numPoints = 10
# Fill a unit circle with random points.
t, u , r, x, y = 0, 0, 0, 0, 0
P = []
for i in range(0,numPoints):
#random() should be within 0 and 1
t = 2*math.pi*random.random()
u = random.random()+random.random()
if u > 1:
r = 2-u
else:
r = u
x = r*math.cos(t)
y = r*math.sin(t)
P.append((x, y))
return P
def convexHull(points):
"""Computes the convex hull of a set of 2D points.
Input: an iterable sequence of (x, y) pairs representing the points.
Output: a list of vertices of the convex hull in counter-clockwise order,
starting from the vertex with the lexicographically smallest coordinates.
Implements Andrew's monotone chain algorithm. O(n log n) complexity.
"""
# Sort the points lexicographically (tuples are compared lexicographically).
# Remove duplicates to detect the case we have just one unique point.
points = sorted(set(points))
# Boring case: no points or a single point, possibly repeated multiple times.
if len(points) <= 1:
return points
# 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
# Returns a positive value, if OAB makes a counter-clockwise turn,
# negative for clockwise turn, and zero if the points are collinear.
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
# Build lower hull
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
# Build upper hull
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
# Concatenation of the lower and upper hulls gives the convex hull.
# Last point of each list is omitted because it is repeated at the beginning of the other list.
return lower[:-1] + upper[:-1]
def test():
start = timeit.default_timer()
n = 3000
p = makeRandomData(n)
iterations = 0
while len(p) != 0:
iterations = iterations + 1
c = convexHull(p)
#print('There are {0} points in p' .format(len(p)) )
#print('There are {0} convex hull points' .format(len(c)))
pop = 0
while len(c) != 0:
x = c.pop()
p.remove(x)
stop = timeit.default_timer()
print('For {0} vertices...' .format(n))
print('Algorithm took {0} seconds' .format(stop-start))
print('There are {0} iterations' .format(iterations))
test()
|
2c54fe4a9662ca722cf4b1b713bf95f14f87411e | mayankmandloi/pythontut-2-7-18 | /Day-15/for.py | 106 | 3.578125 | 4 | for a in range(10):
print(a)
for a in range(2,20):
print(a)
for a in range(2,20,2):
print(a) |
4f3cd05e4dd91274db1921b61e7df7575ee3635c | houxudong1997/Advanced-Artificial-Intelligence | /Uniform-Cost Search.py | 1,561 | 3.78125 | 4 |
import heapq
graph = {
"s": {"a": 8, "b": 5, "c": 10},
"a": {"b": 7, "d": 9},
"b": {"a": 7, "f": 17},
"c": {"e": 13},
"d": {"a": 9, "f": 16, "g":31},
"e": {"c": 13,"f":11,"g":29},
"f": {"b":17,"d":16,"e":11,"g":4},
"g": {"d":31,"e":29,"f":4}
}
class Dijkstra:
def init_distance(self, graph, start):
distance = {start: 0}
for key in graph.keys():
if key != start:
distance[key] = float('inf')
return distance
def dijkstra(self, graph, start):
if not graph or not start:
return None
distance = self.init_distance(graph, start)
pqueue = []
visitorder=[]
heapq.heappush(pqueue, (0, start))
seen = set()
parent = {start: None}
while pqueue:
cur_distance, cur_node = heapq.heappop(pqueue)
seen.add(cur_node)
nodes = graph[cur_node]
for node, dist in nodes.items():
if node in seen:
continue
elif distance[node] > cur_distance + dist:
heapq.heappush(pqueue, (dist + cur_distance, node))
parent[node] = cur_node
distance[node] = cur_distance + dist
visitorder.append(cur_node)
print(visitorder)
return distance, parent
if __name__ == '__main__':
s = Dijkstra()
distance, parent = s.dijkstra(graph, "s")
print(distance)
print(parent)
|
c25ad3658e36e899994e8004e201f9466bf9b38a | HyangSa/study | /Python/2주차(0321)/0321-1-Ellipse.py | 997 | 3.953125 | 4 | import turtle as t
import math
t.speed(0)
def drawLine():
t.penup()
t.setx(-200)
t.pendown()
t.setx(200)
t.write('x',font=('',20,''))
t.penup()
t.goto(0,200)
t.pendown()
t.sety(-200)
t.write('y',font=('',20,''))
##a=int(input("장축 a 입력 : "))
##b=int(input("단축 b 입력 : "))
##x=int(input("x좌표 입력 : "))
##y=int(input("y좌표 입력 : "))
a=200
b=100
curx=100
cury=100
angle=0
drawLine()
t.penup()
t.goto(curx,cury)
t.pendown()
t.dot(a,"blue")
t.goto(curx,cury)
t.dot(b,"red")
t.penup()
##t.goto(curx,cury)
##t.left(120)
##t.forward(b/2)
x=curx+math.cos(math.radians(1))*a/2
y=curx+math.sin(math.radians(1))*b/2
t.goto(x,y)
t.pendown()
for i in range(0,360):
x=(math.cos(math.radians(i))*a/2)
y=(math.sin(math.radians(i))*b/2)
rex=curx+math.cos(math.radians(angle))*x + (-math.sin(math.radians(angle))*y)
rey=curx+math.sin(math.radians(angle))*x + (math.cos(math.radians(angle))*y)
t.goto(rex,rey)
|
438eb372d94e5dc9a8e2af3d0ac646730243254d | Praveenk8051/data-science | /visualizations/visualization_using_dash/makedf.py | 3,681 | 3.578125 | 4 | import pandas as pd
import os
import numpy as np
import datetime
def getDataframe(path):
#declare the string columns
str_columns=['Overall', 'Polarity', 'Response','Unit_Id','rub+buzz','thd']
##TODO:Append the rows in df
def addRow(df,ls):
"""
Given a dataframe and a list, append the list as a new row to the dataframe.
:param df: <DataFrame> The original dataframe
:param ls: <list> The new row to be added
:return: <DataFrame> The dataframe with the newly appended row
"""
numEl = len(ls)
newRow = pd.DataFrame(np.array(ls).reshape(1,numEl), columns = list(df.columns))
df = df.append(newRow, ignore_index=True)
return df
##TODO:Clean all the data
def df_replace(df):
#Data cleaning
df['Overall']=df['Overall'].str.lower().str.replace('sin','').str.replace('1','').str.replace('\n','').str.replace(' ','').str.upper()
df['Polarity']=df['Polarity'].str.lower().str.replace('polarity','').str.replace('\n','').str.replace(' ','').str.upper()
df['Response']=df['Response'].str.lower().str.replace('response','').str.replace('\n','').str.replace(' ','').str.upper()
df['Unit_Id']=df['Unit_Id'].str.lower().str.replace('unit n. ','').str.replace('good','').str.replace('bad','').str.replace('\n','').str.replace(' ','').str.upper()
df['rub+buzz']=df['rub+buzz'].str.lower().str.replace('rub','').str.replace('+','').str.replace('buzz','').str.replace('rub+buzz','').str.replace('\n','').str.replace(' ','').str.upper()
df['thd']=df['thd'].str.lower().str.replace('thd','').str.replace('\n','').str.replace(' ','').str.upper()
df['Timestamp']=df['Timestamp'].str.lower().str.replace('am','').str.replace('pm','').str.rstrip().str.lstrip().str.replace('-','.').str.replace(':','.').str.upper()
##TODO:Discard non date-time formats and keep in datetime.datetime format
for i,j in df['Timestamp'].iteritems():
try:
if len(j)==19:
try:
date=datetime.datetime.strptime(j, '%d.%m.%Y %H.%M.%S')
df.loc[i,'Timestamp']=date.date()
except ValueError:
date=datetime.datetime.strptime(j, '%Y.%m.%d %H.%M.%S')
df.loc[i,'Timestamp']=date.date()
else:
date=datetime.datetime.strptime(j, '%m.%d.%Y %H.%M.%S')
df.loc[i,'Timestamp']=date.date()
except ValueError:
df=df.drop([df.index[i]])
pass
df=df.replace(to_replace=['GOOD', 'BAD'], value=[1, 0])
numericCols=['Overall','Response', 'Polarity', 'rub+buzz', 'thd']
df[numericCols]=df[numericCols].apply(pd.to_numeric, errors='ignore')
return df
##TODO: Copy all the paths of text files
textFiles=[]
for d in os.listdir(path):
textFiles.append(os.path.join(path, d))
##Read and create df
df=pd.DataFrame({'Overall':[],'Response':[],'Polarity':[],'rub+buzz':[],'thd':[],'Timestamp':[],'Unit_Id':[]})
for i in range(len(textFiles)):
G=open(textFiles[i],'r')
stringss=G.readlines()
if len(stringss)==7:
df=addRow(df,stringss)
else:
print(textFiles[i])
continue
##Format the df
df[str_columns]=df[str_columns].astype(str)
df=df_replace(df)
return df
|
ba3da5e6be9389711f85ad8078ca815b59087c72 | Zmek95/A.I-Slot-Car | /Main/DataCollectionMain.py | 548 | 3.75 | 4 | #!/usr/bin/env python3
from pwmGenerate import forward, stop, pwm_init
from SensorRecord import sensor_record, sensor_calibrate
# Get user speed and test time
speed = int(input("Enter the desired duty cycle 0 - 100"))
sensor_time = int(input("Enter the desired sensor read time in seconds"))
# Calibrate BNO-055 sensor
sensor_calibrate()
# Initialize pwm and set speed of motor to the user speed
pwm = pwm_init()
forward(pwm, speed)
# Record readings from sensor
sensor_record(sensor_time)
# Sensor readings complete so stop the motor.
stop(pwm)
|
5efec8cf77caf351914b4cab6fb2a2cebeeecc5d | marcbaetica/Brute-Force-Attack-Utility | /db/db.py | 2,714 | 3.671875 | 4 | import os
import sqlite3 as sl
class DB:
def __init__(self, name):
self.name = name
self.connection = self._create_db()
self.tables = []
def _create_db(self):
connection = sl.connect(self.name)
return connection
def query(self, query):
with self.connection as con:
return con.execute(query)
def create_table(self, table):
self._drop_table_if_exists(table)
query = f"""
CREATE TABLE {table} (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
username TEXT,
password TEXT
);
"""
self.query(query)
self.tables.append(table)
def _drop_table_if_exists(self, table):
query = f'DROP TABLE IF EXISTS {table};'
self.query(query)
def read_all_entries_from_table(self, table):
if len(self.tables) == 0:
print('There are no tables to read from at this time.')
return
if table not in self.tables:
print(f'Table {table} was not found in the list of existing db tables: {self.tables}')
return
with self.connection as con:
data = con.execute(f'SELECT * FROM {table};')
return data
def list_all_tables(self):
with self.connection as con:
return con.execute(f'SELECT * FROM sqlite_master WHERE type="table";')
def insert_into_table(self, table, identifier, username, password):
if table not in self.tables:
print(f'Table {table} was not found in the list of existing db tables: {self.tables}')
return
with self.connection as con:
con.execute(f'INSERT INTO {table} (id, username, password) VALUES ({identifier}, "{username}", "{password}");')
# print(?)
def list_table_columns(self, table):
with self.connection as con:
table_columns = con.execute(f'PRAGMA table_info([{table}]);')
for column in table_columns:
print(column)
def delete_table(self, table):
table = table
with self.connection as con:
con.execute(f'DROP TABLE {table};')
# if above is successful
self.tables.remove(table)
print(f'Removed {table} from db {self.name}. Remaining tables: {self.tables}')
def delete_db(self, db):
if self.connection:
self.connection.close() # Otherwise os system call will fail as file is in use.
os.remove(db)
remaining_dbs = [file for file in os.listdir() if '.db' in file]
if remaining_dbs:
print(f'Databases remaining: {remaining_dbs}')
|
b621d3680a868209d8d62d3269470d8ea297c4ae | Jayesh598007/Python_tutorial | /Chap4_list_and_tuple/05_tuple_methods.py | 182 | 3.90625 | 4 | t = (1, 3, 4, 2, 6, 1, 4, 1)
# counting the elements
print(t.count(1))
print(t.count(4))
print(t.count(3))
# searching the index for an element
print(t.index(6))
print(t.index(3)) |
d5df2ef3916e395783d51a27896ba5a85f0828b7 | feeroz123/LearningPython | /udemy/ReverseWordOrder.py | 486 | 4.375 | 4 | # Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
ustring = input("Enter a sentence: ")
splitString = ustring.split(" ") # Separate the words by " " character
splitString.reverse() # Perform reverse operation on the string
print(" ".join(splitString)) # Stitch/Merge the words with " " character in between them
|
9ab67f773a12cc42061300cb39d1d08f5ca10933 | Lihess/AlgorithmStudy | /CodeUP_100/1034 _ [기초-출력변환] 8진 정수 1개 입력받아 10진수로 출력하기.py | 125 | 3.53125 | 4 | a = input()
print("%d" % int(a, 8)) # int(숫자, 8)과 같이 지정하면 해당 숫자를 8진수로 변경할 수 있다
|
8c04b68d31ca11155783a7d40a70e880a3f9c8bc | darcyfzh/algorithm | /leedcode/Search_Insert_Position.py | 530 | 3.6875 | 4 | def Search_Insert_Position(nums,k):
if nums == None or nums == []:
return 0
low = 0
high = len(nums) - 1
while(low <= high):
if k > nums[-1]:
return len
if k < nums[0]:
return 0
mid = (low + high) / 2
midData = nums[mid]
if midData == k:
return k
elif midData > k:
high = mid - 1
if nums[high] < k:
return high + 1
else:
low = mid + 1
if nums[low] > k:
return low
|
1115c3d085790edd6e6cc89087bc25513a27a4dd | harshraj22/problem_solving | /solution/hacker_rank/ConnectedComponent.py | 817 | 3.65625 | 4 | # https://www.hackerrank.com/contests/data-structure-tasks-binary-tree-union-find/challenges/connected-component/problem
from sys import stdin
par, weight = [], []
nodes = int(input())
connected = nodes
par = [i for i in range(nodes+5)]
weight = [1 for i in range(nodes+5)]
def find_par(u):
if par[u] == u:
return u
par[u] = find_par(par[u])
return par[u]
def merge(u, v):
up, vp = find_par(u), find_par(v)
if weight[up] > weight[vp]:
weight[up] += weight[vp]
par[vp] = up
else:
weight[vp] += weight[up]
par[up] = vp
for line in stdin:
u, v = map(int, line.split())
up, vp = find_par(u), find_par(v)
if up == vp:
print(connected, "CYCLE FORMED!")
else:
connected -= 1
print(connected)
merge(up, vp) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.