blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
2c462db90bac86347ea07ac7e8c1a230d12cab34 | dalaAM/month-01 | /day19_all/day19/exercise02.py | 621 | 4 | 4 | """
exercise:使用装饰器,为旧功能增加新功能.
"""
def print_fun(func):# 拦截(调用旧功能,执行内部函数)
def wrapper(*args, **kwargs):# 包裹(执行新+旧功能)
print("执行了", func.__name__, "函数")
return func(*args, **kwargs)
return wrapper
# 新功能
# def print_func(func):
# print("执行了", func.__name__, "函数")
# 旧功能
@print_fun
def insert(data):
# print_func(insert)
print("插入", data, "成功")
@print_fun
def delete(id):
# print_func(delete)
print("删除", id, "成功")
insert("ok")
delete(1001)
|
96546d75487294307a6e49df40e02c3eebbe832c | PunterGit/StructuralProgramming | /Laba3/Z6.py | 171 | 4 | 4 | import math
n = int(input("Введите n "))
x = int(input("Введите x "))
s = 1
for i in range(1, n):
s += (math.cos(i * x)) / math.factorial(i)
print(s)
|
4fecf598156df9a1fcad61f9d78b66c1705f40b9 | aishwarya07g/SpeckbitLaunchpad | /Problem3.py | 125 | 3.734375 | 4 | num1 = eval(input("Enter a list: "))
num2 = []
for i in range(len(num1)):
if num1[i]==2:
num2.append(i)
print(num2)
|
13e83b663e3e5fcf43505e4a7133701f5d2db97a | yaoayaoflora/gogoyao | /DataStructuresAlgorithms/grokking-the-coding-interview-patterns-for-coding-questions/3_Fast_Slow_Pointers/3_6.py | 1,876 | 4.28125 | 4 | # Given the head of a Singly LinkedList, write a method to modify the LinkedList such that the
# nodes from the second half of the LinkedList are inserted alternately to the nodes from the first half
# in reverse order. So if the LinkedList has nodes 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null,
# your method should return 1 -> 6 -> 2 -> 5 -> 3 -> 4 -> null.
#
# Your algorithm should not use any extra space and the input LinkedList should be modified in-place.
from __future__ import print_function
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:
print(str(temp.value) + ' ', end='')
temp = temp.next
print()
def reorder(head):
if head is None or head.next is None:
return
slow = head
fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
head_second_half = reverse(slow)
head_first_half = head
while head_first_half is not None and head_second_half is not None:
temp = head_first_half.next
head_first_half.next = head_second_half
head_first_half = temp
temp = head_second_half.next
head_second_half.next = head_first_half
head_second_half = temp
if head_first_half is not None:
head_first_half.next = None
def reverse(head):
prev = None
while head is not None:
next = head.next
head.next = prev
prev = head
head = next
return prev
def main():
head = Node(2)
head.next = Node(4)
head.next.next = Node(6)
head.next.next.next = Node(8)
head.next.next.next.next = Node(10)
head.next.next.next.next.next = Node(12)
reorder(head)
head.print_list()
main() |
c8f3c94c82ff4a912740c388cec1b0e1642c19d1 | Kyrandis/Zookeeper | /Problems/Difference of times/task.py | 331 | 3.875 | 4 | # put your python code here
hours1 = int(input())
minutes1 = int(input())
result1 = int(input())
hours2 = int(input())
minutes2 = int(input())
result2 = int(input())
time1 = (hours1 * 3600) + (minutes1 * 60) + result1
time2 = (hours2 * 3600) + (minutes2 * 60) + result2
# output is in seconds
final = time2 - time1
print(final)
|
47604b124541814122d49bc9c8c21f34572968b5 | DishantNaik/kg_DishantNaik_2021 | /main.py | 811 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 17:16:43 2020
@author: iCule10 (Dishant Naik)
"""
def run(s1,s2):
#Both string must be of same length
if(len(s1) == len(s2)):
tmp_s1, tmp_s2 = {},{}
#Assigning key to each value in s1
for i, val in enumerate(s1): tmp_s1[val] = tmp_s1.get(val,[]) + [i]
#Assigning key to each value in s2
for i, val in enumerate(s2): tmp_s2[val] = tmp_s2.get(val,[]) + [i]
#Compare if number of distinc values + same same values(all same valses counts as 1 e.g (aab = [[0,1],2]))in s1 is equal to s2 then return true
#else return false
if sorted(tmp_s1.values()) == sorted(tmp_s2.values()): return("true")
else: return("false")
else: return("false")
|
b716b9987677efa593f1ca3370f866328c6753fe | DavidMarquezF/InfoQuadri2 | /Practica 7/MergeSort.py | 1,046 | 4.28125 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
def mergeSort(l):
"""
retorna una nova llista ordenada segons el merge sort
>>> mergeSort([10,5,25,1,4,3,5,68,2,9])
[1, 2, 3, 4, 5, 5, 9, 10, 25, 68]
>>> mergeSort([256,44,32,56,2,134])
[2, 32, 44, 56, 134, 256]
"""
list = l[:]
if len(list)>1:
mid=len(list)/2
lefthalf=list[:mid]
righthalf=list[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i] < righthalf[j]:
list[k]=lefthalf[i]
i+=1
else:
list[k]=righthalf[j]
j+=1
k+=1
while i<len(lefthalf):
list[k]=lefthalf[i]
i+=1
k+=1
while j<len(righthalf):
list[k]=righthalf[j]
j+=1
k+=1
return list
if (__name__ == "__main__"):
l=[54,26,93,17,77,31,44,55,20]
print mergeSort(l)
|
9aef0a377798e58e7813147391b272f1557bae96 | Zhaisan/PythonDev | /informatics/int arithmetic/m.py | 253 | 3.671875 | 4 | x = int(input())
y = int(input())
z = int(input())
if x % 2 == 0:
x = x // 2
else:
x = x // 2 + 1
if y % 2 == 0:
y = y // 2
else:
y = y // 2 + 1
if z % 2 == 0:
z = z // 2
else:
z = z // 2 + 1
print(x + y +z) |
57736873fa1c9c4d839c61c8a14788e117b163de | JayakumarClassroom/Python-Programs | /code/sample-41.py | 1,078 | 4.375 | 4 | #For loop - Quadratic Equation Solver
import cmath
#welcome message
print("Welcome to Quadratic Equation Solver")
print("Quadratic Equation is ax^2 + bx + c = 0 ")
print("Your solution can be Real or Imaginary")
print("Your complex number is a + bj ")
print("Where a is the real portion bi is the imaginary portion")
#Get value from user
en_num=int(input("\nHow many equation would you like to solve today : "))
#loop through solve the equation
for i in range(1,en_num+1):
print(f"\nSolving Equation # {i}")
print("------------------------------------")
a = float(input("Enter the coefficient of x^2 : "))
b = float(input("Enter the coefficient of x : "))
c = float(input("Enter the coefficient : "))
#solving Quadratic Equation formula
x1=(-b + cmath.sqrt(b**2 - 4*a*c))/(2*a)
x2=(-b - cmath.sqrt(b**2 - 4*a*c))/(2*a)
print(f"\nThe Solution to {a}x^2 + {b}x + {c} = 0")
print(f"\n\tX1 = {x1}")
print(f"\tX2 = {x2}")
print("--------------------------------------------------------------------")
print("\nThank you for solving the Quadratic Equation. :)") |
8e45df8771b20eeef380aa2f4e67dd5608a98e56 | HatlessFox/UNIX-labs | /TEST1/t2.py | 344 | 3.734375 | 4 | #!/usr/local/bin/python3
import sys
arg = sys.argv[1]
def is_pol(st):
return st == st[::-1]
def substr(st, code):
res = [st[i] for i in range(len(st)) if code & 2**i == 0]
return "".join(res)
max_p = ""
for code in range(0, 2**len(arg)):
st = substr(arg, code)
if is_pol(st) and len(st) > len(max_p):
max_p = st
print(max_p) |
7ac2281b46afc482f38a90ac430e862d66cb255f | bioJain/python_Bioinformatics | /Rosalind/Bioinformatic-textbook-track/BA1I_FreqWordWithMis.py | 1,532 | 3.75 | 4 | # BA1I
# Find the Most Frequent Words with Mismatches in a String
# Find the most frequent k-mers with mismatches in a string.
# Given: A string Text as well as integers k and d.
# Return: All most frequent k-mers with up to d mismatches in Text.
# to calculate the hamming distance between two strings
from BA1G import hamming
from ReadnWrite import *
def FreqWordWithMis(text, k, d):
Set = {}
maxcount = 0
for i in range(len(text)-k+1):
pattern = text[i:i+k]
Neighborpattern = Neighbors(pattern, d)
for pt in Neighborpattern :
Set[pt] = Set.get(pt, 0) + 1
if Set[pt] >= maxcount :
maxcount = Set[pt]
for i in Set.keys():
if maxcount == Set[i] :
print i,
def Neighbors(pattern, d):
if d == 0:
return pattern
if len(pattern) == 1:
return ['A', 'C', 'G', 'T']
Neighborhood = []
SuffixNeighbors = Neighbors(pattern[1:], d)
for text in SuffixNeighbors :
if hamming(pattern[1:], text) < d :
for nt in ['A', 'C', 'G', 'T']:
Neighborhood.append(nt+text)
else :
Neighborhood.append(pattern[0]+text)
return Neighborhood
#print FreqWordWithMis('CACAGTAGGCGCCGGCACACACAGCCCCGGGCCCCGGGCCGCCCCGGGCCGGCGGCCGCCGGCGCCGGCACACCGGCACAGCCGTACCGGCACAGTAGTACCGGCCGGCCGGCACACCGGCACACCGGGTACACACCGGGGCGCACACACAGGCGGGCGCCGGGCCCCGGGCCGTACCGGGCCGCCGGCGGCCCACAGGCGCCGGCACAGTACCGGCACACACAGTAGCCCACACACAGGCGGGCGGTAGCCGGCGCACACACACACAGTAGGCGCACAGCCGCCCACACACACCGGCCGGCCGGCACAGGCGGGCGGGCGCACACACACCGGCACAGTAGTAGGCGGCCGGCGCACAGCC', 10, 2)
#Data = readExcLast('rosalind_ba1i.txt')
#FreqWordWithMis(Data, 7, 2)
|
9f313ba2d0b10c4731c82bb81e6af49ee71cdbbd | fuLinHu/python | /learn/set.py | 251 | 3.546875 | 4 | #set={2,4,5}
#print(type(set))
set1=set("78yttru")
print(set1)
a={x for x in ("a","e","3") if x != "3"}
print(a)
b=set()
b.add(1)
b.add(2)
b.add("4")
b.add("5")
print(b.discard(2))
print(b)
a,b=0,1
while b<1000:
a,b=b,a+b
print(a,end=",")
|
ea1d4a64de8bf29793354aa346c7c1b86a99f558 | Kimberly07-Ernane/Python | /Pacote para dowloand/Python/ex008( if ,elif e while) receber idade e peso.py | 792 | 3.96875 | 4 | #Crie um programa que receba idade e peso de cinco pessoas e calcule:
#A maior idade;
#A quantidade de pessoas que pesam mais que 90kg;
#Média das idades das pessoas que pesam menos de 50 kg.
maior=0
qtd90=0
media=0
qtd=0
soma=0
idade=int(input("Entre com a idade:"))
while idade >0:
peso=int(input("Entre com o peso: "))
if idade > maior:
msior=idade
if peso<90:
qtd90+=1
if peso <50:
soma = soma +idade
qtd+=1
idade=int(input("Entre com a idade: "))
if qtd>0:
media=soma/qtd
print("Maior idade:",maior)
print("Quantidade de pessoas que pesam mais que 90kg: ",qtd90)
print("Média das idades das pessoas que pasam menos que 50kg: ",media)
|
9e361efb8a2ecddd5e39dfb6f7dd8c0b285f5dc4 | gsourdat/TestRepo | /LogMagasin/Model/user_model.py | 663 | 3.546875 | 4 | print(2)
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
engine = create_engine('sqlite:///:memory:', echo=True)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
nickname = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', nickname='%s')>" % (self.name, self.fullname, self.nickname)
Base.metadata.create_all(engine)
user = User(id=123, name="greg", fullname="greg", nickname="greg")
print(user.name)
|
78138901da48f3774cd4a58d8600a9090c2f4e8a | franperez022/LMSGI | /Usuarioxml/4.py | 552 | 3.71875 | 4 | #4) Pedir una cadena por teclado y mostrar todos los usarios
#cuyo nombre empieza por dicha cadena (Ejemplo: si meto la cadena "A"
#mostrará todos los usuarios cuyo nombre empeiza por A...)
from lxml import etree
arbol = etree.parse('users.xml')
usuarios = arbol.findall("user")
cadena = input("Introduce una letra: ")
for usuario in usuarios:
#Que empiece por la cadena introducida
if usuario.findtext("firstname").startswith(cadena):
#print el campo texto user name cuyo
#nombre empieza por cadena
print (usuario.find("username").text) |
4fc94f85e4cf6c538535f4ae3a06b41e892eb39c | Dirguis/cepbp | /cepbp/common/custom_error_handler.py | 402 | 3.609375 | 4 | class CustomError(Exception):
"""
Custom error class, to pass a custom message and data to the user as needed
Parameters
----------
msg: string
Error message
data: anything
Whatever data is useful to print
"""
def __init__(self, msg, data=''):
self.msg = msg
self.data = data
def __str__(self):
return repr(self.msg, self.data)
|
ee68fb6ff223f3dae8c9460a6cb54fe27c3447b2 | lehuutrung1412/CS112.L21.KHTN | /Homework/Week_6/bestSum.py | 663 | 3.578125 | 4 | def findBestSum(arr, sum, memo = {}):
if sum in memo:
return memo[sum]
elif sum < 0:
return None
elif sum == 0:
return []
min_element = None
for num in arr:
remain = sum - num
sum_remain = findBestSum(arr, remain, memo)
if not sum_remain is None:
element = [num]
element += sum_remain
if min_element is None or len(min_element) > len(element):
min_element = element
memo[sum] = min_element
return min_element
if __name__ == "__main__":
arr = list(map(int, input().split()))
k = int(input())
print(*findBestSum(arr, k)) |
0e7671ccbd45a80c1b7435ccf9f89191f4d2b4c6 | NechayevAntonn/--- | /исходный.py | 1,904 | 3.9375 | 4 |
# http://blog.chapagain.com.np/hash-table-implementation-in-python-data-structures-algorithms/
hash_table = [[] for _ in range(10)] #Создание хеш-таблицы в виде вложенного списка (списки внутри списка).
def insert(hash_table, key, value): #hash_table -- [[], [], [], [], [], [], [], [], [], []], key -- 10, value -- Nepal
hash_key = hash(key) % len(hash_table) # hash(10) % len([[], [], [], [], [], [], [], [], [], []]), т.е hash_key == 0
key_exists = False
bucket = hash_table[hash_key] #назовем каждый отдельный список в списке хеш-таблиц как «bucket», возьмет 0-й элемент, т.е. [] -- пустой список.
for i, kv in enumerate(bucket): # выполнится bucket.append((key, value)), при (20, 'India') Цикл по enumerate выполнится и i == 0, kv == (10, 'Nepal'), k == 10, v = Nepal
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket[i] = ((key, value))
else:
bucket.append((key, value)) # append() - добавляет элемент в список
insert(hash_table, 10, 'Nepal')
insert(hash_table, 25, 'USA')
insert(hash_table, 20, 'India')
def search(hash_table, key): #При поиске любого ключа в хеш-таблице мы должны циклически проходить по каждому отдельному подсписку.
hash_key = hash(key) % len(hash_table)
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
return v
print (search(hash_table, 10)) # Output: Nepal
print (search(hash_table, 20)) # Output: India
print (search(hash_table, 30)) # Output: None
|
c5e533812ab141ae1bc66bb37147133d937770ac | Carolina1992Assen/SE | /ku.py~ | 1,371 | 3.78125 | 4 | #!/usr/bin/env python3
# Author: Carlijn Assen
import sys
import numpy as np
def is_vowel(letter):
l = 0
if letter in ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]:
l = 0.5
else:
l = 1
return l
def ls(x, y):
if x == y:
return 0
elif len(x) == 0:
return len(y)
elif len(y) == 0:
return len(x)
lx = len(x) + 1
ly = len(y) + 1
d = np.zeros((lx, ly))
for i in range(len(d[0])):
d[0][i] = i
for j in range(len(d)):
d[j][0] = j
for j in range(1, ly):
for i in range(1, lx):
if y[j - 1] == x[i - 1] or y[j - 1] == x[i - 1]:
n = 0
deletion = d[i - 1, j] + n
insertion = d[i, j - 1] + n
substitution = d[i - 1, j - 1] + n
elif x[i - 1] != y[j - 1]:
deletion = d[i - 1, j] + is_vowel(x[i - 1]) or is_vowel(y[i - 1])
insertion = d[i, j - 1] + is_vowel(y[j - 1]) or is_vowel(x[i - 1])
substitution = d[i - 1, j - 1] + 1
d[i, j] = min(deletion, substitution, insertion)
return d[i, j]
def main():
for line in sys.stdin:
line = line.strip()
line = line.split()
w1 = line[0]
w2 = line[1]
print(w1, w2, ls(w1, w2), line[2])
if __name__ == "__main__":
main()
|
e3fc109f6a9aad31a268998a86e624813b2e4bcd | MatthiasHunt/Project-Euler | /euler-07.py | 665 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 19:23:14 2019
https://projecteuler.net/problem=7
@author: matth
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
def main():
print(primes(10001)[-1])
def primes(n):
"""Returns a list of the first n primes in increasing order - Not useful past 10,000"""
prime_list = [2]
p = 3
while (len(prime_list) < n):
if all (p % prime != 0 for prime in prime_list):
prime_list.append(p)
p += 1
return prime_list
#############################
if __name__ == '__main__':
main() |
ebd54ff62a5918a42095b205aaa71bd95df9dfb4 | YuliuSYK/NLP_Test | /5.NLTK_Tokenize.py | 628 | 3.5625 | 4 | from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
mytext = "Hello Adam, how are you? I hope everything is going well. Today is a good day, see you dude."
print(sent_tokenize(mytext))
mytext = "Hello Mr. Adam, how are you? I hope everything is going well. Today is a good day, see you dude."
print(sent_tokenize(mytext))
mytext = "Hello Mr. Adam, how are you? I hope everything is going well. Today is a good day, see you dude."
print(word_tokenize(mytext))
mytext = "Bonjour M. Adam, comment allez-vous? J'espère que tout va bien. Aujourd'hui est un bon jour."
print(sent_tokenize(mytext,"french")) |
d6862340307234ad349356f25b5d569d3aafe481 | subhi28/python | /hun89.py | 87 | 3.65625 | 4 | str=input()
x=''
for i in str:
if i not in x:
x=x+i
print(x[::-1])
|
210101ea57119fd5916d524fd2fcff9ab609c8e5 | Mr-Venu/Assignment-WEEK-1 | /7.py | 125 | 4 | 4 | print('Printing first m multiples of n')
m=int(input('Enter m '))
n=int(input('Enter n '))
i=range(n,m*n+1,n)
print(list(i))
|
02c655efed59f7c923b46e0340f7962a9ba02319 | dsluijk/TICT-V1PROG-15 | /les-1/perkavic/2-13.py | 234 | 3.671875 | 4 | # Variable assignment
s1 = '-';
s2 = '+';
# A
print(s1 + s2);
# B
print(s1 + s2);
# C
print(s2 + (s1 * 2));
# D
print((s2 + (s1 * 2)) * 2);
# E
print(((s2 + (s1 * 2)) * 10) + s2);
# F
print((s2 + s1 + (s2 * 3) + (s1 * 2)) * 5);
|
9ebdaf6a7ee7bfa8cefe855c95c39ec9700a864f | priysha2/concepts | /2.py | 287 | 4.0625 | 4 | def max_of_three(x,y,z):
if ((x>y)&(x>z)):
print("%d is greater than %d and %d" %(x,y,z))
elif ((y>x) & (y>z)):
print("%d is greater than %d and %d" % (y,x,z))
else:
print("%d is largest of %d and %d" %(z,x,y))
max_of_three(20,40,10) |
908b6fa528a02a36ebceea98b67f695b00884675 | ricardo-tapia/CYPJoseMT | /libro/ejemplo1_13.py | 360 | 3.515625 | 4 | CAL1 = float(input("Dame la calificación 1: " ))
CAL2 = float(input("Dame la calificación 2: " ))
CAL3 = float(input("Dame la calificación 3: " ))
CAL4 = float(input("Dame la calificación 4: " ))
CAL5 = float(input("Dame la calificación 5: " ))
PRO = ( CAL1 + CAL2 + CAL3 + CAL4 + CAL5 ) / 5
imprimir ( f " El promedio es { PRO } " )
|
2078b677679d7b13749a54455623cc127a9749a8 | Nscampa/hw6-costs | /hw6-costs.py | 1,312 | 4.4375 | 4 | # Function Purpose: To sum up all of the money that has been spent this week
# Parameters: None
# Return: The sum of all money
# Algorithm: Use a sentinel-controlled loop to ask the user for a cost to add to the total.
# Return the total at the end of the function.
# Assume the user only gives values that are > 0, and are numbers.
def cost_function():
total_cost = 0
day_count = 0
cost_str = input("Please enter the amount of money of spent on a day here, and enter -999 when finished:")
cost = int(cost_str)
while cost != -999:
day_count += 1
total_cost += cost
cost_str = input("Please enter the amount of money of spent on a day here, and enter -999 when finished:")
cost = int(cost_str)
average = total_cost / day_count
print"You have spent", total_cost, "dollars this week."
print"You spent on average", average, "dollars per day this week."
# Function Purpose: Main
# Parameters:
# Return: None
def main():
# Output the purpose
print("This program determines how much money on average you spend in a week")
# Find out how much money has been spent this 7-day week
# Determine the average amount of money spent each day
# Output the total money spent this week and the average per day
cost_function()
main()
|
ec014dbb877f8de1b876336c56eb15436960671e | omergamliel3/next.py-course-python | /Unit 2 - OOP/animal.py | 1,162 | 3.71875 | 4 | class Animal:
count_animals = 0
def __init__(self, name='Animal', age=0):
self._name = name
self._age = age
Animal.count_animals += 1
def __repr__(self) -> str:
return f'Name: {self._name}\nAge: {self._age}'
def birthday(self):
self._age += 1
def get_age(self):
return self._age
def set_age(self, age: int):
self._age = age
def get_name(self):
return self._name
def set_name(self, name: str):
self._name = name
@classmethod
def my_animal(cls):
return cls('Grey', 10)
@staticmethod
def class_name() -> str:
return 'Animal'
def main():
animal1 = Animal('Grey', 10)
animal2 = Animal('White', 11)
animal1.birthday()
print(f'Animal1: {animal1.get_age()}')
print(f'Animal2: {animal2.get_age()}')
print(animal1)
print(animal2)
animal3 = Animal.my_animal()
animal3.birthday()
animal3.birthday()
print(animal3)
print(Animal.class_name())
animal3.set_age(15)
animal4 = Animal()
print(f'Animals count {Animal.count_animals}')
if __name__ == "__main__":
main()
|
7e519039b56f03d97aff251649c75b29b1a11fa8 | sds1vrk/Algo_Study | /Programers_algo/sort/pro_2_fail.py | 883 | 3.5625 | 4 | #가장 큰 수 찾기
def solution(numbers):
array=[]
for i in numbers:
array.append(str(i))
if max(numbers)==0:
return '0'
array.sort(reverse=True)
print(array)
def bigo(i, j):
a = int(i + j)
b = int(j + i)
if a >= b:
return True
else:
return False
for i in range(0,len(array)-1,1):
# print(array[i])
result=bigo(array[i],array[i+1])
if result:
# new_array.append(array[i])
continue
else :
# new_array.append(array[i+1])
array[i],array[i+1]=array[i+1],array[i]
# new_array.append(array[])
print("swap",array)
answer=''
for i in array:
answer+=i
# print(answer)
return answer
solution([90,908,89,898,10,101,1,8,9])
solution([10, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) |
e0c26c39a165399b8bb9cf9a81740e4a0b115f6a | Conchristador/python-challange | /PyPoll/main.py | 1,933 | 3.625 | 4 | import os
import csv
PyPollcsv = os.path.join("Pypoll.csv")
#Set Variables and Lists
count = 0
canlist = []
unique_can = []
v_count = []
v_percent = []
#Open CSV file
with open(PyPollcsv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvreader)
#Count the variables in the csv file and add it to total count this is the total votes, add row two to canlist to get the canidates in a list
for row in csvreader:
count = count + 1
canlist.append(row[2])
# Make the varables for the math then put the varibles in the formula
# set = makes a unique set and sorted sorts them alphabetically unique can will now have each canidate once
for x in sorted(set(canlist)):
unique_can.append(x)
y = canlist.count(x) #Set the variable to count the amount of variables in canlist
v_count.append(y) #Add this to vote count for each canidate and make y the total votes for a canidate
z = (y/count)*100 #make vote percenteage
v_percent.append(z)
winning_vote_count = max(v_count)
winner = unique_can[v_count.index(winning_vote_count)]
#Get printing
print("-------------------------")
print("Election Results")
print("-------------------------")
print("Total Votes :" + str(count))
print("-------------------------")
for i in range(len(unique_can)):
print(unique_can[i] + ": " + str(round(v_percent[i])) +"% (" + str(v_count[i])+ ")")
print("-------------------------")
print("The winner is: " + winner)
print("-------------------------")
# Could not figure out how to print results to a new file. I do not beleive we went over this in class. Ask TA's for help as this is probably important.
# Ther is probably a less loop instensive way of doing this with dictionaries but I couldn't figure it out. Would probably make code more efficient. |
8fa9189e48e1f87b7dfe1fd9fa27f262914cc65a | Malukeh/comp110-21f-workspace | /exercises/ex03/find_duplicates.py | 346 | 3.6875 | 4 | """Finding duplicate letters in a word."""
__author__ = "730319407"
User_string: str = input('Enter a word:')
count: int = 0
i: int = 0
result: bool = False
while i < len(User_string):
x = i + 1
while x < len(User_string):
if User_string[i] == User_string[x]:
result = True
x += 1
i += 1
print(result) |
94ecd127e48b1005010906d82e6f6f72fd6eb702 | AntonAroche/DataStructures-Algorithms | /arrays/remove-duplicates.py | 856 | 3.765625 | 4 | # Given a sorted array nums, remove the duplicates in-place such that each element
# appears only once and returns the new length. Do not allocate extra space
# for another array, you must do this by modifying the input array in-place with O(1) extra memory.
def removeDuplicates(nums):
size = len(nums)
idx = 0
while (idx < size - 1):
if nums[idx] == nums[idx + 1]:
nums.pop(idx)
size -= 1
else:
idx += 1
return len(nums)
# This solution removes duplicates in O(n) time (since array.pop isn't used).
def removeDuplicatesIdeal(nums):
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[read - 1]:
nums[write] = nums[read]
write += 1
return write
nums = [0,0,1,1,1,2,2,3,3,4]
print(removeDuplicatesIdeal(nums))
print(nums)
|
fea3eb8962250ac66a1d519c751f53e1f5119379 | luthraG/ds-algo-war | /general-practice/11_09_2019/p6.py | 1,163 | 3.9375 | 4 | '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
'''
from timeit import default_timer as timer
import math
def prime_rwh(upper_limit, number):
primes = [True]* upper_limit
primes[0] = False
primes[1] = False
i = 3
limit = int(upper_limit ** 0.5) + 1
while i <= limit:
primes[i*i::2*i] = [False]*((upper_limit-i*i-1)//(2*i) + 1)
i += 2
count = 1
i = 3
nthPrimeNumber = -1
while i < upper_limit:
if primes[i]:
count += 1
if count == number:
nthPrimeNumber = i
break
i += 2
return nthPrimeNumber
number = int(input('Enter which prime number is required :: '))
start = timer()
primes = [2,3,5,7,11,13]
if number < 7:
nthPrimeNumber = primes[number - 1]
else:
upper_limit = int((number * math.log(number)) + (number * math.log(math.log(number))) + 3)
nthPrimeNumber = prime_rwh(upper_limit, number)
end = timer()
print('{} prime number is {}'.format(number, nthPrimeNumber))
print('Time taken is {}'.format(end - start)) |
384fdefe028d1c8f714087ac013e75c3f8038716 | matt0418/Data-Structures | /queue/queue.py | 2,457 | 4.09375 | 4 | class Node:
def __init__(self, value = None, next_node = None):
# the value at this linked list Node
self.value = value
# refernce tot he next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next_node):
self.next_node = new_next_node
class LinkedList:
def __init__(self):
#reference to the head of the list
self.head = None
#reference to the tail of the list
self.tail = None
def add_to_tail(self, value):
# init a node with a value of ValueError
new_node = Node(value, None)
# check if there is no head( i.e list is empty)
if self.tail is None:
self.head = new_node
self.tail = new_node
else:
#set the current tails next reference to our new node
self.tail.set_next(new_node)
self.tail = new_node
def remove_head(self):
# Return none if there is no head
if self.head is None:
return None
# Check to see if there is only one element
elif not self.head.get_next():
head = self.head
self.head = None
self.tail = None
return head.get_value()
else:
value = self.head
self.head = self.head.get_next()
return value.get_value()
def contains(self, value):
# if list of empty
if not self.head:
return False
else:
current = self.head
while current:
if value == current.get_value():
return True
else:
current = current.get_next()
return False
def add_to_head(self, value):
# inti node wth value of ValueError
new_node = Node(value, None)
# If list is empty
if not self.head:
self.head = new_node
self.tail = new_node
# If list only has one item
elif not self.head.get_next():
new_node.set_next = self.head
self.head = new_node
else:
prev_head = self.head
self.head = new_node
self.head.set_next(prev_head)
class Queue:
def __init__(self):
self.size = 0
# what data structure should we
# use to store queue elements?
self.storage = LinkedList()
def enqueue(self, item):
self.size += 1
self.storage.add_to_tail(item)
def dequeue(self):
if self.size == 0:
return None
else:
self.size -= 1
return self.storage.remove_head()
def len(self):
return self.size
|
bf90b1026c3dac839e35a0446a498f03d87a4a96 | wuggy-ianw/Project-Euler-py | /problem-0009.py | 1,083 | 4.3125 | 4 | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a**2 + b**2 = c**2
# For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
from itertools import combinations
from utils.generators import first
def pythagorean_triplets(length_limit):
"""
Produces integer triplets a,b,c such that a < b < c and a**2 + b**2 = c**2. Triplets are generated
based on Euclid's formula. See https://en.wikipedia.org/wiki/Pythagorean_triple#A_variant
:param length_limit: the maximum length of a and b to search up to
:return: iterator of tuples (a,b,c) in some arbitrary order
"""
for n, m in combinations(range(1, length_limit, 2), 2):
assert m > n
a, b, c = m*n, int((m**2 - n**2)/2), int((m**2 + n**2)/2)
if a > b: # ensure ordering of a < b < c
a, b = b, a
assert a < b < c
yield a, b, c
a, b, c = first(filter(lambda x: sum(x) == 1000, pythagorean_triplets(1000)))
print(a, b, c, a*b*c)
|
5ba0d9bcdb7e7190fb32b62c507dfa2f75dd62b5 | chongin12/Problem_Solving | /acmicpc.net/11966.py | 76 | 3.546875 | 4 | import math
n=int(input())
if 2**int(math.log2(n))==n:print(1)
else:print(0) |
75da13397d080fac035891a136e815b836c07659 | Caaaam/Canoe-Polo-Team-Generator-V2 | /TeamGenerator.py | 855 | 3.578125 | 4 | # This is our main file
import readfromcsv
import playerclass
import teammakerclass
# Returns players dataframe from readfromcsv module
players = readfromcsv.readplayers()
#define playerlist to contain class instances of players
playerlist = []
for row, val in players.iterrows():
playerlist.append(playerclass.player(players['Name'][row],players['Score'][row]))
# Uncomment below to see players/score
#playerclass.player.showplayer(playerlist[row])
# Calls teammakerclass to sort into even teams
Teams = teammakerclass.TeamMaker(playerlist)
# Prints teams to screen, in future, update this output
print('\nWelcome to the Team Generator V2')
teammakerclass.TeamMaker.getteams(Teams)
print(f'\nThis attempts the algorithm {teammakerclass.TeamMaker.getiterations(Teams)} times and returns the best result.\n') |
bb32a6ff2284110025f78413c8de4dbb3f89d1cd | mikelitu/DSCUSB | /DSCUSBSensor.py | 2,598 | 3.5 | 4 | import ctypes
class Sensor():
def __init__(self, COMPort):
"""
:param COMPort (int): The port where the DSCUSB is located in your computer
This function loads the library containing the functions to establish an ASCII connection with the DSCUSB,
and opens the port to start sending commands
"""
print("Creating connection with DSCUSB Sensor at COM", COMPort)
self.dll = ctypes.WinDLL("C:\\Windows\\System32\\MantraASCII2Drv.dll")
isOpen = self.dll.OPENPORT(
ctypes.c_int (COMPort),
ctypes.c_long (115200)
)
if isOpen==0:
print("The connection is established!")
else:
self.GetErrors(isOpen)
def close(self):
"""
Closes the port and ends the connection
"""
isClose = self.dll.CLOSEPORT()
if isClose==0:
print("Connection finished")
else:
self.GetErrors(isClose)
def readvalue(self):
"""
:return: The value of the load cell
This function generates a command to ask for the value in the load cell. In this case, the command will be SYS
corresponding to the main output. It automatically transforms the value back to a Python floating variable.
"""
command = ctypes.create_string_buffer(255)
command.value = b"SYS"
result = ctypes.c_float(0.0)
value = self.dll.READCOMMAND(
ctypes.c_int(1),
command,
ctypes.byref(result)
)
if value==0:
return result.value
else:
self.GetErrors(value)
def version(self):
return self.dll.VERSION()
def GetErrors(self, value):
"""
:param value: The values return by the MantraASCII2Drv.dll
:return: Returns the type of error the program has
"""
if value == -1:
raise ValueError("Invalid argument value in function call")
elif value == -2:
raise ValueError("Cannot open or close serial port")
elif value == -100:
raise ValueError("No response")
elif value == -200:
raise ValueError("Invalid station number in response")
elif value == -300:
raise ValueError("Invalid checksum")
elif value == -400:
raise ValueError("Not acknowledge (NAK)")
elif value == -500:
raise ValueError("Invalid reply length")
|
b9cae5cc0317174a10ebac44b39499bc607dc7ae | stevjain37/Profile | /headTails.py | 532 | 3.578125 | 4 | import numpy as np
def coinFlip(p):
result = np.random.binomial(1,p)
#adds result to numpy array
return result
probability = .5
inquireFlips = input("How many flips?")
n = int(inquireFlips)
#initiate array
fullResults = np.arange(n)
for i in range(0,n):
fullResults[i] = coinFlip(probability)
i += 1
print("probability is set to ", probability)
print("Tails = 0, Heads = 1: ", fullResults)
print("Head Count: ", np.count_nonzero(fullResults == 1))
print("Tail Count: ", np.count_nonzero(fullResults == 0))
|
24264b6d4e5222fb46e3cc7a3ec7f7cac1a6be88 | smudugal/ValidPhoneNumber | /test_validphone.py | 972 | 3.765625 | 4 | import unittest
import validphone
class TestValidPhone(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
def test_valid_phone_num(self):
num = "333-333-3333"
self.assertTrue(validphone.telephone_check(num))
num = "(123)555-5555"
self.assertTrue(validphone.telephone_check(num))
num = "(123) 555-5555"
self.assertTrue(validphone.telephone_check(num))
num = "333 333 3333"
self.assertTrue(validphone.telephone_check(num))
num = "3333333333"
self.assertTrue(validphone.telephone_check(num))
num = "1 333 333 3333"
self.assertTrue(validphone.telephone_check(num))
def test_letters(self):
num = "333-abc-3333"
self.assertFalse(validphone.telephone_check(num))
def test_special_chars(self):
num = "$325678908"
self.assertFalse(validphone.telephone_check(num))
if __name__ == '__main__':
unittest.main()
|
095cf9940781f4cab04e2ab7914c9ea700824632 | mawande21/class-py | /main.py | 588 | 4.125 | 4 | class Bus:
'''this class defines how a bus looks like'''
count = 0
def __init__(self, driver, color,seats):
self.driver= driver
self.num_of_seats= seats
self.color = color
self.bus_count()
def set_color(self,color):
self.color = color
def num_of_seats(self,seats):
self.seats=seats
def bus_count(self):
self.count = self.count + 1
bus = Bus("Masande",66,"Yellow")
bus.num_of_seats = 45 #update the seats
bus.set_color('Red') #update the bus color
print(bus)
print(bus.count)
|
e2a0fb395a65e624c80c58a54332550bc595e7aa | thirihsumyataung/Python_Tutorials | /function_box_rectangle.py | 234 | 4.09375 | 4 | def area_Box(length , width):
area = length * width
print("Area of the Box is : " + str(area))
area_Box(5,6.0)
length = float(input("Length of the box : "))
width = float(input("Width of the box : "))
area_Box(length, width) |
99be0a95548104762aae10dac062761d4baac436 | Shanil98/haarCascade_Car-Pedestrian_detector | /Detection_Driving.py | 1,421 | 3.5625 | 4 | import cv2
# our image or video
#img_file = 'dashCam.jpeg'
vid = 'dashcam1.mp4'
# our pre-trained car classifier and pre-trained pedestrian classififer
car_tracker_file = 'car_detector.xml'
pedestrian_tracker_file = 'haarcascade_fullbody.xml'
# create opencv image, it reads the image to read it correctly
#img = cv2.imread(img_file)
# create car and pedestrian classifiers
car_tracker = cv2.CascadeClassifier(car_tracker_file)
pedestrian_tracker = cv2.CascadeClassifier(pedestrian_tracker_file)
video = cv2.VideoCapture(vid)
while True:
successful_frame_read, frame = video.read()
if successful_frame_read:
# convert the vid to grayscale
black_n_white = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
break
# detect cars and pedestrians
cars = car_tracker.detectMultiScale(black_n_white)
pedestrians = pedestrian_tracker.detectMultiScale(black_n_white)
for (x, y, w, h) in cars:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
for (x, y, w, h) in pedestrians:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
# display the square when the car is spotted in the frame
cv2.imshow('heres the video', frame)
# waitKey is necessary to display the image, till you hit a key
key = cv2.waitKey(1)
# checking key agains ASCII for Q or q
if key == 81 or key == 113:
break
print('code completed')
|
74332f358b9fff9d954c0c0329d934c5868f692c | ashwinm2/Challenges | /subsequent_words_binary_add.py | 628 | 3.78125 | 4 | # Implementing the all subsequent words for given basestring
# Binary Addition
def compute(temp_lt, pointer):
flag = 0
check_lt = [1 for x in temp_lt]
if temp_lt[pointer] == 0:
temp_lt[pointer] = 1
elif temp_lt == check_lt:
pass
else:
temp_lt[pointer] = 0
temp_lt = compute(temp_lt, pointer - 1)
return temp_lt
def iter(str):
temp_lt = [0 for x in str]
check_lt = [1 for x in str]
while temp_lt != check_lt:
temp_lt = compute(temp_lt, len(temp_lt) - 1)
words = ''
for x in range(0,len(temp_lt)):
if temp_lt[x] == 1:
words += str[x]
print words
str = list(raw_input())
print str
iter(str)
|
210740ed5a634c7800f4a52ee49d9b081fab99b4 | hydrahs/golden_mine | /exercise_1.py | 234 | 4.0625 | 4 |
def myFunction(str):
array = list(str)
array_1 = array.reverse
if (array==array_1):
return True
else:
return False
print(myFunction(str = "dsfasdf"))
""" str.join(array.reverse)
print(str) """ |
a8cb384dc0440a3f8ae962d3c543af8e179fa9cd | riteshelias/UMC | /ProgramFlow/guessgame.py | 1,734 | 4.125 | 4 | import random
answer = random.randint(1, 10)
print(answer)
tries = 1
print()
print("Lets play a guessing game, you can exit by pressing 0")
guess = int(input("try count - {}. Please enter a number between 1 and 10: ".format(tries)))
while guess != answer:
if guess == 0:
print("Bye, have a nice day!")
break
if tries == 5:
print("You have reached your guess limit. Bye!")
break
tries += 1
guess = int(input("try count - {}. Please enter a number between 1 and 10: ".format(tries)))
else:
if tries == 1:
print("Wow, correct guess at the first time!")
else:
tries += 1
print("You took {} tries to guess right!".format(tries))
# if guess == answer:
# print("Woah! You got that right at the first go!")
# else:
# if guess < answer:
# print("Please guess a higher number")
# else:
# print("Please guess a lower number")
# guess = int(input("Try again: "))
# if guess == answer:
# print("You get it finally")
# else:
# print("Oops! Still wrong!")
# if guess != answer:
# if guess < answer:
# print("Please guess a higher number")
# else:
# print("Please guess a lower number")
# guess = int(input("Guess again: "))
# if guess == answer:
# print("You finally got it")
# else:
# print("Sorry, you still didn't get it")
# else:
# print("Woah! You got it right the first time")
# if guess < 1 or guess > 10:
# print("The entered number is not in the requested range")
# elif guess < answer:
# print("Please guess a higher number")
# elif guess > answer:
# print("Please guess a lower number")
# else:
# print("You guessed right!")
|
ceb4632cb6d2ddd46ac1c532f18a5e6fea6bc1fc | oreqizer/pv248 | /12/frames.py | 1,711 | 3.9375 | 4 | import pandas as pd
import math
# The data for this exercise is in ‹frames.csv›. The data represents
# grading of this very subject (with made-up names and numbers, of
# course). The columns are names, number of points from weekly
# exercises, from assignments and from reviews. Implement the
# following functions:
# Return a DataFrame which only contains rows of students, which
# achieved the best result among their peers in one of the
# categories (weekly, assignments, reviews). If there are multiple
# such students for a given category, include all of them.
def best( data ):
pass
# Return a DataFrame which contains the name and the total score (as
# the only 2 columns). Don't forget that the weekly exercises
# contribute at most 9 points to the total.
def compute_total( data ):
pass
# Return a dictionary with 4 keys ('weekly', 'assignments', 'reviews'
# and 'total') where each value is the average number of points in
# the given category. Consider factoring out a helper function from
# compute_total to get a DataFrame with 5 columns.
def compute_averages( data ):
pass
# Test utilities and tests follow.
def eq( data, student, col, val ):
matches = data[ data[ 'student' ] == student ][ col ]
return ( matches == val ).all()
def test_main():
df = pd.read_csv( 'frames.csv' )
assert len( best( df ) ) == 5
tot = compute_total( df )
assert eq( tot, 'Věra Hrbáčková', 'total', 18 )
assert eq( tot, 'Blanka Pichrtová', 'total', 17.4 )
avg = compute_averages( df )
assert math.isclose( avg['weekly'], 61/9 )
assert math.isclose( avg['assignments'], 245/36 )
assert math.isclose( avg['reviews'], 87/90 )
if __name__ == '__main__':
test_main()
|
7320010cead35e71307e2da7aa6093e7a49d4503 | ajgrinds/adventOfCode | /2020/day05.py | 1,125 | 3.765625 | 4 | # Advent Of Code 2020 Day 5 Answer
# Code by: Andrew Grindstaff
# https://adventofcode.com/2020/day/5
def main():
file = open("input.txt").read().splitlines()
a = set()
part_2 = 0
# Part 1: Converts the string of F, B, L and R to a binary number, then gets the decimal version - saves
# it in a list and stores the highest one
for x in file:
string = x.replace("F", "0").replace("B", "1").replace("L", "0").replace("R", "1")
num = int(string, 2)
a.add(num)
part_1 = len(a)
# Part 2: A simple for loop to go through the list and find which value is not in it
for y in a:
if y - 1 not in a and y - 2 in a:
part_2 = y - 1
print(f"Part 1: {part_1}")
print(f"Part 2: {part_2}")
def one_line():
print("Part 1: (one line)")
print(max(int(x.translate({70:48,66:49,76:48,82:49}),2) for x in open("input.txt").readlines()))
print("Part 2: (one line)")
print((max(y:=[int(x.translate({70:48,66:49,76:48,82:49}),2) for x in open("input.txt").readlines()])**2+max(y)-min(y)**2+min(y))/2-sum(y))
if __name__ == '__main__':
main()
|
400526da0cf90a4bae999cf9c503fa3b985f8fc0 | pau1fang/learning_notes | /数据结构与算法/剑指offer_python语言/question36_二叉搜索树与双向链表.py | 1,107 | 3.984375 | 4 | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def convert(root):
last_node = [None]
convert_node(root, last_node)
head_of_list = last_node[0]
while head_of_list is not None and head_of_list.left is not None:
head_of_list = head_of_list.left
return head_of_list
def convert_node(node, last_node):
if node is None:
return
if node.left is not None:
convert_node(node.left, last_node)
node.left = last_node[0]
if last_node[0]:
last_node[0].right = node
last_node[0] = node
if node.right is not None:
convert_node(node.right, last_node)
tree = Node(10)
tree.left = Node(6)
tree.right = Node(14)
tree.left.left = Node(4)
tree.left.right = Node(8)
tree.right.left = Node(12)
tree.right.right = Node(16)
head = convert(tree)
print()
rear = None
while head:
print(head.val, end=' ')
head = head.right
if head is not None and head.right is None:
rear = head
print()
while rear:
print(rear.val, end=' ')
rear = rear.left
|
4cf6cade9d4aefe4399ddbbd278290a0f2723c02 | Ramune6110/Machine-learnig | /Logistic-Regression.py | 4,668 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[17]:
# ニュートン法
import numpy as np
import matplotlib.pyplot as plt
class Newton:
def __init__(self, n, w, lamda, iteration):
# parameter
self.n = n
self.w = w
self.lamda = lamda
self.iteration = iteration
def draw(self, w_stack, eval_stack):
plt.figure(1)
plt.plot(w_stack, eval_stack, 'ro-', linewidth=0.5, markersize=0.5, label='newton')
plt.legend()
plt.xlabel('wight')
plt.ylabel('loss')
plt.figure(2)
show_iter = 50
plt.plot(np.abs(w_stack[:show_iter] - self.w), 'ro-', linewidth=0.5, markersize=1, label='seepest')
plt.legend()
plt.yscale('log')
plt.xlabel('iter')
plt.ylabel('diff from the gold weight')
def main(self):
# noise
omega = np.random.randn()
noise = np.random.randn(self.n)
# 2次元入出力データ
x = np.random.randn(self.n, 2)
y = 2 * (omega * x[:, 0] + x[:, 1] + noise > 0) - 1
# 値格納用メモリ
w_stack = np.zeros(self.iteration)
eval_stack = np.zeros(self.iteration)
# main loop
for t in range(self.iteration):
# 事後確率
posterior = 1 / (1 + np.exp(-y * (self.w * x[:, 0] + x[:, 1])))
# 勾配方向(**a1) 評価関数をwについて一回微分したもの
grad = 1 / self.n * np.sum((1 - posterior) * y * x[:, 0]) + 2 * self.lamda * self.w
# ヘッセ行列(**a1) 評価関数をwについて二回微分したもの
hess = 1 / self.n * np.sum(posterior * (1 - posterior) * x[:, 0] ** 2) + 2 * self.lamda
# 評価関数の値(p22)
J = 1 / self.n * np.sum(np.log(1 + np.exp(-y * (self.w + x[:, 0] + x[:, 1])))) + self.lamda * (self.w ** 2)
# 値の格納
w_stack[t] = self.w
eval_stack[t] = J
# 重み更新のための勾配方向 d (p35)
d = - grad / hess
# step size
s = 1.0 / np.sqrt(t + 10)
# 重み更新
self.w = self.w + s * d
# draw graph
self.draw(w_stack, eval_stack)
# data number, weight, lamda, iteration number, step size
newton = Newton(100, 3, 0.1, 300)
newton.main()
# In[18]:
# 最急降下法
import numpy as np
import matplotlib.pyplot as plt
class Steepest:
def __init__(self, n, w, lamda, iteration, alpha):
# parameter
self.n = n
self.w = w
self.lamda = lamda
self.alpha = alpha
self.iteration = iteration
def draw(self, w_stack, eval_stack):
plt.figure(1)
plt.plot(w_stack, eval_stack, 'bo-', linewidth=0.5, markersize=0.5, label='steepest')
plt.legend()
plt.xlabel('wight')
plt.ylabel('loss')
plt.figure(2)
show_iter = 50
plt.plot(np.abs(w_stack[:show_iter] - self.w), 'bo-', linewidth=0.5, markersize=1, label='seepest')
plt.legend()
plt.yscale('log')
plt.xlabel('iter')
plt.ylabel('diff from the gold weight')
def main(self):
# noise
omega = np.random.randn()
noise = np.random.randn(self.n)
# 2次元入出力データ
x = np.random.randn(self.n, 2)
y = 2 * (omega * x[:, 0] + x[:, 1] + noise > 0) - 1
# 値格納用メモリ
w_stack = np.zeros(self.iteration)
eval_stack = np.zeros(self.iteration)
# main loop
for t in range(self.iteration):
# 事後確率
posterior = 1 / (1 + np.exp(-y * (self.w * x[:, 0] + x[:, 1])))
# 勾配方向(**a1) 評価関数をwについて一回微分したもの
grad = 1 / self.n * np.sum((1 - posterior) * y * x[:, 0]) + 2 * self.lamda * self.w
# 評価関数の値(p22)
J = 1 / self.n * np.sum(np.log(1 + np.exp(-y * (self.w + x[:, 0] + x[:, 1])))) + self.lamda * (self.w ** 2)
# 値の格納
w_stack[t] = self.w
eval_stack[t] = J
# step size
s = 1.0 / np.sqrt(t + 10)
# 重み更新
self.w = self.w - self.alpha * s * grad
# draw graph
self.draw(w_stack, eval_stack)
# data number, weight, lamda, iteration number, step size
steepest = Steepest(100, 3, 0.1, 300, 1)
steepest.main()
# In[ ]:
|
d2cd61433e3264f38f57ba81166f941a15f7b91e | pcomo24/DigitalCrafts-work | /part1ex5.py | 201 | 4.03125 | 4 | day = int(input('Day (0-6)? '))
#print({day}).format("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
if day == 0 or 6:
print("Sleep in")
else:
print("Go to work")
|
5d38b8b3ce98f10d0c2bbb92ea808cfdee0277a4 | daniel-reich/ubiquitous-fiesta | /CD5nkQ6ah9xayR3cJ_4.py | 77 | 3.75 | 4 |
def add_odd_to_n(n):
return sum([i for i in range(n + 1) if i % 2 != 0])
|
5e694a438d68a89d264bcbc8dcba06bc1aa4c6e8 | Elixeus/BigData | /project/bigDataFinal.py | 2,524 | 3.6875 | 4 | from string import punctuation, maketrans
import sys
def eventWordCount(index, lines):
'''
author: Xia Wang
This function maps the candidates of each election cycle and return a
tuple of (candidate name, media attitude). It first makes sure the
encoding is utf-8 because there are characters like e' that cannot be
decoded by the ancsii codec. Then it parse the http string (last column
of the input files) to find out if the last name of a candidate is present.
For the rows where candidate names are present, the name of the candidate and
the media attitude towards it will be output as a tuple.
TODO: The function uses a list of corresponding candidate names. Decide whether
to create this list internally to each map script and use a different map script
for each election cycle, or to create a csv file with the list provided. Also
modify the __main__ part, specify how the map takes place.
parameters:
----------------------
index: the index of the input file
lines: the content of the row
'''
ls = set(['clinton', 'sanders', 'trump', 'cruz', 'rubio'])
# do something about this list
import csv
from string import punctuation, maketrans
import itertools
if index == 0:
lines.next()
reader = csv.reader(itertools.imap(lambda x: x.encode('utf-8'), lines),
delimiter='\t')
for row in reader:
(day, score, url) = (row[1], row[34], row[-1])
# find the corresponding info
# change all punctuations to comma, change all
# letter case to lower, and split the words
words = set(url.lower()
.translate(maketrans(punctuation,
',' * len(punctuation)))
.split(','))
if len(ls.intersection(words)) == 1:
# ls is a set that contains all the relevant candidate names
for candidate in list(ls.intersection(words)):
yield (candidate, float(score), day)
if __name__ == '__main__':
# sc = pyspark.SparkContext()
events = sc.textFile('20160425.export.CSV')
# !!!!!!!do something here!!!!!!! events is the textFile RDD
attitude = events.mapPartitionsWithIndex(eventWordCount).mapValues(lambda x:
(x, 1)) \
.reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1]))
# print counts
attitude.saveAsTextFile('output3.txt')
|
15eda0a573fd5c355da02c34506a8e6cc7532fac | dwkang707/BOJ | /python3/(18238)BOJ.py | 467 | 3.671875 | 4 | input_data = input()
location = int(ord('A'))
time = 0
# ord 내장 함수는 ASCII code를 반환하는 함수
# abs(int(ord(i)) - location)는 시계방향
# abs(26 - abs(int(ord(i)) - location))는 반시계방향
for i in input_data:
if abs(int(ord(i)) - location) < abs(26 - abs(int(ord(i)) - location)):
time += abs(int(ord(i)) - location)
else:
time += abs(26 - abs(int(ord(i)) - location))
location = int(ord(i))
print(time)
|
e02942eb84a9eadceec5b9d3faaf68693aabdb7b | AswiniSankar/pattern | /pattern1.py | 731 | 3.5 | 4 | '''
*
* *
* * *
* * * *
'''
n=int(input())
for i in range(1,n+1):
for j in range(i,n):
print(end=" ")
for k in range(1,i+1):
print("*",end=" ")
print("\r")
'''
1
1 2
1 2 3
1 2 3 4
'''
n=int(input())
for i in range(1,n+1):
for j in range(i,n):
print(end=" ")
for k in range(1,i+1):
print(k,end=" ")
print("\r")
'''
1
2 3
4 5 6
7 8 9 10
'''
n=int(input())
t=1
for i in range(1,n+1):
for j in range(i,n):
print(end=" ")
for k in range(1,i+1):
print(t,end=" ")
t=t+1
print("\r")
'''
A
B C
D E F
G H I J
'''
n= int(input())
t=65
for i in range(1,n+1):
for j in range(i,n):
print(end=" ")
for k in range(1,i+1):
u=chr(t)
print(u,end=' ')
t=t+1
print("\r")
|
c21881534c9c6fa6627404561cc57291bd261f8a | dvalp/coding-practice | /hackerrank/python_intro.py | 522 | 4.21875 | 4 | def print_to_N():
'''
The challenge was to write a function that could take a given integer
and print all the numbers leading up to it without any spaces.
Two interesting things are happening here. First, the '*' is unpacking
the generator created by range and passing the elements individually.
Second, I find it interesting that you can tell print how to separate
the elements, and in this case not separate them at all.
'''
N = int(input())
print(*range(1, N + 1), sep='')
|
52b28892a10c6c1e4ca943050dd5f2b5bc653ba3 | luisalourenco/AdventOfCode2019 | /24/part2.py | 5,683 | 3.53125 | 4 | import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
f = func(*args, **kwargs)
print(f'The function ran for {time.time() - start} s')
return f
return wrapper
def printMap(map, level = None, iteration = None, fileMode = True):
if fileMode:
file1 = open("MyFileAll.txt","a")
if iteration != None:
file1.write("Time: "+str(iteration))
file1.write("\n")
if level != None:
file1.write("Level "+str(level))
file1.write("\n")
for l in map:
for j in range(len(l)):
file1.write(l[j])
file1.write("\n")
file1.write("\n")
file1.write("\n")
file1.close()
def bugsInAdjacentTilesLowerLevel(map, border):
# -1, 0 - lower border
# 0, -1 - upper border
# -1, -1 - right border
# -2, -2 - left border
bugs = 0
if border == 'DOWN':
for i in range(5):
if map[4][i] == '#':
bugs += 1
if border == 'UP':
for i in range(5):
if map[0][i] == '#':
bugs += 1
if border == 'RIGHT':
for i in range(5):
if map[i][4] == '#':
bugs += 1
if border == 'LEFT':
for i in range(5):
if map[i][0] == '#':
bugs += 1
return bugs
def bugsInAdjacentTilesUpperLevel(map, x, y):
bugs = 0
if map != None:
left = map[2][1]
right = map[2][3]
up = map[1][2]
down = map[3][2]
if x == 0:
if left == '#':
bugs += 1
if y == 0:
if up == '#':
bugs += 1
if x == 4:
if right == '#':
bugs += 1
if y == 4:
if down == '#':
bugs += 1
return bugs
def bugsInAdjacentTiles(map, x, y, levels, level):
bugs = 0
size = 5
upperMap = levels.get(level + 1)
bugs += bugsInAdjacentTilesUpperLevel(upperMap, x, y)
lowerLevel = levels.get(level-1)
if lowerLevel != None:
if (x,y) == (2,1): # upper
bugs += bugsInAdjacentTilesLowerLevel(lowerLevel, 'UP')
if (x,y) == (1,2): # left
bugs += bugsInAdjacentTilesLowerLevel(lowerLevel, 'LEFT')
if (x,y) == (3,2): # right
bugs += bugsInAdjacentTilesLowerLevel(lowerLevel, 'RIGHT')
if (x,y) == (2,3): # down
bugs += bugsInAdjacentTilesLowerLevel(lowerLevel, 'DOWN')
if y != 0:
if map[y-1][x] == '#':
bugs += 1
if y != size -1:
if map[y + 1][x] == '#':
bugs += 1
if x != 0:
if map[y][x - 1] == '#':
bugs += 1
if x != size -1:
if map[y][x + 1] == '#':
bugs += 1
return bugs
def mutation(levels, levelSize, iteration):
size = 5
newLevels = {}
for level in range(-levelSize, levelSize):
# current map
map = levels.get(level)
# map after mutation
newMap = [ [ '.' for i in range(5) ] for j in range(5) ]
for y in range(size):
for x in range(size):
unchanged = True
if (x,y) != (2,2):
# count bugs in adjacent tiles, including edge cases with lower and upper level
numBugs = bugsInAdjacentTiles(map, x, y, levels, level)
# bug dies unless there is exactly one bug adjacent to it
if map[y][x] == '#' and numBugs != 1:
newMap[y][x] = '.'
unchanged = False
# empty space becomes infested with a bug if exactly one or two bugs are adjacent to it
if map[y][x] == '.' and (numBugs == 1 or numBugs == 2):
newMap[y][x] = '#'
unchanged = False
# otherwise, nothing changes
if unchanged:
newMap[y][x] = map[y][x]
#end for
#end for
# update current level's map
newLevels[level] = newMap.copy()
# printing map for debugging
if level == -levelSize:
printMap(newMap, level, iteration+1)
else:
printMap(newMap, level)
return newLevels
def countBugsAllLevels(levels):
bugs = 0
for map in levels.values():
for y in range(5):
for x in range(5):
if map[y][x] == '#':
bugs += 1
return bugs
@timer
def part2(map, iterations, size):
levels = {}
# init levels maps for -size..size
for i in range(-size, size):
level = [ [ '.' for i in range(5) ] for j in range(5) ]
level[2][2] = '?'
levels[i] = level
levels[0] = map
newLevels = levels.copy()
for i in range(iterations):
# feed next iteration with resulting levels maps
newLevels = mutation(newLevels, size, i)
# count bugs for all levels
print(countBugsAllLevels(newLevels))
filepath = 'input.txt'
with open(filepath) as fp:
line = fp.readline().strip()
map = [ [ '.' for i in range(5) ] for j in range(5) ]
j = 0
while line:
map[j] = list(line)
j += 1
line = fp.readline().strip()
#end while
# part2(map, iterations, size)
part2(map, 200, 110)
|
097270984b4389d5dc12526d5977aa657a0e4528 | UtkuAraal/Mini-Python-Projects | /Kayıt Ve Giriş/Arayüz.py | 1,349 | 3.984375 | 4 | from Kullanıcı import *
app = App()
def valudation(email):
if email.find("@") != -1 and email.endswith(".com"):
return True
else:
return False
print("Welcome to our program!")
while True:
print("1- Login\n2- Register")
choose = input("Your choose: ")
if choose == "q":
print("See you!")
app.diconnect()
break
elif choose == "1":
email = input("E-mail: ").strip()
password = input("Password: ").strip()
app.login(email, password)
elif choose == "2":
username = input("Username: ").strip()
email = input("E-mail: ").strip()
if not (valudation(email)):
print("İt isn't real email! Try again!")
continue
password = input("Password: ").strip()
app.register(username, email, password)
while app.who != "":
print("1- List of all user\n2- Delete an account\n3- Find an account")
choose = input("Would you like to see? (yes, no) (quit = 'q')")
if choose == "yes":
app.all_user()
elif choose == "q":
app.who = ""
elif choose == "2":
username = input("Username: ")
app.delete_account(username)
elif choose== "3":
username = input("Username: ")
app.find_account(username)
|
1635448cfe9e94d5830a564d91047ceee4e1805b | JamesLawrence30/FinancialExploration | /mongoQuotesDB/oldVersions/firstVersion.py | 1,154 | 3.625 | 4 | import requests;
import collections;
"""import json;"""
alphaVantageKey = "0ZU6NM5CMUSMR7DO"
def makeRequest(symbol):
#create api call string below. receive time series from api
request = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol="+symbol+"&outputsize=compact&datatype=json&apikey="+alphaVantageKey
response = requests.get(request)
#my own key used. output size compact is last 100 datapoints..full is last 20+ yrs of data
responseBody = response.content; #remove header from time series
return responseBody;
def updateMongo(responseBody):
print(responseBody);
#this needs to connect to mongodb
#for every day in response body, add the data to collection timeSeries
#wil then be able to filter for the close prices from each day's data
###each day is a "file"?? in the collection
def main():
responseBody = makeRequest("MSFT"); #structure api call by passing in a ticker symbol
#evenrually pull hidden secret api key from another file that won't go on git.
updateMongo(responseBody);
#Tell python to call main function first
if __name__ == "__main__":
main()
|
dfa37f5383aeb294e3729f44264d9020cd22d808 | laippmiles/Leetcode | /20_有效的括号.py | 1,469 | 3.875 | 4 | '''
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
'''
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
#应该是第一次做了栈相关的题?
#还算好理解
#循环字符串,遇左括号入栈。
#遇右括号,从栈顶取元素然后配对,判断配对结果。
#最后再判断栈是否不为空。
res = []
left = ['(', '[', '{']
right = [')', ']', '}']
pair = ['()', '[]', '{}']
for i in s:
if i in left:
res.append(i)
#左括号入栈
else:
if res == []:
return False
#防止栈是空的,写一个判断
tep = res.pop() + i
#右括号出栈配对
if tep not in pair:
return False
if len(res) != 0:
return False
#最后判断是否是空栈
return True |
5da053e7f13052d6790ecec2f497ada2d06ec4a0 | quartox/AXA-Driver-Telemetrics | /loopTiming.py | 890 | 4 | 4 | """Computes the estimate when a loop will be finished."""
__author__="Jesse Lord"
__date__="March 14, 2015"
import time
def timeInit():
return time.time()
def extrapolateEnd(inittime,totaliter,index):
current = time.time()
secperiter = (current-inittime)/float(index)
remainingsec = (totaliter-index)*secperiter
return time.localtime(remainingsec+current)
def loopTiming(inittime,totaliter,index):
if index == 1 or index == 2 or index == 10:
endingtime = extrapolateEnd(inittime,totaliter,index)
print "After,",index,"iteration(s) the loop expected to finish at",time.strftime('%X',endingtime),"on",time.strftime('%x',endingtime)
if index == totaliter/2:
endingtime = extrapolateEnd(inittime,totaliter,index)
print "Halfway done. The loop expected to finish at",time.strftime('%X',endingtime),"on",time.strftime('%x',endingtime)
|
d19778411d4451d09d3a9d53f7521731e4387e8f | sCAIwalker/InterviewPreparation | /TreeRepresentations.py | 317 | 3.65625 | 4 | #Regular Tree
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, obj):
self.children.append(obj)
#Binary Tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None |
f490a789fca3e73effb87b210dec0145c8256316 | sambapython/batch78 | /log.py | 976 | 3.90625 | 4 | import logging
logging.info("strt the program")# it's already configured the default basic Config. It will not consider
# any config later
#NOTE: what ever the basic config writing it, make sure that will execute before executing any log message.
logging.basicConfig(level=logging.DEBUG,
filename="log.txt", format="%(asctime)s->%(levelname)s==>%(message)s")
n1=input("Entere a number:")
n2=input("Enter a numebr:")
logging.debug(f"before conversion: n1={n1}, n2={n2}")
try:
n1=int(n1)
n2=int(n2)
logging.debug(f"after conversion: n1={n1}, n2={n2}")
res=n1/n2
print(f"result={res}")
logging.debug(f"result={res}")
except ZeroDivisionError as err:
logging.error("ERROR: %s"%err)
print("expecting second number not equals to zero")
except ValueError as err:
logging.error("ERROR: %s"%err)
print("expecting only the digits.")
except Exception as err:
logging.error("ERROR:some issue")
print("ERROR: %s"%err)
logging.info("end") |
4f61b26e71cc54bd599364c19e9413227d7c6586 | sagarnikam123/learnNPractice | /hackerEarth/practice/dataStructures/advancedDataStructures/suffixArrays/catsSubstrings.py | 1,604 | 3.796875 | 4 | # Cats Substrings
#######################################################################################################################
#
# There are two cats playing, and each of them has a set of strings consisted of lower case English letters.
# The first cat has N strings, while the second one has M strings. Both the first and the second cat will choose
# one of it's strings and give it to you. After receiving two strings, you will count the number of pairs of
# equal substrings that you can choose in both strings, and send this number back to the cats. (Note that two
# occurences of the same substring are considered different. For example, strings "bab" and "aba" have 6 such pairs.)
# The cats are going to give you all N * M possible pairs. They are interested in the total sum of numbers
# received from you. Your task is to find this number.
#
# Input format
# The first line of the input contains the integer N. The next N lines contain the first cat's strings,
# one string per line. The next line contain the integer M, and after that the next M lines contain the second
# cat's strings, one string per line as well.
#
# Output format
# In one line print the answer to the problem.
#
# Constraints
# 1 <= N, M <= 100,000 , the total length of each cat strings set will not exceed 100,000.
# All strings in the input will be non-empty.
#
# SAMPLE INPUT
# 2
# ab
# bab
# 2
# bab
# ba
#
# SAMPLE OUTPUT
# 18
#
#######################################################################################################################
|
1b06ebb55b9210a3d863aadf9256a34098996f9e | drewplant-MIDS/W205 | /exercise_2/scripts/histogram.py | 2,284 | 3.65625 | 4 | """
Python source code - search through postgresql table to find number of occurrences of particular word
Usage:
python histogram k1 k2
=========================
where:
k1, k2 Bin limits for number of occurrences for words
where k1 > k2
Output: all words occurring between k1 and k2 times in the database.
"""
# Import code:
import psycopg2
import sys
import pprint
import argparse # For easy argument parsing
# Usage
parser = argparse.ArgumentParser(description='Locate words with wordcount in given bin range')
parser.add_argument("k1", type=int, help='k1 is min bin count for word' )
parser.add_argument("k2", type=int, help='k2 is max bin count for word and k1 <= k2' )
# Produce an args object
args = parser.parse_args()
Usage = 'Usage: python histogram.py k1 k2\n\
where k1, k2 = bin values for word counts in database\n\
and 0 < k1 <= k2'
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
# Error checking:
if not (args.k1 <= args.k2):
print "\n"
print "Error: k1 must be < or = to k2!"
print Usage
print "\n"
exit()
elif not (args.k1 > 0):
print "\n"
print "Error: k1 and k2 must be greater than 0!"
print Usage
print "\n"
exit()
# Setup cursor object for doing postgresql querying
# # Create a new connect object
conn = psycopg2.connect(database="tcount", user="postgres", password="", host="localhost", port="5432")
# # Create a cursor
cur = conn.cursor()
# Either search for all words in table or only one word in table...
if args.k1 == args.k2:
cur.execute("SELECT word, count from Tweetwordcount WHERE count=%s ORDER BY count desc;", (args.k1,))
else:
cur.execute("SELECT word, count from Tweetwordcount WHERE (count>=%s) AND (count<=%s) ORDER BY count desc;", (args.k1,args.k2))
ReturnRecords = cur.fetchall()
if len(ReturnRecords) > 0:
print "\n"
OutString = ""
for Tuple in ReturnRecords:
OutString += " " + Tuple[0] + ": " + str(Tuple[1]) + "\n"
print OutString
print "\n"
else:
print "\n"
print "No words found in database with counts of k1 = %d and k2 = %d" %(args.k1,args.k2)
print "\n"
# # Close the cursor
conn.close()
|
14c9636420c5db250525c7ed26bfd380841300db | DanMayhem/project_euler | /058.py | 1,620 | 4.0625 | 4 | #!python
"""
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
"""
from functools import lru_cache
from math import floor, sqrt
def nw_diags(n):
for i in range(3, n+1, 2):
yield i*i - 2*i + 2
def sw_diags(n):
for i in range(3,n+1,2):
yield i*(i-1)+1
def se_diags(n):
for i in range(1,n+1,2):
yield i*i
def ne_diags(n):
for i in range(3, n+1, 2):
yield (i-2)**2 + i - 1
@lru_cache(maxsize=None)
def is_prime(n):
if n < 2:
return False
for i in range(2,floor(sqrt(n))+1):
if n%i==0:
return False
return True
if __name__=="__main__":
diags = set([1])
prime_count = 0
diags_count = 1
for i in range(3, 100001, 2):
if is_prime(i*i -2*i +2):
prime_count += 1
if is_prime(i*(i-1)+1):
prime_count += 1
if is_prime((i-2)**2 + i - 1):
prime_count += 1
diags_count += 4
prime_pcnt = prime_count / diags_count
print("{0}: {1}".format(i, prime_pcnt))
if prime_pcnt <= .1:
exit()
|
ec0e131b746d2bd8093d91236ab43c7702bb7053 | ZL4746/Basic-Python-Programming-Skill | /Second_Part/Practice_Assignment/01_Dice.py | 1,285 | 3.796875 | 4 |
def graphy(list1):
list2 = []
larggest = max(list1)
for h in range(larggest):
inlist = "|"
for i in range (len(list1)):
if list1[i] > 0:
inlist += " *"
list1[i] -= 1
else:
inlist += " "
list2.append(inlist)
list2.reverse()
list2.append("+--+--+--+--+--+--+--+--+--+--+--+-\n"+" 2 3 4 5 6 7 8 9 10 11 12")
return list2
import random
def main():
random.seed(1314)
times = eval(input("How many times do you want to roll the dice? "))
#0,1,2,3,4,5,6,7,8,9,0
#2,3,4,5,6,7,8,9,0,1,2
results = [0,0,0,0,0,0,0,0,0,0,0]
for i in range(times):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
diceSum = dice1 + dice2
#print (dice1,dice2,diceSum)
results[diceSum-2] += 1
print("Results: ", results)
if times <= 100:
list_in = results
else:
list_in = []
for item in results:
x = int( round( item/(times/100) ) )
list_in.append(x)
graph = graphy(list_in)
for line in graph:
print (line)
main()
|
c98a38057b4e420cca442a17f501bf397926e0ae | s-kimmer/tesp2016 | /demo/camcapture_demo.py | 884 | 3.546875 | 4 | from __future__ import print_function # with this, print behaves like python 3.x even if using python 2.x
import cv2
camera_device_index = 1 #choose camera device [0,N-1], 0 for first device, 1 for second device etc.
cap = cv2.VideoCapture(camera_device_index)
if cap.isOpened(): # try to get the first frame
print("Opened camera stream!")
ret, frame = cap.read()
if ret == True:
width = cap.get(3)
height = cap.get(4)
print("Frame width x height: {} x {} ".format( width, height ))
print("Press 'Esc' to close application")
window_name = "webcam_demo"
else:
ret = False
while ret:
cv2.imshow(window_name, frame)
ret, frame = cap.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
# When everything is done, release the capture device
cap.release()
cv2.destroyWindow(window_name)
#%% |
bbf8b432ddf101d3e6986c2a09695773abd47c98 | JosevanyAmaral/Exercicios-de-Python-Resolvidos | /Exercícios/ex091.py | 559 | 3.671875 | 4 | from random import randint
from time import sleep
from operator import itemgetter
jogadores = {'Jogador 1': randint(1, 6), 'Jogador 2': randint(1, 6),
'Jogador 3': randint(1, 6), 'Jogador 4': randint(1, 6)}
ranking = list()
print('Valores sorteados: ')
for c, j in jogadores.items():
print(f' O {c} tirou {j} no dado.')
sleep(1)
print(f'{" RANKING DOS JOGADORES ":=^30}')
ranking = sorted(jogadores.items(), key=itemgetter(1), reverse=True)
for i, v in enumerate(ranking):
print(f' {i+1}º lugar: {v[0]} com {v[1]}')
sleep(1)
|
d127705f9dd239922fbb76363c5cc3ca519736c3 | refeed/StrukturDataA | /meet1/F_max3Angka.py | 549 | 3.65625 | 4 | '''
Max 3 angka
Batas Run-time: 1 detik / test-case
Batas Memori: 32 MB
DESKRIPSI SOAL
Buatlah program yang menerima 3 buah input nilai, outputkan nilai paling besar
diantara ketiga input tersebut.
PETUNJUK MASUKAN
Input terdiri atas 3 angka dalam 1 baris
PETUNJUK KELUARAN
Outputkan angka terbesar dari 3 angka yang dimasukkan
CONTOH MASUKAN
10 9 11
CONTOH KELUARAN
11
'''
input_int_list = list(map(int, input().split()))
biggest = input_int_list[0]
for num in input_int_list:
if num > biggest:
biggest = num
print(biggest)
|
7737bc3a3753c7641c3d418ec6e0ba50c979c69a | DanMayhem/project_euler | /024.py | 939 | 3.96875 | 4 | #!python
"""
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
"""
def _find_k(a):
k=-1
for i in range(len(a)-1):
if a[i] < a[i+1]:
k = i
return k
def _find_l(a, k):
l = -1
for i in range(k+1,len(a)):
if a[k] < a[i]:
l=i
return l
def permutations(l):
a = l[:]
a.sort()
yield a
k=0
while k>-1:
k = _find_k(a)
l = _find_l(a, k)
x = a[k]
a[k] = a[l]
a[l] = x
a[k+1:] = reversed(a[k+1:])
yield a
if __name__=="__main__":
l = [0,1,2,3,4,5,6,7,8,9]
i=1
for p in permutations(l):
if i==1000000:
print("".join(map(str,p)))
exit()
i+=1
|
e6a6567a742d646ffce0638931e93eac0bbe801d | bpotten7198/code-change-test | /greenBottles.py | 466 | 3.96875 | 4 | import time
bottles=10 #Sets bottles to 10
for x in range(bottles,0,-1): #Creates a loop which loops 10 times
print("{0} green bottles, hanging on the wall\n{0} green bottles, hanging on the wall".format(x)) #Prints out how many bottles there are
print("And if 1 green bottle should accidently fall,\nThere'll be {0} green bottles hanging on the wall.".format(x-1)) #Prints out how many bottles there will be
time.sleep(1) #Pauses the code for 1 second
|
6a8c50c79564dbaf30b72f7f17641782c71b8e24 | punyanishivam/Cracking-the-Coding-Interview | /2.2.py | 226 | 3.6875 | 4 | import Linked Lists
def nthToLast(self, n):
p1 = self.head
p2 = self.head
for i in range(n):
if p1 is None:
return
p1 = p1.next
while p1 is not None:
p1 = p1.next
p2 = p2.next
return p2
|
21b5a20e826dbf86648762e4b7b4a7782369ec35 | Ashleshk/Python-For-Everybody-Coursera | /Course-1-Programming-for-Everybody-Getting-Started-with-Python/Codes/compute_gross_pay_py3.py | 185 | 3.859375 | 4 | hrs = input('Enter Hours: ')
hrs = float(hrs)
hourly_rate = input('Enter Hourly Rate: ')
hourly_rate = float(hourly_rate)
gross_pay = hourly_rate * hrs
print("Gross pay:", gross_pay)
|
e6efecc8e0521bfbe6519713f8d0b19410b43c76 | keshavmusunuri/Isolation_Game_Agent | /my_custom_player.py | 3,733 | 3.71875 | 4 |
from sample_players import DataPlayer
import random
class CustomPlayer(DataPlayer):
""" Implement customized agent to play knight's Isolation """
def get_action(self, state):
""" Employ an adversarial search technique to choose an action
available in the current state calls self.queue.put(ACTION) at least
This method must call self.queue.put(ACTION) at least once, and may
call it as many times as you want; the caller is responsible for
cutting off the function after the search time limit has expired.
See RandomPlayer and GreedyPlayer in sample_players for more examples.
**********************************************************************
NOTE:
- The caller is responsible for cutting off search, so calling
get_action() from your own code will create an infinite loop!
Refer to (and use!) the Isolation.play() function to run games.
**********************************************************************
"""
depth_limit = 20
if state.ply_count < 4 and self.data is not None:
if state in self.data:
self.queue.put(self.data[state])
else:
self.queue.put(random.choice(state.actions()))
else:
for depth in range(1, depth_limit+1):
best_move = self.alpha_beta_search(state, depth)
if best_move is not None:
self.queue.put(best_move)
def alpha_beta_search(self, state, depth):
def min_value(state, depth, alpha, beta):
val = float("inf")
if state.terminal_test():
return state.utility(self.player_id)
if depth <= 0 :
return self.score(state)
for action in state.actions():
val = min(val, max_value(state.result(action), depth - 1, alpha, beta))
if val <= alpha:
return val
beta = min(beta, val)
return val
def max_value(state, depth, alpha, beta):
val = float("-inf")
if state.terminal_test():
return state.utility(self.player_id)
if depth <= 0 :
return self.score(state)
for action in state.actions():
val = max(val, min_value(state.result(action), depth - 1, alpha, beta))
if val >= beta:
return val
alpha = max(alpha, val)
return val
return max(state.actions(), key=lambda x: min_value(state.result(x), depth - 1, float('-inf'), float('inf')))
def score(self, state):
width = 11
height = 9
borders = [
[(0, widths) for widths in range(width)],
[(heights, 0) for heights in range(height)],
[(height - 1, widths) for widths in range(width)],
[(width - 1, heights) for heights in range(height)]
]
player_loc = state.locs[self.player_id]
opponent_loc = state.locs[1 - self.player_id]
player_liberties = state.liberties(player_loc)
opponent_liberties = state.liberties(opponent_loc)
if self.at_border(player_loc, borders):
next_opponent_liberties = [len(state.liberties(next_move)) for next_move in opponent_liberties]
return len(player_liberties) - 3 * (len(opponent_liberties) + sum(next_opponent_liberties))
else:
return len(player_liberties) - 3 * (len(opponent_liberties))
def at_border(self, locs, borders):
for border in borders:
return locs in border
|
0fc2f839ca636ef43f39f6174ff4f42c8a4c8daa | karim-aboelazm/PyCheckio_ScientificExpedition | /Striped Words/mission.py | 939 | 4.09375 | 4 | def checkio(line: str) -> str:
Vowels = 'AEIOUY'
Consonants = 'BCDFGHJKLMNPQRSTVWXZ'
cont = 0
newline = ''
for c in line:
if c.upper() in Vowels:
newline += 'a'
elif c.upper() in Consonants:
newline += 'b'
elif not c.isalnum():
newline += ' '
else:
newline += c
for word in newline.split():
if 'aa' not in word and 'bb' not in word and word.isalpha() and len(word)>1:
cont += 1
return cont
if __name__ == '__main__':
print("Example:")
print(checkio('My name is ...'))
# These "asserts" are used for self-checking and not for an auto-testing
assert checkio('My name is ...') == 3
assert checkio('Hello world') == 0
assert checkio('A quantity of striped words.') == 1
assert checkio('Dog,cat,mouse,bird.Human.') == 3
print("Coding complete? Click 'Check' to earn cool rewards!")
|
e3a0151735dbb748d5ce32b674e95bacdf73a09a | JinJianyuCSlover/MLBoBo | /Chapter6_GradientDescent/ML61a.py | 1,157 | 3.875 | 4 | import numpy as np
import matplotlib.pyplot as plt
plot_x = np.linspace(-1,6,141)#绘制的x点均匀取值
plot_y=(plot_x-2.5)**2-1#模拟损失函数
#绘制图像
# plt.plot(plot_x,plot_y)
# plt.show()
def dJ(theta):
"""导数"""
return 2*(theta)-5
def J(theta):
"""损失函数"""
try:
return (theta-2.5)**2-1
except:
return float('inf')#异常处理,防止过大的值
"""封装梯度下降"""
initial_theta = 0.0
def gradient_descent(initial_theta,eta,epsilon=1e-8,n_iterations=1e4):
theta=initial_theta
theta_history.append(theta)
i_iter=0
while i_iter<n_iterations:
gradient = dJ(theta)
last_theta = theta
theta = theta - (gradient * eta)
theta_history.append(theta)
if (abs(J(theta) - J(last_theta)) < epsilon):
break
i_iter+=1
def plot_theta_history():
plt.plot(plot_x,J(plot_x))
plt.plot(np.array(theta_history), J(np.array(theta_history)), color='r', marker='+')
plt.show()
eta=1.1
theta_history=[]
gradient_descent(0.0,eta,n_iterations=10)
plot_theta_history()
print(len(theta_history))
print(theta_history[-1]) |
7c119286b9eeadbfa532e9a016266fa9512b93b3 | Chidinma-U/Personal_Tutorials | /dynamic.py | 460 | 3.578125 | 4 | import time
stored_results = {}
def sum_to_n (n):
start_time = time.perf_counter()
result = 0
for i in reversed (range(n)):
if i + 1 in stored_results:
print ('Stopping sum at %s because we have previously computed it' %str(i+1))
result += stored_results [i + 1]
break
else:
result += i + 1
stored_results [n] = result
print(time.perf_counter() - start_time, "seconds")
|
1f39ae582667b7a12e07d832ea04b6643431fdb3 | skanwat/python | /learnpython/fibonacciseries.py | 218 | 3.625 | 4 | def fibo(x):
if x == 1:
return 1
elif x == 0:
return 0
else:
return (fibo(x-1) + fibo(x-2))
list=[]
for x in range(1,10):
z=fibo(x)
list.append(z)
print(z)
|
4d869cbc3693ffcd8843a6f939cbc4f1daabcf48 | renukadeshmukh/Leetcode_Solutions | /1072_FlipColumnsForMaximumNumberofEqualRows.py | 1,959 | 4.3125 | 4 | '''
1072. Flip Columns For Maximum Number of Equal Rows
Given a matrix consisting of 0s and 1s, we may choose any number of columns in
the matrix and flip every cell in that column. Flipping a cell changes the value
of that cell from 0 to 1 or from 1 to 0. Return the maximum number of rows that
have all values equal after some number of flips.
Example 1:
Input: [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.
Example 2:
Input: [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal
values.
Example 3:
Input: [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows
have equal values.
Note:
1 <= matrix.length <= 300
1 <= matrix[i].length <= 300
All matrix[i].length's are equal
matrix[i][j] is 0 or 1
'''
'''
ALGORITHM:
1. Convert each row into a tuple and store the number of times the same row
occues in the given matrix.
2. Now find the largest value of row + row_complement for this matrix.
RUNTIME COMPLEXITY: O(M*N) for m rows and n cols.
SPACE COMPLEXITY: O(M*N)
'''
from collections import defaultdict
class Solution(object):
def maxEqualRowsAfterFlips(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
max_equal = -1
store = defaultdict(int)
for row in matrix:
t = tuple(row)
store[t] += 1
for key in store:
c = store[key]
t_inv = self.invert(key)
if t_inv in store:
c += store[t_inv]
max_equal = max(max_equal, c)
return max_equal
def invert(self, tup):
t_inv = []
for t in tup:
if t == 0:
t_inv.append(1)
else:
t_inv.append(0)
return tuple(t_inv)
|
df53ce2d187cd33ea26398e5c5f4c1c8ba9d1782 | ghxuan/leetcode | /py/calculate.py | 1,761 | 3.796875 | 4 | def calculate(s):
"""
:type s: str
:rtype: int
"""
s = s.replace(' ', '')
fix = postfix(s)
print(fix)
temp = []
sign = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'/': lambda x, y: x / y,
'*': lambda x, y: x * y,
'×': lambda x, y: x * y,
'%': lambda x, y: x % y,
}
while fix:
i = fix[0]
fix.pop(0)
if i not in '+-×*/%':
temp.append(int(i))
else:
b, a = temp.pop(), temp.pop()
temp.append(sign[i](a, b))
return temp[0]
def postfix(s):
"""
字符串转后缀表达式
:param s: str
:return: list
"""
res = []
temp = []
# 优先级
priority = {
'+': 1, '-': 1, '*': 2,
'×': 2, '/': 2, '%': 2,
}
for i in s:
if i not in '*×/%+-()':
res.append(i)
elif i == ')':
for j in temp[::-1]:
if j == '(':
temp.pop()
break
res.append(temp.pop())
else:
while True:
# 判断优先级
if not temp or temp[-1] == '(' or i == '(' or priority[i] > priority[temp[-1]]:
temp.append(i)
break
else:
res.append(temp.pop())
pass
res += temp[::-1]
return res
print(calculate('1 + 1'))
print(calculate(' 2-1 + 2 '))
print(calculate('(1+(4+5+2)-3)+(6+8)'))
print(calculate('1+((2-3+2)×4)-5'))
# ['1', '1', '+']
# 2
# ['2', '1', '-', '2', '+']
# 3
# ['1', '4', '5', '+', '2', '+', '+', '3', '-', '6', '8', '+', '+']
# 23
# ['1', '2', '3', '-', '2', '+', '4', '×', '+', '5', '-']
# 0 |
c1a508753c8441bbf76d4f6b9768e3b261b6e6f4 | vishalkarda/DailyPracticeProblems | /October/06Oct2019_tree_at_height_h.py | 695 | 3.890625 | 4 | """
Given a binary tree, return all values given a certain height h.
"""
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
val = list()
def values_at_height(root, height):
if root is None:
return None
if height == 1:
val.append(root.value)
else:
values_at_height(root.left, height-1)
values_at_height(root.right, height-1)
return val
a = Node(1)
a.left = Node(2)
a.right = Node(3)
a.left.left = Node(4)
a.left.right = Node(5)
a.right.right = Node(7)
print(values_at_height(a, 3))
# [4, 5, 7]
# 1
# / \
# 2 3
# / \ \
# 4 5 7
|
99aef96df8226b8ecee48251e9aa270a05097fd9 | theo-l/theo-l.github.io | /hacking_python_class_python_source/builtin_call_expression_demo.py | 356 | 3.53125 | 4 | class CallableInstanceClass:
def __init__(self, name):
print(f'calling class:<{self.__class__.__name__}>')
self.name = name
def __call__(self, *args, **kwargs):
print(f'calling instance:<{self.name}>')
if __name__ == '__main__':
callable_instance = CallableInstanceClass('callable instance')
callable_instance()
|
37e0f0c22fe9c50f30981ce55cb95992dc531c59 | Mike1604/MIPS | /Proyecto_D13E02/Decodificador.py | 11,709 | 3.625 | 4 | #Decodificador
import os, sys, subprocess
from io import open
def inicio():
os.system("cls")
print("Bienvenido")
print("Equipo 02")
print("Fʟᴏʀᴇs Esᴛʀᴀᴅᴀ Aʙʀᴀʜᴀᴍ Mɪɢᴜᴇʟ Aɴɢᴇʟ")
print("Guerra Lopez Paulina Estefania")
print("Pᴇʀᴇᴢ ᴅᴇ ʟᴀ Tᴏʀʀᴇ Lᴇᴏɴᴀʀᴅᴏ Oᴄᴛᴀᴠɪᴏ\n")
print("Este algoritmo resuelve las combinaciones posibles al escoger N elementos del total de N elementos\n")
print("Para obtener el numero de combinatorias posibles se resta el a - b a el resultado despues se le obtendra")
print("el factorial al igual que a y b. Despues b se multplicara por el factorial de la resta y el resultado")
print("se usara para dividir el factorial de a por este")
input("\nPresione enter para iniciar")
def DB (opc):
numero_binario = 0
multiplicador = 1
while opc != 0:
numero_binario = numero_binario + opc % 2 * multiplicador
opc //= 2
multiplicador *= 10
return numero_binario
def MEMD(opc,sel):
archivo_texto=open("MEMD.txt","w")
opcs=str(opc)
sels=str(sel)
salt="\n"
uno="1\n"
archivo_texto.write(opcs)
archivo_texto.write(salt)
archivo_texto.write(sels)
archivo_texto.write(salt)
archivo_texto.write(uno)
for i in range(29):
archivo_texto.write("0\n")
archivo_texto.close()
def MEMIns(opc,sel):
archivo_texto=open("MEMIns.txt","w")
salt="\n"
nop="00000000\n"
lw="100011"
dirb0="00\n000"
dirb0_1="00000"
dirb1="00\n001"
dirb1_1="00001\n"
dirb1_0="00001"
dirb4="00\n100"
dirb4_1="00100"
dirb4_2="001\n00"
dirb5="00101\n"
dirb5_0="00101"
dirb5_1="00\n101"
dirb2="00\n010"
dirb2_1="00010"
dirb3="00011\n"
dirb3_1="00\n011"
dirb6="00110"
dirb6_1="00\n110"
R="000000"
shif="000\n00"
mul="011000"
sub="100010"
beq="000100"
j="000010"
jnop="00\n00000000"
j1="00001010"
j2="00010011"
j3="00011100"
beq1="00000101"
div="011010"
sw="101011"
#Instruccion 0 NOP
for i in range(4):
archivo_texto.write(nop)
#instruccion 1 Carga el primer operando al banco de registros
archivo_texto.write(lw)
archivo_texto.write(dirb2)
archivo_texto.write(dirb0_1)
archivo_texto.write(salt)
archivo_texto.write(nop)
archivo_texto.write(nop)
#instruccion 2 Carga el segundo operando al banco de registros
archivo_texto.write(lw)
archivo_texto.write(dirb2)
archivo_texto.write(dirb1_1)
archivo_texto.write(nop)
archivo_texto.write(nop)
#instruccion 3 Carga el primer operando al banco de registros en otra direccion
archivo_texto.write(lw)
archivo_texto.write(dirb0)
archivo_texto.write(dirb4_1)
archivo_texto.write(salt)
archivo_texto.write(nop)
archivo_texto.write(nop)
#instruccion 4 Carga el segundo operando al banco de registros en otra direccion
archivo_texto.write(lw)
archivo_texto.write(dirb1)
archivo_texto.write(dirb5)
archivo_texto.write(nop)
archivo_texto.write(nop)
#Instruccion 5 Carga el numero 1 al banco de registros
archivo_texto.write(lw)
archivo_texto.write(dirb2)
archivo_texto.write(dirb2_1)
archivo_texto.write(salt)
archivo_texto.write(nop)
archivo_texto.write(nop)
#Instruccion 6 Carga el numero 1 al banco de registros
archivo_texto.write(lw)
archivo_texto.write(dirb2)
archivo_texto.write(dirb3)
archivo_texto.write(nop)
archivo_texto.write(nop)
#Instruccion 7
for i in range(4):
archivo_texto.write(nop)
#Instruccion 8
for i in range(4):
archivo_texto.write(nop)
"""
Primer Factorial
"""
#Instruccion 9 se resta un operando por el otro
archivo_texto.write(R)
archivo_texto.write(dirb4)
archivo_texto.write(dirb5)
archivo_texto.write(dirb6)
archivo_texto.write(shif)
archivo_texto.write(sub)
archivo_texto.write(salt)
#Instruccion 10 multiplica los operandos para calcular el factorial
archivo_texto.write(R)
archivo_texto.write(dirb0)
archivo_texto.write(dirb4_1)
archivo_texto.write(salt)
archivo_texto.write(dirb0_1)
archivo_texto.write(shif)
archivo_texto.write(mul)
archivo_texto.write(salt)
#Instruccion 11 resta el operando por 1
archivo_texto.write(R)
archivo_texto.write(dirb4)
archivo_texto.write(dirb2_1)
archivo_texto.write(salt)
archivo_texto.write(dirb4_1)
archivo_texto.write(shif)
archivo_texto.write(sub)
archivo_texto.write(salt)
#Instruccion 12 BEQ
archivo_texto.write(beq)
archivo_texto.write(dirb4)
archivo_texto.write(dirb2_1)
archivo_texto.write(salt)
archivo_texto.write(nop)
archivo_texto.write(beq1)
archivo_texto.write(salt)
#Instruccion 13 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 14 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 15 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 16 J
archivo_texto.write(j)
archivo_texto.write(jnop)
archivo_texto.write(salt)
archivo_texto.write(nop)
archivo_texto.write(j1)
archivo_texto.write(salt)
#Instruccion 17 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 18 NOP
for i in range(4):
archivo_texto.write(nop)
"""
Segundo Factorial
"""
#Instruccion 19 multiplica los operandos para calcular el factorial
archivo_texto.write(R)
archivo_texto.write(dirb1)
archivo_texto.write(dirb5)
archivo_texto.write(dirb1_0)
archivo_texto.write(shif)
archivo_texto.write(mul)
archivo_texto.write(salt)
#Instruccion 20 resta el operando por 1
archivo_texto.write(R)
archivo_texto.write(dirb5_1)
archivo_texto.write(dirb3)
archivo_texto.write(dirb5_0)
archivo_texto.write(shif)
archivo_texto.write(sub)
archivo_texto.write(salt)
#Instruccion 21 BEQ
archivo_texto.write(beq)
archivo_texto.write(dirb3_1)
archivo_texto.write(dirb5)
archivo_texto.write(nop)
archivo_texto.write(beq1)
archivo_texto.write(salt)
#Instruccion 22 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 23 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 24 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 25 J
archivo_texto.write(j)
archivo_texto.write(jnop)
archivo_texto.write(salt)
archivo_texto.write(nop)
archivo_texto.write(j2)
archivo_texto.write(salt)
#Instruccion 26 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 27 NOP
for i in range(4):
archivo_texto.write(nop)
"""
Tercer Factorial
"""
#Instruccion 28 multiplica los operandos para calcular el factorial
archivo_texto.write(R)
archivo_texto.write(dirb2)
archivo_texto.write(dirb6)
archivo_texto.write(salt)
archivo_texto.write(dirb2_1)
archivo_texto.write(shif)
archivo_texto.write(mul)
archivo_texto.write(salt)
#Instruccion 29 resta el operando por 1
archivo_texto.write(R)
archivo_texto.write(dirb6_1)
archivo_texto.write(dirb3)
archivo_texto.write(dirb6)
archivo_texto.write(shif)
archivo_texto.write(sub)
archivo_texto.write(salt)
#Instruccion 30 BEQ
archivo_texto.write(beq)
archivo_texto.write(dirb3_1)
archivo_texto.write(dirb6)
archivo_texto.write(salt)
archivo_texto.write(nop)
archivo_texto.write(beq1)
archivo_texto.write(salt)
#Instruccion 31 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 32 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 33 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 34 J
archivo_texto.write(j)
archivo_texto.write(jnop)
archivo_texto.write(salt)
archivo_texto.write(nop)
archivo_texto.write(j3)
archivo_texto.write(salt)
#Instruccion 35 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 36 NOP
for i in range(4):
archivo_texto.write(nop)
"""
Multiplicacion de factoriales
"""
#Instruccion 37 Mul
archivo_texto.write(R)
archivo_texto.write(dirb1)
archivo_texto.write(dirb2_1)
archivo_texto.write(salt)
archivo_texto.write(dirb4_1)
archivo_texto.write(shif)
archivo_texto.write(mul)
archivo_texto.write(salt)
"""
Division de Factoriales
"""
#Instruccion 38 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 39 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 40 Div
archivo_texto.write(R)
archivo_texto.write(dirb0)
archivo_texto.write(dirb4_1)
archivo_texto.write(salt)
archivo_texto.write(dirb5_0)
archivo_texto.write(shif)
archivo_texto.write(div)
archivo_texto.write(salt)
"""
Guarda el resultado en la memoria
"""
#Instruccion 41 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 42 NOP
for i in range(4):
archivo_texto.write(nop)
#Instruccion 43 Sw
swoff="00000010"
archivo_texto.write(sw)
archivo_texto.write(dirb3_1)
archivo_texto.write(dirb5)
archivo_texto.write(nop)
archivo_texto.write(swoff)
archivo_texto.close()
def Ens():
archivo_texto=open("AlgoritmoEns.txt","w")
Ens1="Nop $0 $0 #0\n Lw $0 $2 #0\n Lw $1 $2 #0\nLw $4 $0 #0\nLw $5 $1 #0\nLw $2 $2 #0\nLw $3 $2 #0\nNop $0 $0 $0\n"
Ens2="Nop $0 $0 $0\nSub $6 $4 $5\nMul $0 $0 $4\nSub $4 $4 $2\nBeq $4 $2 #5\nNop $0 $0 $0\nNop $0 $0 $0\nNop $0 $0 $0\n"
Ens3="J $10 \nNop $0 $0 $0\nNop $0 $0 $0\nMul $1 $1 $5\nSub $5 $5 $3\nBeq $3 $5 #5\nNop $0 $0 $0\nNop $0 $0 $0\n"
Ens4="Nop $0 $0 $0\nJ $19 \nNop $0 $0 $0\nNop $0 $0 $0\nMul $2 $2 $6\nSub $6 $6 $3\nBeq $3 $6 #5\nNop $0 $0 $0\n"
Ens5="Nop $0 $0 $0\nNop $0 $0 $0\nJ $28 \nNop $0 $0 $0\nNop $0 $0 $0\nMul $4 $1 $2b\nNop $0 $0 $0\nNop $0 $0 $0\n"
Ens6="Div $5 $0 $4\nNop $0 $0 $0\nNop $0 $0 $0\nSw $5 $3 #2"
archivo_texto.write(Ens1)
archivo_texto.write(Ens2)
archivo_texto.write(Ens3)
archivo_texto.write(Ens4)
archivo_texto.write(Ens5)
archivo_texto.write(Ens6)
archivo_texto.close()
def deco():
print(inicio())
os.system("cls")
try:
print("Para este algoritmo unicamente se pueden usar numeros enteros, el numero de opciones posibles maximo es 10\n")
opc=int(input("\nIngrese el numero de opciones posibles: \n"))
sel=int(input("Ingrese que opciones fueron seleccionadas: \n"))
if ((opc<0) or (sel<0)):
print("Las opciones no pueden ser negativas")
input("Presiona enter para continuar")
deco()
if(opc>10):
print("Recuerda que el algoritmo unicamente soporta hasta factoriales de 10....")
input("Presiona enter para continuar")
deco()
if (opc>sel):
opcM=DB(opc)
selM=DB(sel)
MEMD(opcM,selM)
MEMIns(opc,sel)
Ens()
print("Archivo de instrucciones, Ensamblador, Memoria de datos generados correctamente......")
input("Presiona enter para salir")
else:
print("El numero de elementos seleccionados no puede ser menor que el numero de elementos totales")
input("Presiona enter para continuar")
deco()
except:
print("Debes ingresar numeros enteros")
input("Presiona enter para continuar")
deco()
deco()
|
ce923c095efc5afeb210150989cf4ca4dad36935 | rmzturkmen/Python_assignments | /Assignment-13_1-Find-largest-number.py | 234 | 4.1875 | 4 | # Find Largest Number in a List with function, for and if.
def max_num(lst):
max = lst[0]
for i in lst:
if i > max:
max = i
else:
return max
lst = [-6, 8, 12, 5, 13, -4]
print(max_num(lst))
|
84aa8557cd98423577a6b35b8e1747d09d693755 | michakomo/aisd.py | /linked_list.py | 1,851 | 3.890625 | 4 | class LinkedList:
def __init__(self):
self.head = None
class Node:
def __init__(self, val = None, next = None):
self.val = val
self.next = next
def __repr__(self):
return str(self.val)
def push(self, val): ### O(1)
self.head = self.Node(val, self.head)
def pop(self):
if not self.head:
return None
ret = self.head
self.head = self.head.next
return ret
def search(self, val): ### O(n) # bez wartownika
node = self.head
while node.val != val:
node = node.next
return node
def inject(self, val): ### O(n)
if not self.head:
self.push(val)
return
node = self.head
while node.next != None:
node = node.next
node.next = self.Node(val)
def front(self): ### O(1)
return self.head
def max(self):
node = self.head
max_node = self.head
while node != None:
if node.val > max_node.val:
max_node = node
return max_node
def remove(self, val):
if not self.head:
raise Exception("empty list")
if self.head.val == val:
self.head = self.head.next
return
prev = self.head
node = self.head
while node != None:
if node.val == val:
prev.next = node.next
return
prev = node
def __repr__(self): ### O(n)
nodes = []
node = self.head
while node != None:
nodes.append(str(node.val))
node = node.next
nodes.append("None")
return " -> ".join(nodes)
|
0b36554bc801daff7196db982eb3a875343241a3 | stefifm/trabajos-practicos-utn | /tp/2020_AED_TP3_Bruera_59149[1K10]_Tanchiva_82179[1K10]/funciones_participantes.py | 10,989 | 3.640625 | 4 | import random
print("Para la carga de los participantes")
#Aquí se encuentran las clases Participantes y Fixture
class Participantes:
def __init__(self, nom, conti, rank):
self.nombre = nom
self.continente = conti
self.ranking = rank
def to_string(participantes):
"""
Genera una cadena que representa el contenido del registro
Participantes
:param participantes: convertir en string
:return: un string representando a participantes
"""
r = " "
r += "{:<6}".format("Nombre: " + participantes.nombre)
r += "{:<10}".format(" | Continente: " + str(participantes.continente))
r += "{:<10}".format(" | Ranking: " + str(participantes.ranking))
return r
class Fixture:
def __init__(self, participantes, punt):
self.nombre = participantes.nombre
self.puntos = punt
def to_string_fixture(fixture):
"""
Genera una cadena que representa el contenido del registro Fixture
:param fixture: a convertir en string
:return: un string representando a fixture
"""
r = " "
r += "{:<6}".format("Nombre: " + fixture.nombre)
r += "{:<10}".format(" | Puntos: " + str(fixture.puntos))
return r
def mostrar_participantes(participantes):
"""
Muestra los elementos de un vector de registros de
tipo Participantes
:param participantes: El vector de registros de tipo Participantes
:return: None
"""
for i in range(len(participantes)):
print(to_string(participantes[i]))
#------------------------------------------------------------------------------
# Primera parte del ejercicio: Carga manual y automática del vector de
# participantes
# Validación para que no se repitan los nombres
def buscar_nombre(nom, participantes):
"""
Busca en el vector participantes si un nombre se repite
:param nom: El nombre que se ingresará
:param participantes: vector de registro Tipo Participantes
:return: True si ya existe el nombre. Y False si no está
"""
for reg in participantes:
if reg.nombre == nom:
return True
return False
# Validar el rango para continente y ranking
def validar_rango(inf, sup, mensaje):
n = inf - 1
while n < inf or n > sup:
n = int(input(mensaje))
if n < inf or n > sup:
print("Valor no válido. Ingrese un valor entre",str(inf),"y",
str(sup))
return n
#Carga manual del vector
def carga_manual(participantes):
"""
Genera el vector de registros tipo Participantes de forma manual
:return: vector de participantes con datos cargados manualmente
"""
for i in range(16):
nombre = input("Ingrese el nombre de los participantes: ")
while buscar_nombre(nombre, participantes):
nombre = input("Ingrese el nombre de los participantes: ")
continente = validar_rango(0, 4, "Ingrese el continente [0-América. "
"1-Europa. 2-Asia. 3-África. "
"4-Oceanía")
ranking = validar_rango(1, 100, "Ingrese el ranking: ")
reg1 = Participantes(nombre, continente, ranking)
participantes.append(reg1)
# Esta sección es para la carga automática
# Una tupla para que nombre lo use en el random.choice
nom = ("Mercedes", "Red Bull", "Ferrari", "McLaren", "Williams",
"Racing Point", "Renault", "Alpha Tauri", "Haas", "Alfa Romeo",
"Team Penske", "Toyota Gazoo Racing", "Peugeot Sport Team",
"Chip Ganassi Racing", "RLL Racing", "Action Express")
def carga_automatica(participantes):
"""
Genera el vector de registros tipo Participantes de forma automática
:return: vector de participantes con datos aleatorios
"""
for i in range(16):
nombre = random.choice(nom)
while buscar_nombre(nombre, participantes):
nombre = random.choice(nom)
continente = random.randint(0, 4)
ranking = random.randint(1, 100)
reg1 = Participantes(nombre, continente, ranking)
participantes.append(reg1)
# Ordenamiento de mayor a menor
def orden_sort(participantes):
"""
Algoritmo de Selección Directa para ordenar de mayor a menor el arreglo
:param participantes: El vector de registros de tipo Participantes
:return: El vector ordenado
"""
n = len(participantes)
for i in range(n-1):
for j in range(i+1, n):
if participantes[i].ranking < participantes[j].ranking:
participantes[i], participantes[j] = participantes[j], \
participantes[i]
#Estadística participante por continente
def estadistica_continente(participantes):
"""
Arma y muestra el vector de conteo de continente
:param participantes: El vector de registros de tipo Participantes
:return: El vector de conteo de participantes por continente
"""
conteo_continente = [0] * 16
for i in range(len(participantes)):
cont = int(participantes[i].continente)
conteo_continente[cont] += 1
for i in range(16):
if conteo_continente[i] != 0:
print("Continente:",i,"| Cantidad de participantes:",
conteo_continente[i])
#------------------------------------------------------------------------------
# Función para armar y mostrar el fixture de octavos
def fixture(fixture):
"""
Genera y muestra los elementos de un vector de registros de
tipo Fixture solo para octavos
:param fixture: El vector de registros de tipo Fixture
:return: El vector de registros Tipo Fixture ya mostrando los
enfrentamientos y por elección nuestra, los puntos. Solo sirve para octavos
"""
n = len(fixture) // 2
posicion = len(fixture) - 1
c = 0
for i in range(n):
fixture[i].puntos = random.randint(100, 1000)
fixture[posicion - c].puntos = random.randint(100, 1000)
e1 = Fixture(fixture[i],fixture[i].puntos)
e2 = Fixture(fixture[posicion-c], fixture[posicion - c].puntos)
c += 1
print(to_string_fixture(e1), "vs", to_string_fixture(e2))
def mostrar_fixture(fixture):
"""
Muestra los cruces de cuartos, semis, tercero y final
:param fixture: El vector de registros de tipo Fixture
:return: Muestra de los cruces + puntos de cuartos, semis, tercero y
final
"""
n = len(fixture) // 2
posicion = len(fixture) - 1
c = 0
for i in range(n):
e1 = fixture[i]
e2 = fixture[posicion-c]
c += 1
print(to_string_fixture(e1), "vs", to_string_fixture(e2))
#Función para determinar los ganadores de cada cruce
def ganador(fixture):
"""
Determina el ganador de cada ronda
:param fixture: El vector de registros de tipo Fixture
:return: El vector ronda con los que pasaron a la siguiente instancia
"""
n = len(fixture) // 2
posicion = len(fixture) - 1
c = 0
ronda = []
for i in range(n):
if fixture[i].puntos > fixture[posicion-c].puntos:
ronda.append(fixture[i])
else:
ronda.append(fixture[posicion-c])
c += 1
return ronda
#Función para armar el vector de la final
def final(fixture):
"""
Genera el vector de la final
:param fixture: El vector de registros de tipo Fixture
:return: el vector con los finalistas
"""
n = len(fixture) // 2
posicion = len(fixture) - 1
c = 0
ronda_final = []
for i in range(n):
if fixture[i].puntos > fixture[posicion - c].puntos:
ronda_final.append(fixture[i])
else:
ronda_final.append(fixture[posicion - c])
c += 1
return ronda_final
#Función para armar el vector del tercer puesto
def tercer(fixture):
"""
Genra el vector con los que compiten por el tercer puesto
:param fixture: El vector de registros de tipo Fixture
:return: vector con los que van por el tercer puesto
"""
n = len(fixture) // 2
posicion = len(fixture) - 1
c = 0
ronda_tercero = []
for i in range(n):
if fixture[i].puntos < fixture[posicion - c].puntos:
ronda_tercero.append(fixture[i])
else:
ronda_tercero.append(fixture[posicion - c])
c += 1
return ronda_tercero
# Función para calcular el promedio
def estadistica_promedio_ronda(fixture):
"""
Función para el cálculo de promedio de puntos por partcipantes en
octavos, cuartos y semis
:param fixture: el vector de registros de tipo Fixture
:return: promedio de los puntos por participantes
"""
suma = 0
contador = 0
for reg in fixture:
suma += reg.puntos
contador += 1
prom = round(suma / contador, 2)
return prom
#------------------------------------------------------------------------------
# Función para determinar el campeón y subcampeón
def top2(final):
"""
Determina quién fue campeón y subcampeón
:param final: El vector de finalistas antes creado
:return: ganador y segundo
"""
posicion = len(final) - 1
c = 0
for i in range(len(final)):
if final[i].puntos > final[posicion - c].puntos:
ganador = final[i]
segundo = final[posicion-c]
else:
ganador = final[posicion-c]
segundo = final[i]
c += 1
return ganador, segundo
# Función para el tercer lugar
def tercero(ter):
"""
Determina quién termina en el tercer lugar
:param ter: El vector de tercer_puesto antes creado
:return: tercer lugar
"""
posicion = len(ter) - 1
c = 0
for i in range(len(ter)):
if ter[i].puntos > ter[posicion - c].puntos:
tercer_lugar = ter[i]
else:
tercer_lugar = ter[posicion-c]
c += 1
return tercer_lugar
#------------------------------------------------------------------------------
# Está función se ubica al último de porque suma los puntos al ranking
# de los tres primeros de la competencia y luego va a parar al nuevo arreglo
def nuevo_arreglo(pri, seg, ter, participantes):
"""
Suma los puntos del ranking (25 al 1º, 15 al 2º y 5 al 3º)
:param pri, seg, ter, participantes: primero, segundo, tercero y el
vector de registros del tipo Participantes
:return: El nuevo vector de registro de tipo Participantes con las
modificaciones en el ranking
"""
pri.ranking += 25
seg.ranking += 15
ter.ranking += 5
return participantes |
a9c81ba963c8a3c9426971edfc9ac3dfeac00d01 | LeleCastanheira/cursoemvideo-python | /Exercicios/ex047.py | 100 | 3.625 | 4 | for n in range(2, 51, 2):
print(n, end=' ') #end = é pra escrever um número do lado do outro
|
7f5f33b40f1a8d3acc72c889bef1accf9432abb7 | rubenvdham/Project-Euler | /euler009/__main__.py | 833 | 4.4375 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def find_triplet_with_sum_of(number):
sum = number
number = int(number/2)
for a in range(1,number):
for b in range (a,number):
for c in range(b,number):
if (a**2 +b**2) == c**2:
if a+b+c == sum:
return a,b,c
def multiply(list):
answer = 1
for i in range (0,len(list)):
answer*=result[i]
return answer
if __name__ == '__main__':
result = find_triplet_with_sum_of(1000)
print("Triplet %s %s %s"%(result[0],result[1],result[2]))
print("product:%s"%(multiply(result)))
|
359773269fee557d0a513abace1283ac871af2a9 | BrickMyself/Python | /2020_5_24Test.py | 2,193 | 3.921875 | 4 | #任务一:设计一个 Circle 类来表示圆,
# 这个类包含圆的半径以及求面积和周长的函数。
# 再 使用这个类创建半径为 1~10 的圆,并计算出相应的面积和周长。
# 运行结果如下:
#半径为 1 的圆,面积: 3.14 周长: 6.28
# 半径为 2 的圆,面积: 12.57 周长: 12.57
# 半径为 3 的圆,面积: 28.27 周长: 18.85
# 半径为 4 的圆,面积: 50.27 周长: 25.13
# 半径为 5 的圆,面积: 78.54 周长: 31.42
# 半径为 6 的圆,面积: 113.10 周长: 37.70
# 半径为 7 的圆,面积: 153.94 周长: 43.98
# 半径为 8 的圆,面积: 201.06 周长: 50.27
# 半径为 9 的圆,面积: 254.47 周长: 56.55
# 半径为 10 的圆,面积: 314.16 周长: 62.83
#class Circle:
# def __init__(self, r):
# self.r = r
# def printSquare(self):
# print("半径为"+str(self.r)+"的圆,面积: "+'%.2f' %(3.1415*(self.r**2))+"周长: "+'%.2f' %(2*3.1415*self.r))
#for i in range(1, 11):
# c = Circle(i)
# c.printSquare()
#任务二:设计一个 Account 类表示账户,自行设计该类中的属性和方法,
#并利用这个类创 建一个账号为 998866,余额为 2000,
#年利率为 4.5%的账户,然后从该账户中存 入 150,取出 1500。
#打印出帐号、余额、年利率、月利率、月息。
class Account:
def __init__(self, number, money):
self.number = number
self.money = money
def storage(self, m):
self.money = self.money+m
print("存入" + '%d' %m + "元"+"你的余额为: " + '%d' % self.money)
def get(self, m):
self.money = self.money-m
print("取出" + '%d' % m + "元"+"你的余额为: " + '%d' % self.money)
def Print(self):
year = str(0.045)
month = str(0.00375)
anthony = str(self.money*0.00375)
print("您的账户: "+'%d' % self.number+" 的余额为: "+'%d' % self.money)
print("年利率为: " + str(year)+"月利率为 :" + str(month)+" 月息为:" + anthony)
person = Account(998866, 2000)
person.storage(150)
person.get(1500)
person.Print()
|
963ce62e914916093f6c07e47a1d63d5ce195dc2 | stevengonsalvez/python_training | /04_ListsTuplesDictionariesAndSets/Exercises_SourceCode/primes_alt_D.py | 1,872 | 3.890625 | 4 | # -*- coding:utf-8; -*-
'''A module providing some functions generating prime numbers.'''
__author__ = 'Russel Winder'
__date__ = '2013-03-03'
__version__ = '1.1'
__copyright__ = 'Copyright © 2012, 2013 Russel Winder'
__licence__ = 'GNU Public Licence (GPL) v3'
from math import sqrt
class Prime(object):
def __init__(self, value):
self.value = value
self.next = None
def process(self, value):
if value % self.value != 0:
if self.next is None:
self.next = Prime(value)
else:
self.next.process(value)
def deliver(self, result):
result.append(self.value)
return self.next.deliver(result) if self.next is not None else tuple(result)
def primesLessThan(maximum):
'''Return a tuple containing the primes less than maximum in ascending order.'''
if maximum <= 2:
return ()
start = Prime(2)
for i in range(3, maximum, 2):
start.process(i)
return start.deliver([])
def firstNPrimes(count):
'''Return a tuple containing the first count primes in ascending order'''
if count < 1:
return ()
start = Prime(2)
i = 3
while len(start.deliver([])) < count: # Horrendously inefficient.
start.process(i)
i += 2
return start.deliver([])
def sieveOfEratosthenes(maximum):
'''Return a tuple containing the primes less than maximum in ascending order.'''
# Actually this is not a Sieve algorithm, but we use the symbol improperly to try out this functional
# style list trimming algorithm. It will be horrendously slow but…
#### TODO: This works in Python 2 but not Python 3.
if maximum <= 2:
return ()
primes = range(2, maximum)
for i in range(2, int(sqrt(maximum)) + 1):
primes = filter(lambda x: x == i or x % i != 0, primes)
return tuple(primes)
|
64ba84d0a6089267233573ee1d4edfe9d04128b1 | timurridjanovic/data-structures | /graph/graph_depth_first.py | 905 | 3.828125 | 4 | ### Not done ####
graph = {
1: [2, 4], 2: [1, 3, 5], 3: [2, 11], 4: [1, 5, 7],
5: [2, 4, 6, 8], 6: [5, 9, 10], 7:[4, 13], 8: [5, 14],
9: [6, 12], 10: [6, 11], 11: [3, 10],
12: [9], 13: [7, 14], 14: [8, 13]
}
class Graph(object):
def find_path(self, start, end, graph):
open = [start]
closed = []
while len(open) > 0:
currentNode = open.pop()
closed.append(currentNode)
if currentNode == end:
print 'yay'
print closed
break
neighbors = graph[currentNode]
for neighbor in neighbors:
if neighbor not in closed:
open.append(neighbor)
g = Graph()
g.find_path(1, 12, graph)
print graph
|
a14474e5a769a60119b78ae772effd5b9d25343e | MohamedELfeky44/Tic-tac-toe | /Tic tac toe/Tic tac toe pygame.py | 10,378 | 3.734375 | 4 | import pygame
pygame.init() #initiate pygame
win = pygame.display.set_mode((800,550)) #set the window
pygame.display.set_caption("Tic tac toe") # set title
win.fill((255,255,255)) #set backgroud
start_button = pygame.draw.rect(win,(250,200,100),(550,30,200,150))
result_board = pygame.draw.rect(win,(250,200,100),(550,200,200,150))
score_board = pygame.draw.rect(win,(250,200,100),(550,370,200,150))
font = pygame.font.SysFont(None, 80)
start = font.render('Start', True, (0,0,255))
win.blit(start, (580,80))
#Create buttons
x = 30 #x position
y = 30 #Y position
h = 150 #height
w = 150 #wedith
#a variable to store in the value of the buttons
board = [[0,1,2],[3,4,5],[6,7,8]]
lst=[] #a list contains all buttons
for i in range(3):
for j in range(3):
lst.append(pygame.draw.rect(win,(0,0,0),((x+(w*j)+(20*j)),(y+(h*i)+(20*i)),w,h)))
def draw_x(x,y):
#this function draws X shape
pygame.draw.line(win,(255,0,0),(x,y),(x+100,y+100),15)
pygame.draw.line(win,(255,0,0),(x+100,y),(x,y+100),15)
def draw_o(x,y):
#this function draws O shape
pygame.draw.circle(win,(0,255,0),(x,y),50)
def reset():
lst=[]
for i in range(3):
for j in range(3):
lst.append(pygame.draw.rect(win,(0,0,0),((x+(w*j)+(20*j)),(y+(h*i)+(20*i)),w,h)))
def is_winner(p):
if board[0][0]== board[0][1] == board[0][2] == p or board[1][0]== board[1][1] == board[1][2] ==p or \
board[2][0]== board[2][1] == board[2][2] == p or board[0][0]== board[1][0] == board[2][0] ==p or \
board[1][1]== board[0][1] == board[2][1] == p or board[2][2]== board[1][2] == board[0][2] ==p or \
board[0][0]== board[1][1] == board[2][2] == p or board[0][2]== board[1][1] == board[2][0] ==p:
print("{} player wins".format(p))
return True
else : return False
first_choice = True
lst_of_choices = [True for i in range(9)] # list of choices for every cell
draw_object = "circle"
run = True
while run:
pygame.time.delay(10)
for event in pygame.event.get(): #checks the events and get them
if event.type == pygame.QUIT: #checks the exit button
run = False
if event.type == pygame.KEYDOWN: #checks the space button
if event.key == pygame.K_SPACE: #space button used to reset the screen
reset()
lst_of_choices = [True for i in range(9)]
result_board = pygame.draw.rect(win,(250,200,100),(550,200,200,150))
used_cells = 0
if event.type == pygame.MOUSEBUTTONUP: #checks the mouse click
pos = pygame.mouse.get_pos() #gets the position of the click of the mouse
#print(pos)
if start_button.collidepoint(pos):
s = True
used_cells=0
x_scoore = 0
o_scoore = 0
try:
if s:
print(x_scoore)
#
#
# asks if the click inside first button
if lst[0].collidepoint(pos) and lst_of_choices[0]:
used_cells += 1
if draw_object == "circle" :
draw_o(100,100)
draw_object = "line"
board[0][0] = "o"
else :
draw_x(50,50)
draw_object = "circle"
board[0][0] = "x"
lst_of_choices[0] = False
if lst[1].collidepoint(pos) and lst_of_choices[1] :
used_cells += 1
if draw_object == "circle":
draw_o(270,100)
draw_object = "line"
board[0][1] = "o"
else:
draw_x(220,50)
draw_object = "circle"
board[0][1] = "x"
lst_of_choices[1] = False
if lst[2].collidepoint(pos) and lst_of_choices[2]:
used_cells += 1
if draw_object == "circle":
draw_o(440,100)
draw_object = "line"
board[0][2] = "o"
else:
draw_x(390,50)
draw_object = "circle"
board[0][2] = "x"
lst_of_choices[2] = False
if lst[3].collidepoint(pos) and lst_of_choices[3]:
used_cells += 1
if draw_object == "circle":
draw_o(100,270)
draw_object = "line"
board[1][0] = "o"
else:
draw_x(50,220)
draw_object = "circle"
board[1][0] = "x"
lst_of_choices[3]= False
if lst[4].collidepoint(pos) and lst_of_choices[4] :
used_cells += 1
if draw_object == "circle":
draw_o(270,270)
draw_object = "line"
board[1][1] = "o"
else:
draw_x(220,220)
draw_object = "circle"
board[1][1] = "x"
lst_of_choices[4]= False
if lst[5].collidepoint(pos) and lst_of_choices[5]:
used_cells += 1
if draw_object == "circle":
draw_o(440,270)
draw_object = "line"
board[1][2] = "o"
else:
draw_x(390,220)
draw_object = "circle"
board[1][2] = "x"
lst_of_choices[5] = False
if lst[6].collidepoint(pos) and lst_of_choices[6] :
used_cells += 1
if draw_object == "circle":
draw_o(100,440)
draw_object = "line"
board[2][0] = "o"
else:
draw_x(50,390)
draw_object = "circle"
board[2][0] = "x"
lst_of_choices[6] = False
if lst[7].collidepoint(pos) and lst_of_choices[7] :
used_cells += 1
if draw_object == "circle":
draw_o(270,440)
draw_object = "line"
board[2][1] = "o"
else:
draw_x(220,390)
draw_object = "circle"
board[2][1] = "x"
lst_of_choices[7] = False
if lst[8].collidepoint(pos) and lst_of_choices[8] :
used_cells += 1
if draw_object == "circle":
draw_o(440,440)
draw_object = "line"
board[2][2] = "o"
else:
draw_x(390,390)
draw_object = "circle"
board[2][2] = "x"
lst_of_choices[8] = False
if is_winner("x"):
x_scoore +=1
score_board = pygame.draw.rect(win,(250,200,100),(550,370,200,150))
board = [[0,1,2],[3,4,5],[6,7,8]]
show_X="X wins"
result_x = font.render(show_X, True, (0,0,255))
win.blit(result_x, (560,250))
lst_of_choices = [False for i in range(9)]
elif is_winner("o"):
o_scoore +=1
score_board = pygame.draw.rect(win,(250,200,100),(550,370,200,150))
board = [[0,1,2],[3,4,5],[6,7,8]]
show="O wins"
result = font.render(show, True, (0,0,255))
win.blit(result, (560,250))
lst_of_choices = [False for i in range(9)]
elif used_cells == 9 :
draw = font.render("Draw", True, (0,0,255))
win.blit(draw, (560,250))
board = [[0,1,2],[3,4,5],[6,7,8]]
used_cells = 0
xstring= str(x_scoore) + "for x"
ostring = str(o_scoore) + "for o"
scored = font.render(xstring, True, (0,0,255))
win.blit(scored, (580,380))
scored2 = font.render(ostring, True, (0,0,255))
win.blit(scored2, (580,440))
else:
continue
except NameError:
pass
pygame.display.update() #update the surface
pygame.quit()
|
dde19b935c765c4368f5c1970ea2b010247519ba | TwisterMike15/Python-Projects | /CarrolaGorseMarietta.py | 944 | 4.09375 | 4 | #Python Program 1- Compound Interest
#Michael Gorse, Anthony Carrola, and Brittany Marietta
#Prints out a description of what the program does for user
print('This is a compound interest calculator. Enter the values for the variables')
print('in the compund interest equation, and this will produce the result for A')
print('(the amount of money in the account ater a specified number of years)\n')
#Reads in data for each variable as a string, then converts it to a float, so it can be manipulated
p = float(input('Enter P. It is the principle amount deposited into the account.'))
r = float(input('Enter r. This is the anual interest rate. Enter this value as a percentage \n(ie: 2.5 for 2.5% interest)'))
r = r/100
n = float(input('Enter n. This is the number of times per year the interest is compounded.'))
t = float(input('Enter t. This is the number of years.'))
#equation used to calculate a
a = p*(1+(r/n))**(n*t)
print('\nA is', a)
|
b4b27dfb0d7c88afd95ce1bda1c214a62191b7be | Jiaget/LeetCode-Python3 | /并查集模板.py | 886 | 3.828125 | 4 | class DisjointSet:
def __init__(self, length):
self.father = {i: i for i in range(1, length + 1)}
self.depth = 0
def add(self, x):
# 添加一个节点,该节点父节点应该为空
if x not in self.father:
self.father[x] = None
def find(self, x):
# 查找根节点
root = x
while self.father[root] != root:
root = self.father[root]
# 路径压缩,将x到root节点之间的所有节点直接和root节点相连
while x != root:
origFather = self.father[x]
self.father[x] = root
x = origFather
return root
def isConnected(self, x, y):
return self.find(x) == self.find(y)
def merge(self, x, y):
xRoot, yRoot = self.find(x), self.find(y)
if xRoot != yRoot:
self.father[xRoot] = yRoot |
cec0f9cf86a0a2f563b0dfe415fd5c97195d5749 | Dan-Teles/URI_JUDGE | /1255 - Frequência de Letras.py | 383 | 3.53125 | 4 | for _ in range(int(input())):
s = input().lower()
res = ""
l = [0]
for letra in s:
if letra.isalpha():
if s.count(letra) >= max(l):
l.append(s.count(letra))
for letra in s:
if s.count(letra) == max(l):
if not letra in res:
res += letra
print(''.join(sorted(res)).strip()) |
10655a3b1d978fb5760af7ddeb8a8287a566e8ee | TimMunday/BootCamp2018 | /ProbSets/Comp/Week1/PS_1/ComplexNumbertesting.py | 1,549 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 14:29:19 2018
@author: Tim
"""
from object_oriented import ComplexNumber
def test_ComplexNumber():
a=3
b=4
py_cnum, my_cnum = complex(a, b), ComplexNumber(a, b)
#Validate the constructor
if my_cnum.real != a or my_cnum.imag != b:
print("__init__() set self.real and self.imag incorrectly")
#Validate conjugate() by checking the new number's imag attribute
if py_cnum.conjugate().imag != my_cnum.conjugate().imag:
print('conjugate() failed for', py_cnum)
#Validate __str__()
if str(py_cnum) != str(my_cnum):
print("__str__() failed for", py_cnum)
#Validate __abs__()
if abs(py_cnum) != abs(my_cnum):
print('absolute value failed for', py_cnum)
#Validate __eq__()
if py_cnum != my_cnum:
print('equality failed')
#Validate __add__()
if py_cnum + py_cnum.conjugate() != my_cnum + my_cnum.conjugate():
print('Addition failed')
#Validate __sub__()
if py_cnum - py_cnum.conjugate() != my_cnum - my_cnum.conjugate():
print('Substituion failed')
print(py_cnum - py_cnum.conjugate())
print(my_cnum - my_cnum.conjugate())
#Validate__mul__()
if py_cnum*py_cnum.conjugate() != my_cnum*my_cnum.conjugate():
print('Mult failed')
#Validate__truediv__()
if py_cnum/py_cnum.conjugate() != my_cnum/my_cnum.conjugate():
print('Div failed')
print('test ended')
test_ComplexNumber()
|
3f28fc6d3b9ac9b6bbd109f1f9d2ceae5eec3b3b | jaydicine/Python | /POTW Sum of Digits.py | 563 | 3.828125 | 4 |
total = 0
#function to sum digits of a number
def digsum(number):
number=str(number)
sum=0
for i in range(0,len(number)):
digit = number[i]
sum += int(digit)
return(sum)
# loop function for all 3 digit integers
for n in range(100,999):
# check if sum is 5
if digsum(n) == 5:
print(n, digsum(n))
total += 1
# if sum is not 5, check if sum of sum digits is 5 ex. 14, 23
elif digsum(digsum(n)) == 5:
print(n, digsum(n))
total += 1
print(total)
|
2c43eba9b426653ed42a69d751e1873b89b51976 | chanyoonzhu/leetcode-python | /1482-Minimum_Number_of_Days_to_Make_m_Bouquets.py | 1,765 | 3.640625 | 4 | class Solution:
"""
- binary search + greedy
- O(nlogK), O(1) - K is the largest bloom day
"""
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
days = max(bloomDay)
def binary_search(l, r):
if l == r:
return l
mid = l + (r - l) // 2
if can_make(mid):
return binary_search(l, mid)
else:
return binary_search(mid + 1, r)
def can_make(target_day):
bouquets = 0
flowers = 0
for day in bloomDay:
if day > target_day:
flowers = 0
else:
bouquets += (flowers + 1) // k
if bouquets == m:
return True
flowers = (flowers + 1) % k
return False
""" my initial solution for can_make function
def can_make(target_day):
is_consecutive = True
bouquets = 0
current_bloom = 0
for day in bloomDay:
if day <= target_day:
if is_consecutive:
current_bloom += 1
else:
current_bloom = 1
is_consecutive = True
if current_bloom == k:
bouquets += 1
if bouquets >= m:
return True
current_bloom = 0
else:
is_consecutive = False
return False
"""
if m * k > len(bloomDay):
return -1
return binary_search(1, days)
|
e6b8dd911d626ecb9989f5e538b2df1fe7325975 | aviadba/eureka_signalprocessing | /udemySignalProcessing.py | 40,488 | 3.5 | 4 | """
udemysignal - Udemy Signal Processing course root file - contains
all the implemented signal processing classes. For GUI, use through udemysignal
tabs classes and generic GUI framework
"""
import numpy as np
import scipy.signal
from scipy.interpolate import interp1d
from scipy.signal import *
#welch, spectrogram, firwin, butter, filtfilt, morlet, ricker
# Base Signal generating class
class Signal:
def __init__(self):
self.time = None
self.signal = None
self.sample_frequency = None
self.domain = 'time'
def create_signal(self, stype='poles', sample_frequency=1000, time=3, poles=15,
interp='linear', amplitude=1):
"""Create a simulated signal
Parameters:
stype : {'poles', 'spikes', 'white noise', 'lintrend', 'polytrend',
'events', 'sum_frequencies', 'guassian', 'brownian'}
type of signal to create
sample_frequency : float
signal rate in Hz
time : float
signal length in seconds
poles : int
number of random poles in 'poles' signal, or number of spikes in spikes mode or deg of polynomial
interp {'linear', 'cubic'}
modes of interpolation
amplitude : float
amplitude of max pole signal
"""
# create time vector
self.time = np.arange(0, time, 1/sample_frequency)
self.sample_frequency = sample_frequency
# save amplitude as an object property
self.amplitude = amplitude
if stype == 'poles':
# create a signal by interpolating values between randomly selected
# poles
if interp == 'linear':
self.signal = np.interp(np.linspace(0, poles-1, len(self.time)), # interpolate at these values
# define poles
np.arange(0, poles),
np.random.rand(poles)*amplitude)
elif interp == 'cubic':
signal_fun = interp1d(np.arange(0, poles),
np.random.rand(poles)*amplitude,
kind='cubic')
signal_x = np.linspace(0, poles-1, len(self.time))
self.signal = signal_fun(signal_x)
elif stype == 'spikes':
# create randomly distributes spikes
inter_spike_distance = np.exp(np.random.randn(poles))
inter_spike_distance = \
np.round(sample_frequency*time/inter_spike_distance.sum()
* inter_spike_distance)
distribution_tail = inter_spike_distance.sum() - \
(sample_frequency*time - 1)
if distribution_tail > 0:
inter_spike_distance[0] = inter_spike_distance[0] -\
distribution_tail
signal = np.zeros(int(sample_frequency*time))
idx = 0
for distance in inter_spike_distance:
idx += int(distance)
signal[idx] = 1
self.signal = signal * amplitude
elif stype == 'white noise':
self.signal = amplitude*np.random.randn(int(sample_frequency*time))
elif stype == 'lintrend':
trend = 10*amplitude*np.random.random()
self.signal = np.linspace(-trend,
trend, int(sample_frequency*time))
elif stype == 'polytrend':
base_signal = np.zeros(int(sample_frequency*time))
for deg in range(poles):
base_signal += np.random.randn()*self.time**deg
self.signal = base_signal
elif stype == 'events':
# create and scale an event
event_ratio = 0.3 # ratio of signal occupied by 'events'
event_length = int(sample_frequency*time/poles*event_ratio)
event = np.diff(np.exp(np.linspace(-2, 2, event_length+1)**2))
event = event/max(event)*amplitude
event_start_idx = \
np.random.permutation(
range(int(sample_frequency*time)-event_length))[:poles]
base_signal = np.zeros(int(sample_frequency*time))
for idx in event_start_idx:
base_signal[idx:idx+event_length] = event
self.signal = base_signal
elif stype == 'sum_frequencies':
base_signal = np.zeros(int(sample_frequency*time))
freqs = np.linspace(0, time, time*sample_frequency)
# select frequencies to include
selected_signal_frequencies = \
np.random.permutation(
range(1, int(sample_frequency/2)))[:poles]
for instance_freq in selected_signal_frequencies:
base_signal += np.random.randn()*np.sin(2*np.pi*instance_freq*freqs)
self.signal = base_signal
elif stype == 'guassian':
# create randomly distributes centers
guass_center_distance = np.exp(np.random.randn(poles))
if len(guass_center_distance) == 1:
guass_center_distance = \
np.round(sample_frequency*time/3 *
abs(guass_center_distance))
else:
guass_center_distance = \
np.round(sample_frequency*time/guass_center_distance.sum()
* guass_center_distance)
distribution_tail = guass_center_distance.sum() - \
(sample_frequency*time - 1)
if distribution_tail > 0:
guass_center_distance[0] = guass_center_distance[0] -\
distribution_tail
guass_center_distance = np.cumsum(guass_center_distance)
base_signal = np.zeros(int(sample_frequency*time))
signal_idx = range(int(sample_frequency*time))
for distance in guass_center_distance:
instance_signal_idx = [
i_idx - distance for i_idx in signal_idx]
instance_signal_idx = np.array(instance_signal_idx)
instance_sigma = 0.1*sample_frequency*time*np.random.random()
instance_guassian = \
1/(instance_sigma*(2*np.pi)**0.5) * \
np.exp(-0.5*(instance_signal_idx/instance_sigma)**2)
base_signal += instance_guassian
self.signal = base_signal
elif stype == 'brownian':
base_signal = np.random.randn(int(sample_frequency*time))
base_signal = np.cumsum(base_signal)
self.signal = base_signal
# Base load signal class
class Loadsignal:
def __init__(self):
self.time = None
self .signal = None
self.source_signal = None
self.sample_frequency = None
self.domain = 'time'
def load_signal(self, path_to_signal, sigtype='orig', domain='time'):
"""
Load saved signal from .npy files. Supports loading a reference file
to practice cascade processing with a reference target.
Parameters
path_to_signal : string
relative path to data file
sigtype : {'orig', 'ref'}
the type of signal being loaded. Can take the value of 'orig' (original signal) or 'ref' (reference signal after corrections)
"""
raw_signal = np.squeeze(np.load(path_to_signal))
if len(raw_signal.shape) == 2: # array with time and counts
# find smaller dimension
main_data_axis = np.argmin(raw_signal.shape)
if main_data_axis == 0:
time = np.squeeze(raw_signal[0, :])
signal = np.squeeze(raw_signal[1, :])
else:
time = np.squeeze(raw_signal[:, 0])
signal = np.squeeze(raw_signal[:, 1])
else: # time vector not available, default to 1 sec per data4TFnpy
signal = raw_signal
time = np.arange(0, signal.shape[0])
if domain == 'time':
sample_frequency = 1/np.mean(np.diff(time))
if sigtype == 'orig':
self.signal = signal
self.time = time
self.domain = domain
self.sample_frequency = sample_frequency
elif sigtype == 'ref':
self.source_signal = Signal()
self.source_signal.signal = signal
self.source_signal.time = time
self.source_signal.domain = domain
self.source_signal.sample_frequency = sample_frequency
# Add simulated noise of several types to a base signal
class Noise:
def __init__(self, source_signal):
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.domain = 'time'
self.sample_frequency = source_signal.sample_frequency
def add_noise(self, noise_amplitude=1, ntype='rand',
noise_sample_ratio=0.1):
"""
Add noise or other kind of signal interference to the signal
Parameters:
ntype : {'rand', 'normal' , 'pink'}
Noise type to add. 'rand' for randomly distributed noise,
'nrand' for normally distributed noise
'pink' noise distributed with 1/alpha*f distribution (pink noise)
'irregular' downsample the data in irregular intervals
'gap' create a gap in the data
noise_amplitude : float
noise max level in 'standard deviation' units
noise_sample_ratio : float
ratio of point final/points original in creating irregular
sequence or the ratio of gapped data to total signal length
"""
# get standard deviation of signal
noise_amplitude = noise_amplitude*np.std(self.source_signal.signal)
# create noise
if ntype in {'rand', 'normal', 'pink'}:
if ntype == 'rand':
noise = \
noise_amplitude * \
np.random.rand(len(self.source_signal.signal))
elif ntype == 'normal':
noise = \
noise_amplitude * \
np.random.randn(len(self.source_signal.signal))
elif ntype == 'pink':
# create frquency vector
frequency = np.linspace(-len(self.source_signal.signal)//2,
len(self.source_signal.signal)//2,
len(self.source_signal.signal))
pink = 1/frequency
# set pink nan to zero
phase = 2 * np.pi * \
np.random.rand(len(self.source_signal.signal)//2)
# pink = pink * np.exp(-1j
self.signal = self.source_signal.signal + noise
elif ntype == 'irregular':
num_points = \
np.round(irregular_sample_ratio*len(self.source_signal.signal))
intervals = np.exp(np.random.randn(int(num_points)))
intervals = np.cumsum(intervals)
intervals = intervals * \
(len(self.source_signal.signal)-1)/intervals[-1]
intervals = (np.ceil(intervals)).astype(int)
intervals[-1] = len(self.source_signal.signal)-1
self.signal = self.source_signal.signal[intervals]
self.time = self.source_signal.time[intervals]
self.sample_frequency = \
self.sample_frequency*irregular_sample_ratio
elif ntype == 'gap':
gap_length = int(len(self.source_signal.time)*noise_sample_ratio)
gap_start_idx = int(len(self.source_signal.time)/2 - gap_length/2)
gap_end_idx = int(len(self.source_signal.time)/2 + gap_length/2)
time = self.source_signal.time
signal = self.source_signal.signal
time = np.delete(time, range(gap_start_idx, gap_end_idx))
signal = np.delete(signal, range(gap_start_idx, gap_end_idx))
self.time = time
self.signal = signal
# Time domain filters
class Filter:
def __init__(self, source_signal):
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.domain = 'time'
self.sample_frequency = source_signal.sample_frequency
def running_filter(self, ftype='mean', order=3, edge='copy'):
"""Sets the value in a filtered signal according to the values of
neighbors
Arguments
---------
ftype <str> type of filter. Options are: 'mean' 'gaussian' , tkeo
(Teager-Kaiser energy operator), 'median'
order <int> the number of neighbors to consider when calculating the
mean value
edge <string> - defines how to deal with edges. possibilities are
'copy', 'crop'
"""
# find length of signal
signal_length = len(self.source_signal.time)
# allocate memory for for signals and time
signal = np.zeros(signal_length)
if ftype == 'mean':
for idx in range(order, signal_length-order):
signal[idx] = np.mean(
self.source_signal.signal[idx-order:idx+order+1])
elif ftype == 'gaussian':
gaussain_ker = np.arange(-(order), (order+1), 1)
gaussain_ker = np.exp(-(4*np.log(2)*gaussain_ker**2) / (order)**2)
gaussain_ker = gaussain_ker/gaussain_ker.sum()
for idx in range(order, signal_length-order):
signal[idx] = \
(self.source_signal.signal[idx -
order:idx+order+1]*gaussain_ker).sum()
elif ftype == 'tkeo':
# set order to 1 for edge effect actions
order = 1
for idx in range(1, signal_length-1):
signal[idx] = self.source_signal.signal[idx]**2 -\
self.source_signal.signal[idx-1] * \
self.source_signal.signal[idx+1]
signal = signal/np.max(signal)*np.max(self.source_signal.signal)
elif ftype == 'median':
for idx in range(order, signal_length-order):
signal[idx] = np.median(
self.source_signal.signal[idx-order:idx+order+1])
if edge == 'copy':
signal[:order] = self.source_signal.signal[:order]
signal[signal_length-order:] = \
self.source_signal.signal[signal_length-order:]
self.signal = signal
self.time = self.source_signal.time
elif edge == 'crop':
self.signal = signal[order:signal_length-order]
self.time = self.source_signal.time[order:signal_length-order]
# Linear and polynomial detrending of time domain data
class Detrend:
def __init__(self, source_signal):
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.domain = 'time'
self.sample_frequency = source_signal.sample_frequency
def detrend(self, method='linear'):
"""detrend signals
Arguments
---------
method <str> detrending method. Allowed values are' 'linear' (least
square fit of the data, 'polynomial' polynomial fitting with Bayes
information criterion to find best deg
"""
if method == 'linear':
self.signal = scipy.signal.detrend(
self.source_signal.signal, type='linear')
self.time = self.source_signal.time
elif method == 'polynomial':
# use Bayes information criterion
deg_max = 10
bic = []
bic_score = []
signal_l = len(self.source_signal.time)
for deg in range(deg_max):
ifit = np.polyfit(self.source_signal.time,
self.source_signal.signal, deg=deg, full=True)
score = signal_l*np.log(ifit[1])+(deg+1)*np.log(signal_l)
bic.append(ifit)
bic_score.append(score)
# find indices of min val
deg = np.argmin(bic_score)
# get fitting polynomial coeffecients
pol_coeff = bic[deg][0]
detrend = np.zeros(len(self.source_signal.signal))
for idx, coef in enumerate(pol_coeff):
detrend += coef*self.source_signal.time**(deg-idx)
self.signal = self.source_signal.signal - detrend
self.time = self.source_signal.time
# FFT
class FFTsignal:
def __init__(self, source_signal):
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.domain = source_signal.domain
self.sample_frequency = source_signal.sample_frequency
self.time_scaling = 1 # for dealing with frequency sub sampling
def fft_signal(self):
"""Create the frequency domain representation of a time domain or the
time domain representation f a frequency domain signal
"""
if self.source_signal.domain == 'time':
# create time vector
self.signal = np.fft.fft(self.source_signal.signal, norm='ortho')
frequencies = np.fft.fftfreq(self.time.size,
d=np.gradient(self.time).mean())
self.time = frequencies
self.domain = 'frequency'
elif self.source_signal.domain == 'frequency':
self.signal = np.fft.ifft(self.source_signal.signal, norm='ortho')
self.signal = self.signal.real
time = np.linspace(0,
len(self.time)/(2*max(abs(self.time))) *
self.source_signal.time_scaling,
len(self.time))
self.time = time
self.domain = 'time'
# save amplitude as an object property
self.amplitude = None
def welch_signal(self, window_size=1024):
"""calculate the Fourier Transform using Welch's method of
averaging multiple spectra
Arguments
---------
window_size <int> the size of window over which a FFT is calculated
"""
welch_freq, welch_signal = welch(self.source_signal.signal, window='hanning', nperseg=window_size,
return_onesided=False)
frequencies = np.fft.fftfreq(welch_signal.size,
d=np.gradient(self.time).mean())
self.signal = welch_signal
self.time = frequencies
self.time_scaling = self.source_signal.time.size/window_size
self.domain = 'frequency'
def spectrogram_signal(self, window_size=1024):
"""Copute the time dependant spectrogram of a signal
Arguments
---------
window_size <int> size of window to use
"""
spectro_freq, spectro_time, spectro_vals = \
spectrogram(x=self.source_signal.signal, nperseg=window_size)
self.signal = spectro_vals
self.time = spectro_time
self.spectrogram_frequencies = spectro_freq
self.domain = 'spectrogram'
def wavelet_cwt(self, wavelet='morlet'):
"""
Preform a continuous wavelet transform of the data
Parameters
wavelet : {'morlet', 'ricker'}
the type of wavelet to use. Morlet or Ricker (mexican hat)
"""
# define frequency resolution
if wavelet == 'morlet':
wavelet = morlet
elif wavelet == 'ricker':
wavelet = ricker
widths = np.arange(2, self.source_signal.sample_frequency//2)
cwt_matr = np.abs(cwt(self.source_signal.signal, wavelet, widths))**2
self.signal = cwt_matr
self.spectrogram_frequencies = widths
self.domain = 'spectrogram'
# Filters operating in the frequency domain
class Freqfilter:
def __init__(self, source_signal):
"""Filters defined in the frequency domain. Operate in the time domain.
Class allows comparing the resulting filter to the expected filter.
Filters are then applied using filtfilt (zero phase shift) to the
source_signal data"""
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.domain = 'time'
self.sample_frequency = source_signal.sample_frequency
self.filter = None # the filter representation in the time domain
self.filterfreq = None # the filter representation in the frequqnecy domain
def fir_filter(self, window='boxcar', order=73, frange=[None, None]):
"""Apply the FIR (Finite impulse response) filter using the specified method
Arguments
---------
window <str> - tapering window to use. Allowed values are 'none',
'hann', 'hamming', 'guassian'
order <int> - size of filter
frange <lst(2)>: band pass rise and fall or rise/fall for high/low pass
"""
# create window
if window == 'gaussian':
window = ('guassian', order/6)
# create filter
if frange[0]:
if frange[1]: # bandpass filter
if frange[0] > frange[1]:
fir_filter = firwin(numtaps=order,
cutoff=[frange[1], frange[0]],
pass_zero=True,
window=window,
scale=True)
elif frange[1] > frange[0]:
fir_filter = firwin(numtaps=order,
cutoff=frange,
pass_zero=False,
window=window,
scale=True)
self.filterfreq = ['bandpass', frange]
else: # highpass filter
fir_filter = firwin(
numtaps=order, cutoff=frange[0], pass_zero=False,
window=window, scale=True)
self.filterfreq = ['highpass', frange[0]]
else:
if frange[1]: # lowpass filter
fir_filter = firwin(
numtaps=order, cutoff=frange[1], pass_zero=True,
window=window, scale=True)
self.filterfreq = ['lowpass', frange[1]]
# save filter
self.filter = fir_filter
# filtered signal
self.signal = np.convolve(
self.source_signal.signal, fir_filter, mode='same')
self.time = self.source_signal.time
def iir_filter(self, order=9, frange=[None, None]):
"""Implemetation of IIR filter
Arguments
---------
order <int> - the order of the filter
frange <lst(2)>: band pass rise and fall or rise/fall for high/low pass
ftype <str> - filter tyepe. Allowed options are 'lowpass'
, 'highpass', 'bandpass'
"""
# create filter
if frange[0]:
if frange[1]: # bandpass filter
if frange[0] > frange[1]:
iir_filter = butter(
N=order, Wn=[frange[1], frange[0]], btype='bandstop')
elif frange[1] > frange[0]:
iir_filter = butter(N=order, Wn=frange, btype='bandpass')
self.filterfreq = ['butterpass', frange]
else: # highpass filter
iir_filter = butter(N=order, Wn=frange[0], btype='highpass')
self.filterfreq = ['butterhigh', frange[0]]
else:
if frange[1]: # lowpass filter
iir_filter = butter(N=order, Wn=frange[1], btype='lowpass')
self.filterfreq = ['butterlow', frange[1]]
# create impulse
impulse = np.zeros(len(iir_filter[0])*len(iir_filter[1]))
impulse[(len(iir_filter[0])*len(iir_filter[1]))//2] = 1
impulse_response = filtfilt(iir_filter[0], iir_filter[1], impulse)
# save filter
self.filter = impulse_response
# filtered signal
self.signal = filtfilt(iir_filter[0], iir_filter[1],
self.source_signal.signal)
self.time = self.source_signal.time
# Convolution
class Convolution:
def __init__(self, source_signal):
"""Convolve signal with a kernel
"""
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.domain = 'time'
self.filter = None # the filter representation in the time domain
self.sample_frequency = source_signal.sample_frequency
def convolve(self, ktype='guassian', kradius=None):
"""Apply a convolution kernel on the signal
Parameters:
ktype : {'guassian', 'mean', 'linear'}
The convolution kernel type.
'guassian', 'linear' (linear decay function),
'mean', 'morlet' (real), 'ricker' (mexican hat)
kradius : int
radius of convolution kernel in sampling units. Actual width is
2*kradius+1
"""
kernel_base = np.arange(-kradius, kradius+1)
# create the convolution kernel
if ktype == 'guassian':
kernel = np.exp(- (kernel_base**2)/(2 * (0.3*kradius)**2))
# normalize kernel
self.filter = kernel/np.sum(kernel)
elif ktype == 'mean':
self.filter = np.ones(2*kradius+1)/(2*kradius+1)
elif ktype == 'linear':
kernel = np.linspace(start=1, stop=0.1, num=(2*kradius+1),
endpoint=True)
kernel = kernel - np.mean(kernel)
self.filter = kernel
elif ktype == 'morlet':
self.filter = morlet(M=(2*kradius+1))
elif ktype == 'ricker':
self.filter = ricker(points=(2*kradius+1), a=0.3*kradius)
# apply convolution
self.signal = np.convolve(self.source_signal.signal,
np.real(self.filter),
mode='same')
# Resample
class Resample:
def __init__(self, source_signal):
"""Resample signal
"""
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.sample_frequency = source_signal.sample_frequency
self.domain = 'time'
def resample(self, factor=None, new_sample_rate=None, method='linear'):
"""Resample data
Parameters
factor : int
new data sampling rate will be factor * sampeling. if
factor>1 data is upsampled, if factor<1 data is
downsampled. If data is downsampled, original if initially
low-pass filtered at the new nyquist freq to avoid
aliasing. Use this value or new_sample_rate
new_sample_rate : float
new target sampling rate. User either this value or factor
method : {'linear', 'cubic', 'nearest'}
method of interpolation
"""
if factor:
new_sample_rate = self.source_signal.sample_frequency * factor
elif new_sample_rate:
factor = new_sample_rate/self.source_signal.sample_frequency
else: # default to max sample rate in data
delta_time = np.diff(self.source_signal.time)
new_sample_rate = 1/np.min(delta_time)
factor = 1
self.sample_frequency = new_sample_rate
#downsampling: anitaliasing
if self.sample_frequency < self.source_signal.sample_frequency:
num_samples_resample = \
int(self.sample_frequency/self.source_signal.sample_frequency *
len(self.source_signal.signal))
self.signal, self.time = resample(x=self.source_signal.signal,
num=num_samples_resample,
t=self.source_signal.time)
else:
# create new time series
self.time = np.arange(self.source_signal.time[0],
self.source_signal.time[-1],
1/new_sample_rate)
# interpolate new points
interpolation_function = interp1d(self.source_signal.time,
self.source_signal.signal, kind=method)
# calculate new signal
self.signal = interpolation_function(self.time)
def fill_gaps(self):
"""fill gaps in data
fill_gaps for gapped data, uses the mean power spectrum of data
before gap and after gap (representing sequences the same
length of the gap, detrending and adding a trend to
represent last/first known points
"""
# find of gap
time_gaps = np.diff(self.source_signal.time)
gap_start_idx = np.argmax(time_gaps)
# find gap border values
gap_start_value = self.source_signal.signal[gap_start_idx]
gap_end_value = self.source_signal.signal[gap_start_idx+1]
# gap_length = self.source_signal.time[gap_start_idx +
# 1] - self.source_signal.time[gap_start_idx]
# create time sequence
simulated_series_time = np.arange(start=self.source_signal.time[gap_start_idx],
stop=self.source_signal.time[gap_start_idx+1],
step=1/self.source_signal.sample_frequency)
len_gap = len(simulated_series_time)
# get FFT of sequence before gap
pre_gap_fft = \
np.fft.fft(self.source_signal.signal[gap_start_idx-len_gap:gap_start_idx],
norm='ortho')
# get FFT of sequences after the gap
post_gap_fft = \
np.fft.fft(self.source_signal.signal[gap_start_idx+1:gap_start_idx+1+len_gap],
norm='ortho')
# find mean spectrum
mean_gap_spectrum = (pre_gap_fft + post_gap_fft)/2
gap_sequence = np.abs(np.fft.ifft(mean_gap_spectrum, norm='ortho'))
# detrend gap sequence
gap_sequence = detrend(gap_sequence, type='linear')
# add trend to data
base_gap_signal = np.linspace(gap_start_value-gap_sequence[0],
gap_end_value-gap_sequence[-1],
len(simulated_series_time))
gap_sequence += base_gap_signal
self.signal = np.concatenate((self.source_signal.signal[:gap_start_idx-1],
gap_sequence,
self.source_signal.signal[gap_start_idx+2:]))
self.time = \
np.concatenate((self.source_signal.time[:gap_start_idx-1],
simulated_series_time,
self.source_signal.time[gap_start_idx+2:]))
def remove_nan(self):
"""remove nan values from signal and time data"""
nan_bool = np.isnan(self.source_signal.signal)
# keep only non nan
self.signal = self.source_signal.signal[~nan_bool]
self.time = self.source_signal.time[~nan_bool]
class Outliers:
def __init__(self, source_signal):
"""Outliers
"""
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.sample_frequency = source_signal.sample_frequency
self.domain = 'time'
def remove_outliers(self, method='static', metric='std', factor=3, kind='linear',
window_ratio=0.05):
"""remove outliesrs from data
Parameters
method : {'static', 'rolling'}
method of outlier identification
metric : {'std', 'rms'}
factor : int
outlier definition boundary factor (SD or RMS units)
kind : {'linear', 'nearest', 'previous', 'cubic', 'quadratic'}
interpolation method
window : float
the relative size of window for rolling calculations
"""
if method == 'static':
if metric == 'std':
metric = np.std(self.source_signal.signal)
elif metric == 'rms':
metric = self.source_signal.signal - \
np.mean(self.source_signal.signal)
metric = (np.mean(metric**2))**0.5
mean = np.mean(self.source_signal.signal)
outliers = np.logical_or(self.source_signal.signal > mean+factor*metric,
self.source_signal.signal < mean-factor*metric)
elif method == 'rolling':
window = int(len(self.source_signal.signal)*window_ratio)
outliers = np.array([False]*len(self.source_signal.signal))
last_data_idx = len(self.source_signal.signal)-1
for idx in range(len(self.source_signal.signal)):
upper_limit = np.amin((idx+window, last_data_idx))
lower_limit = np.amax((idx-window, 0))
instance_range = self.source_signal.signal[lower_limit:upper_limit]
# np.concatenate([self.source_signal.signal[idx-window:idx],
# self.source_signal.signal[idx+1:idx+window]])
value = self.source_signal.signal[idx]
if metric == 'std':
upper_b = np.mean(instance_range) + \
factor*np.std(instance_range)
lower_b = np.mean(instance_range) - \
factor*np.std(instance_range)
elif metric == 'rms':
metric = instance_range - np.mean(instance_range)
metric = (np.mean(metric**2))**0.5
upper_b = np.mean(instance_range) + factor*metric
lower_b = np.mean(instance_range) - factor*metric
if value > upper_b or value < lower_b:
outliers[idx] = True
interpolator = interp1d(self.source_signal.time[~outliers],
self.source_signal.signal[~outliers], kind=kind,
bounds_error=False, fill_value='extrapolate')
for idx in np.nditer(np.argwhere(outliers)):
idx = int(idx)
self.signal[idx] = interpolator(self.time[idx])
self.domain = 'time'
def map_noise_regions(self, metric='rms'):
"""Create a map of RMS values vs window size used. Calculations are
carried out for windows ranging from 0.01 to 0.2 of the data length in
0.01 increments
Parameters
metric : {'rms', 'std'}
"""
# get rms for the entire data signal
num_test_windows = 20
window_increment = 0.01
ratio_ranges = np.arange(start=0.01,
stop=(num_test_windows+1)*window_increment,
step=window_increment)
# initialize empty results window
result_map = np.full((num_test_windows,
len(self.source_signal.signal)), np.nan)
last_data_idx = len(self.source_signal.signal)-1
window_selection_idx = num_test_windows-1
for win_size_ratio in np.nditer(ratio_ranges):
window = int(len(self.source_signal.signal)*win_size_ratio)
for idx in range(len(self.source_signal.signal)):
upper_limit = np.amin((idx+window, last_data_idx))
lower_limit = np.amax((idx-window, 0))
instance_range = self.source_signal.signal[lower_limit:upper_limit]
value = self.source_signal.signal[idx]
if metric == 'std':
result_map[window_selection_idx,
idx] = np.std(instance_range)
elif metric == 'rms':
# mean center instance range
instance_range = instance_range - np.mean(instance_range)
result_map[window_selection_idx, idx] = (
np.mean(instance_range**2))**0.5
window_selection_idx -= 1
self.domain = 'spectrogram'
self.spectrogram_frequencies = ratio_ranges
self.signal = result_map
class Features:
def __init__(self, source_signal):
"""Features
"""
self.source_signal = source_signal
self.signal = source_signal.signal.copy()
self.time = source_signal.time.copy()
self.sample_frequency = source_signal.sample_frequency
self.domain = 'time'
def find_extrema(self, extrema='max', method='global', order=100):
"""Find maxima/minima in signal
Parameters
extrema : {'max', 'min'}
method : {'global', 'local'}
method of extrema detection
order : int
how many points on each side to consider for local extrema
"""
if method == 'global':
if extrema == 'max':
extremaindx = np.argmax(self.source_signal.signal)
elif extrema == 'min':
extremaindx = np.argmin(self.source_signal.signal)
self.signal = np.array([self.source_signal.signal[extremaindx]])
self.time = np.array([self.source_signal.time[extremaindx]])
elif method == 'local':
if extrema == 'max':
comparator = np.greater
elif extrema == 'min':
comparator = np.less
# signal.signal.argrelextrema
extremaindx = argrelextrema(data=self.source_signal.signal,
comparator=comparator,
order=order)
# create a point set signal of extrema
self.signal = self.source_signal.signal[extremaindx]
self.time = self.source_signal.time[extremaindx]
def find_envelope(self, method='hilbert_transform', order=99, cutoff=0.1):
"""find the envelope of a signal. Note: to asses the different
envelopes, calculate R^2 with the rectified signal.
Parameters
method : {'hilbert_transform', 'varaince_envelope'}
cutoff : float
the cutoff of the low pass filter in nyquist rate ratio
order : float
the size of the lowpass filter
"""
if method == 'hilbert_transform':
# Hilbert transform - rectify, lowpass filter
hilbert_transform = hilbert(self.source_signal.signal)
self.signal = np.abs(hilbert_transform)
self.time = self.source_signal.time
elif method == 'variance_envelope':
# rectify signal
signal = np.abs(self.source_signal.signal)
# create low pass filter
fir_filter = firwin(
numtaps=order, cutoff=cutoff, pass_zero=True,
window='hamming', scale=True)
self.signal = np.convolve(fir_filter, signal,
mode='same')
self.time = self.source_signal.time
def feature_by_wavelets(self, wavelet='DoG'):
"""Convolve signal with a wavelet to find features
Parameters
wavelet : {'DoG'}
name of wavelet
width: int
fwhm
"""
if wavelet == 'DoG':
breakpoint()
wavelet_time = np.linspace(-3, 3,
int(self.source_signal.sample_frequency/2))
wavelet = np.diff(np.exp(-wavelet_time**2))
elif wavelet == 'ricker':
wavelet = ricker(100, width)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.