blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1cf43c3c2e4ca2e790259cfd6d74a0976059281b | simonvidal/Python | /tuplas.py | 1,004 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# Autor: Enmanuel Cubillan
# Tuplas en Python
mi_tupla = (1,'Enmanuel')
print 'Mostrando un elemento de la tupla:',mi_tupla[1]
print 'Tupla:',mi_tupla
# convierte una lista en tupla
# método list
mi_lista = list(mi_tupla)
print 'Tupla convertida en Lista:',mi_lista
# convierte una tupla en lista
# método tuple
lista = [2,1992,2,'Alexander']
tupla = tuple(lista)
print 'Lista convertida en Tupla:',tupla
# comprobar si hay elemento en la tupla
print 'Alexander' in tupla
# para saber cuantos veces se encuentra un elemento en la tupla
# count
print 'Cuantas veces se encuentra un elemento en la tupla:',tupla.count(2)
# longitud de una tupla
# len
print 'Longitud de la tupla:',len(tupla)
# tuplas unitarias
tupla_unitaria = 'Luz',
print 'Tupla unitaria:',len(tupla_unitaria)
# desempaquetado de tupla
d_tupla = ('Enmanuel',4,4,1994)
nombre, dia, mes, ano = d_tupla
print '\nDesempaquetado de tupla:'
print 'Nombre:',nombre
print 'Dia:',dia
print 'Mes:',mes
print 'Año:',ano
|
7058760172fc808ce28cac36e8d8b2aee2378940 | caesarjuming/PythonLearn | /com/test1.py | 4,806 | 3.890625 | 4 | __author__ = 'Administrator'
# python处理的每一样东西都是对象,像模块,函数,类都是对象。
# Python是强类型的,也就是只能对相应类型做相应的操作,例如只能对字符串进行字符串操作,但他是动态类型
# python数字类型有整数,浮点类型,复数,十进制数,有理分数,集合等
print(1+1)
print(2.11+3)
print(2*4)
print(2**3)
import math
print(math.pi)
print(math.sqrt(4))
import random
print(random.random())
print(random.choice([1,2,3,4]))
# 字符串
name = 'jack'
print(name)
print(name[0])
print(len(name))
print(name[-1])
print(name[len(name)-1])
# 分片,取出1到3之间的字符,不包括3,return a new object
print(name[1:3])
print(name[1:])
print(name[:])
print(name[:3])
print(name[:-1])
print(name*8)
print("hello,"+name)
# it's wrong //print(1+"hello"),不能两种类型进行相加
# 不可变性
firstName = "caesar"
# firstName[1] = "b" it doesn't work
print(firstName[1]+'z')
# 类型特定方法
print(firstName.find('c'))
print(firstName.find('z'))
print(firstName.replace('c', '@'))
print(firstName)
str1 = "aaa,bbb,ccc,ddd"
print(str1.split(',')[1])
print(str1.upper())
print(str1.lower())
print(str1.isalpha())
str2 = '\n\naaa\n\n\t'
print(str2.rstrip())
print("%s hello,world %s" % ("a", "b"))
print("{0} hello,world {1}".format("a", "b"))
# 寻求帮助
s1 = "aaa"
print(dir(s1))
print(dir(s1.lower))
s2 = '\b\b\bc'
print(len(s2))
print(ord('a'))
print(ord('A'))
# add a enter
s3 = """jack
jack
"""
print(s3)
s4 = """jack '''' " "" a
"""
print(s4)
L = [1, 's', 2.2]
print(L)
print(L+[1, 2, '5'])
print(L)
print(L.append("D"))
print(L)
print(L.pop(2))
print(L)
M = ["b", "a", "c"]
print(M.sort())
print(M)
print(M.reverse())
print(M)
# wrong print(M[99])
# 嵌套
W = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(W[0][1])
row1 = [row[1] for row in W]
print(row1)
print([row[1]+1 for row in W])
print([row[1]+3 for row in W if row[1] % 2 == 0])
print([W[i][i] for i in [1, 2]])
print([c*2 for c in 'spam'])
# 迭代器
G = (sum(m) for m in W)
print(next(G))
# 运行各项然后产生结果
print(list(map(sum, [[1, 2, 3], [4, 5, 6]])))
print({sum(row) for row in [[1, 2, 3], [4, 5, 6]]})
P = [[1, 2, 3], [4, 5, 6]]
print({i: sum(P[i]) for i in range(2)})
# ord 转换为ASCII码
print([ord(w) for w in ['a', 'b', 'c']])
print({jj: ord(jj) for jj in ['1', '2', '3']})
# 字典 字典没有可靠的顺序
myName = {"firstName": "jack", "lastName": "ming", "age": 5}
print(myName["firstName"])
print(myName["lastName"])
myName["age"] += 1
print(myName)
secondName = {}
secondName["firstName"] = "caesar"
secondName["secondName"] = "wang"
print(secondName)
# 解决嵌套
Ronaldo = {"name": {"firstName": "Cristiano ", "lastName": "Ronaldo"},
"age": 88,
"like": ["girl", "food"]
}
print(Ronaldo)
print(Ronaldo["name"]["firstName"])
print(Ronaldo["like"][1])
Ronaldo["like"].append("pat")
print(Ronaldo)
# 通常最后一个引用失效后,对象会被垃圾回收
KS = {"a": 1, "b": 2, "c": 3}
print(KS.keys())
KSS = list(KS.keys())
KSS.sort()
print(KSS)
# 无序的
for x in KS:
print(x, ":", KS[x])
# 通过内置函数排序,有序的
for xx in sorted(KS):
print(xx, ":", KS[xx])
for c in 'abc':
print(c.upper())
time = 4
while time > 0:
print("hello!"*time)
time -= 1
print([mm*2 for mm in [1, 2, 3, 4]])
print('b' in 'abc')
if 'b' not in 'aac':
print("miss")
DD = {"a": 1, "b": 2, "c": 3}
print(DD.get("d", -1))
print(DD['D']if 'D' in "abc" else -2)
# 元组,不可改变的列表
tup = (1, 2, 3)
print(tup + (4, 5))
print(tup[0])
# tup[0]=3 error 不能改变
print((1, 2, ['a', 'b'], 'c'))
# 写文件
f = open("data.txt", "w")
f.write("bbb\nccc,ddd")
f.close()
# 读文件
ff = open("data.txt", "r")
print(ff.read())
print(ff.read().split(",")[0])
ff.close()
# 二进制
print(open("data.txt", "rb").read())
# 集合
ss = set("aaaabbb")
print(ss)
Y = {'a', 'b', 'd', 'd'}
print(Y)
print(ss, Y)
print(ss & Y)
print(ss | Y)
print(ss - Y)
print(1/3)
print(1/3+2/3)
import decimal
dd = decimal.Decimal(3.14)
dd += 1
print(dd)
decimal.getcontext().prec = 3
print(decimal.Decimal(1)/decimal.Decimal(3))
from fractions import Fraction
# 分数运算
f = Fraction(2, 3)
f += 1
f + Fraction(1, 3)
print(f)
print(bool("aaa"))
print(None)
print(type(L))
print(type(type(L)))
if type(L) == type([]):
print("yes")
if isinstance(L, list):
print("yes!")
class Worker:
def __init__(self, name, pay):
self.name = name
self.pay = pay
def lastName(self):
return self.name.split()[-1]
def giveRaise(self, percent):
self.pay *= (1.0 + percent)
bob = Worker("aaa", 100)
bob.giveRaise(1)
print(bob.lastName())
print(bob.pay)
|
5a4bbadfcdb599c207f1ade512b03d85118f2e74 | Alexan101/students | /main.py | 5,868 | 3.71875 | 4 | class Student:
def __init__(self, name, surname, gender):
self.name = name
self.surname = surname
self.gender = gender
self.finished_courses = []
self.courses_in_progress = []
self.grades = {}
def rate_lecturer(self, lecturer, course, rate):
if (isinstance(lecturer, Lecturer) and course in self.courses_in_progress and
course in lecturer.courses_attached):
if course in lecturer.rating:
lecturer.rating[course] += [rate]
else:
lecturer.rating[course] = [rate]
else:
return 'Ошибка'
def average_grade(self):
grades_list = []
for grade in self.grades.values():
grades_list += grade
average_grade = str(sum(grades_list) / len(grades_list))
return average_grade
def __str__(self):
return (f'Студент \nИмя: {self.name} \nФамилия: {self.surname}'
f'\nСредняя оценка за домашние задания: {self.average_grade()}'
f'\nКурсы в процессе изучения: {", ".join(self.courses_in_progress)}'
f'\nЗавершённые курсы: {", ".join(self.finished_courses)}\n')
def __gt__(self, other):
if not isinstance(other, Student):
return 'Ошибка! Это не студент!'
else:
if self.average_grade() > other.average_grade():
return f'Студент {self.name} {self.surname} успешнее, чем {other.name} {other.surname}\n'
else:
return f'Студент {other.name} {other.surname} успешнее, чем {self.name} {self.surname}\n'
class Mentor:
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.courses_attached = []
class Lecturer(Mentor):
def __init__(self, name, surname):
super().__init__(name, surname)
self.rating = {}
def average_rate(self):
rates_list = []
for rate in self.rating.values():
rates_list += rate
average_rate = str(sum(rates_list) / len(rates_list))
return average_rate
def __str__(self):
return (f'Лектор \nИмя: {self.name} \nФамилия: {self.surname}'
f'\nСредняя оценка за лекции: {self.average_rate()}\n')
def __gt__(self, other):
if not isinstance(other, Lecturer):
return 'Ошибка! Это не лектор!'
else:
if self.average_rate() > other.average_rate():
return f'Лектор {self.name} {self.surname} успешнее, чем {other.name} {other.surname}\n'
else:
return f'Лектор {other.name} {other.surname} успешнее, чем {self.name} {self.surname}\n'
class Reviewer(Mentor):
def rate_hw(self, student, course, grade):
if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:
if course in student.grades:
student.grades[course] += [grade]
else:
student.grades[course] = [grade]
else:
return 'Ошибка'
def __str__(self):
return f'Проверяющий \nИмя: {self.name} \nФамилия: {self.surname}\n'
student_ivanov = Student('Иванов', 'Иван', 'male')
student_ivanov.courses_in_progress += ['Python', 'Git']
student_petrova = Student('Петрова', 'Ольга', 'female')
student_petrova.courses_in_progress += ['Python']
student_petrova.finished_courses += ['Git']
reviewer_sidorova = Reviewer('Анна', 'Сидорова')
reviewer_sidorova.courses_attached += ['Python']
reviewer_andropov = Reviewer('Анатолий', 'Андропов')
reviewer_andropov.courses_attached += ['Git']
lecturer_ignatenko = Lecturer('Марина', 'Игнатенко')
lecturer_ignatenko.courses_attached += ['Python']
lecturer_andropov = Lecturer('Анатолий', 'Андропов')
lecturer_andropov.courses_attached += ['Git']
reviewer_sidorova.rate_hw(student_ivanov, 'Python', 7)
reviewer_andropov.rate_hw(student_ivanov, 'Git', 6)
reviewer_sidorova.rate_hw(student_petrova, 'Python', 9)
student_ivanov.rate_lecturer(lecturer_ignatenko, 'Python', 8)
student_ivanov.rate_lecturer(lecturer_andropov, 'Git', 6)
student_petrova.rate_lecturer(lecturer_ignatenko, 'Python', 9)
print(student_ivanov)
print(student_petrova)
print(reviewer_sidorova)
print(reviewer_andropov)
print(lecturer_ignatenko)
print(lecturer_andropov)
print(student_ivanov > student_petrova)
print(lecturer_ignatenko > lecturer_andropov)
def avg_grades_all(students_list, course):
all_grades_list = []
for student in students_list:
if student.grades.get(course) is not None:
all_grades_list += student.grades.get(course)
all_grades_avg = str(sum(all_grades_list) / len(all_grades_list))
print(f'Средняя оценка всех студентов за домашние задания по курсу {course}: {all_grades_avg}')
def avg_rates_all(lecturer_list, course):
all_rates_list = []
for lecturer in lecturer_list:
if lecturer.rating.get(course) is not None:
all_rates_list += lecturer.rating.get(course)
all_rates_avg = str(sum(all_rates_list) / len(all_rates_list))
print(f'Средняя оценка всех лекторов в рамках курса {course}: {all_rates_avg}')
avg_grades_all([student_ivanov, student_petrova], 'Python')
avg_grades_all([student_ivanov, student_petrova], 'Git')
avg_rates_all([lecturer_ignatenko, lecturer_andropov], 'Python')
avg_rates_all([lecturer_ignatenko, lecturer_andropov], 'Git')
|
3b2fcea13b2469228b39e964a76e00e42b3c28d4 | gurs56/pythonprograming | /test.py | 792 | 3.96875 | 4 | """
#globe scope
num = 10
def change_num(num):
#function scope
num += 5
print("inside function num is {}".format(num))
#intergers are passed by value, i.e we pass a copy to functions
change_num(num)
print("out{}".format(num))
nums = [1,2,3,4,5]
def change_nums(vals):
for index in range(len(vals) - 1):
vals[index] += 5
print("inside the funtion {}".format(vals))
#lists are pass by-reference
change_nums(nums)
print("outside the function")
"""
scores = [5,15,25,4,6,7,3,45,67,78,78,7,5,15,6,6,6]
frequency_conunter = {} #This is an empty dictionary
for score in scores:
if score in frequency_conunter:
frequency_conunter[score] += 1
else:
frequency_conunter[score] = 1
print(frequency_conunter) |
4a5e75314ea40f2fb1f302a031baad563468f5f3 | tusharsappal/Scripter | /python_scripts/python_cook_book_receipes/date_and_time/calculating_time_periods_in_date_range.py | 532 | 4.03125 | 4 | __author__ = 'tusharsappal'
## Credits Python Cook Book Solution 3.3
## This program finds the time period in weeks between the given date range
from dateutil import rrule
import datetime
def weeks_between(start_date, end_date):
weeks=rrule.rrule(rrule.WEEKLY,dtstart=start_date,until=end_date)
print "The number of weeks in the given time duration are ", weeks.count()
## Replace the arguments in the method call with the start date and the end date
weeks_between(datetime.date(2005,01,04),datetime.date(2005,01,15)) |
6d31057c5a5a061f0172087ed962a0edda26f50b | rjayswal-pythonista/DSA_Python | /Practice/test2.py | 422 | 3.5 | 4 |
class Solution:
def suggestedProducts(self, products, searchWord):
list_ = []
products.sort()
for i, v in enumerate(searchWord):
products = [p for p in products if len(p) > i and p[i] == v]
list_.append(products[:3])
return list_
sol = Solution()
products = ['mousepad', 'mobile', 'moneypot', 'monitor', 'mouse']
print(sol.suggestedProducts(products, "mouse")) |
759b84a535c620d24513da826ba8026f90795ad2 | guyunzh/extract_data | /extract_data.py | 853 | 3.640625 | 4 | prices={
"ACME":45.32,
"AAPL":612.76,
"IBM":205.44,
"HPQ":37.21,
"FB":10.75
}
'''利用字典推导式来从字典中取出需要的数据'''
#Make a dictionary of all prices over 200
p1={key:value for key,value in prices.items() if value >200}
#print {'AAPL': 612.76, 'IBM': 205.44}
#Make a dictionary of tech stocks
tech_names={'AAPL','IBM','HPQ','MSFT'}
p2={key:value for key ,value in prices.items() if key in tech_names}
#print {'AAPL': 612.76, 'IBM': 205.44, 'HPQ': 37.21}
'''还可以用一个筛选工具是itertools.compress(),
它接受一个可迭代对象以及一个布尔选择器序列作为输入。
输入相应的布尔选择器为True的可迭代对象元素。
同filter一样,返回一个迭代器'''
from itertools import compress
list(compress(prices,[value>200 for value in prices.values()]))
#print ['AAPL', 'IBM'] |
184c0f625459a5377e41ee735f7efef04b803c0a | Yurun-LI/CodeEx | /.history/TwoSum_20210719232906.py | 370 | 3.703125 | 4 | from typing import List
class Solution:
def twoSum(self,nums:List[int],target:int)->List[int]:
dic = {}
Len = len(nums)
for i in range(Len):
if nums[i] in dic:
return [i,dic[nums[i]]]
dic[target - nums[i]] = i
return None
nums = [1,2,3,6,7]
target = 5
print(Solution().twoSum(nums, target)) |
baff4b4109f9c21948ba543f372fda507def8c30 | dylanhoover/SCU-Coursework | /COEN140/lab1/class3.py | 310 | 3.6875 | 4 | class Person:
def __init__(self, name, jobs, age=None):
self.name = name
self.jobs = jobs
self.age = age
def info(self):
return(self.name, self.jobs)
rec1 = Person('Bob', ['dev','mgr'],40.5)
rec2 = Person('Sue', ['dev','cto'])
print(rec1.jobs)
print(rec2.info())
|
076be9d4edd312dea2afa44759a1e3299340b6a2 | kedarpujara/BioinformaticsAlgorithms | /Rosalind1/Prob56/cycleToChromosome.py | 1,238 | 3.65625 | 4 | def cycleToChromosome(Nodes):
list1 = []
listR = []
for i in range(len(Nodes)/2):
if Nodes[2*i] < Nodes[2*i+1]:
val = i+1
else:
val = -(i+1)
list1.append(val)
for i in list1:
if i >0:
listR.append("+"+str(i))
if i<0:
listR.append(str(i))
print "(" + " ".join(listR) + ")"
return list1
def rCycleToChromosome(input):
file1 = open(input)
pfile1 = file1.readlines()[0].strip()
list1 = []
for i in pfile1[1:-1].split():
list1.append(int(i))
#print list1
cycleToChromosome(list1)
rCycleToChromosome("input2.txt")
# def cycleToChromosome(nodes):
# nodeNum = []
# chromosome = []
# for i in range(len(nodes)):
# nodeNum.append(int(nodes[i]))
# for j in range(0, len(nodeNum)/2):
# if j == 0:
# if nodeNum[0] < nodeNum[1]:
# chromosome.append(nodeNum[1]/2)
# else:
# chromosome.append(-1*nodeNum[0]/2)
# else:
# if nodeNum[2*j - 1] < nodeNum[2*j]:
# chromosome.append(nodeNum[2*j]/2)
# else:
# chromosome.append(-1*nodeNum[2*j-1]/2)
# print chromosome
# return chromosome
# def main():
# inputF = open('input.txt')
# chromosome = inputF.readline().translate(None, "(){}<>").strip().split(' ')
# cycleToChromosome(chromosome)
# #print chromosome
# main()
|
6a7e700e589519ce61c04e3f8de184fcc458b319 | christensonb/Seaborn | /seaborn/sorters/sorters_3.py | 2,487 | 3.609375 | 4 | """ This just contains some standard functions to do sorting by """
import sys
from random import random, seed
__author__ = 'Ben Christenson'
__date__ = "8/25/15"
class by_key(object):
def __init__(self, keys, comp=None):
self.keys = isinstance(keys, list) and keys or [keys]
self.comp = comp or (lambda x: x)
def __call__(self, obj):
return [self.comp(obj[k]) for k in self.keys]
class by_attribute(object):
def __init__(self, keys, comp=None):
self.keys = isinstance(keys, list) and keys or [keys]
self.comp = comp or (lambda x: x)
def __call__(self, obj):
ret = [self.comp(getattr(obj, k)) for k in self.keys]
return ret
def sort_dict_by_value(dict_obj):
""" This will return a list of keys that are sorted by value then keys
:param dict_obj: dict object to sort
:return: list of keys
"""
def by_status(obj):
return dict_obj[obj]
return sorted(dict_obj.keys(), by_key=by_status)
def by_longest(obj):
return -1 * len(obj)
def by_shortest(obj):
return len(obj)
def by_shortest_then_by_abc(obj):
return len(obj), obj
def by_longest_then_by_abc(obj):
return -1 * len(obj), obj
def by_random_order(obj):
return random()
def smoke_test():
seed(1)
class test(object):
def __init__(self, name):
self.name = name
def __repr__(self): return self.name
_list = [test('bbbb'), test('a'), test('cccc'), test('ddddd')]
_list.sort(key=by_attribute('name', comp=by_shortest_then_by_abc))
print([repr(l) for l in _list])
assert _list[0].name == 'a' and _list[2].name == 'cccc' and _list[3].name == 'ddddd'
_list.sort(key=by_attribute('name', comp=by_longest_then_by_abc), reverse=True)
print([repr(l) for l in _list])
assert _list[0].name == 'a' and _list[1].name == 'cccc' and _list[3].name == 'ddddd'
_list = [dict(name='bbbb'), dict(name='a'), dict(name='cccc'), dict(name='ddddd')]
_list.sort(key=by_key('name', comp=by_shortest_then_by_abc))
print([repr(l) for l in _list])
assert _list[0]['name'] == 'a' and _list[2]['name'] == 'cccc' and _list[3]['name'] == 'ddddd'
print(list(range(10)).sort(key=by_random_order))
if sys.version_info[0] == 2:
a = sorted(range(10), key=by_random_order)
else:
a = sorted(range(10), key=by_random_order)
print(a)
assert a == [3, 9, 6, 1, 4, 5, 2, 0, 8, 7]
if __name__ == '__main__':
smoke_test()
|
19807581a63d8d60393619626413609987acfabf | fffDroot/111.py | /prog1.py | 259 | 3.84375 | 4 | import sqlite3
con = sqlite3.connect(input())
cur = con.cursor()
res = cur.execute("""SELECT DISTINCT title FROM genres WHERE id
IN (SELECT genre FROM films WHERE year > 2009 AND year < 2012)""").fetchall()
for elem in res:
print(elem[0])
con.close()
|
63ec2461978aa10ca1f03d14192086a035f73035 | tarikbulbul/GorselProgramlamaVize | /soru2.py | 153 | 3.96875 | 4 | url =input("Url giriniz : ").split(".")
if url[0] == "www" and url[2] == "com" :
print("Url Doğru")
else :
print('Girilen url hatalıdır.') |
75a74f2d0610371edd91c80817310340009e75cc | amarelopiupiu/python-exercicios | /ex26.py | 427 | 3.90625 | 4 | # Escreva um programa que pergunte a quantidade de dias pelos quais ele foi alugado e a quantidade de Km percorridos por um carro alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
dias = float(input('Quantos dias o carro foi alugado? '))
km = float(input('Quantos km foram percorridos? '))
pagar = (60 * dias) + (0.15 * km)
print('É necessário pagar R${:.2f}' .format(pagar)) |
9339060107bef177c65e11f8f90005a64e3ff59f | L200170153/coding | /da best/uas/uas3.py | 203 | 3.578125 | 4 | def putar(l):
k = []
a = l[-2:]
b = l[0:len(l)-2]
for i in a:
k.append(i)
for l in b:
k.append(l)
print(k)
l = [x for x in input().split(',')]
putar(l)
|
bfb002d7e3ba1eb86e392416d66b964cdb4b9e1f | dedin/sides | /sorts/sorts.py | 4,742 | 4.375 | 4 | # BUBBLE SORT
# Go through the list over and over again, swapping as you go(if necessary)
# until you go through the list w/out swapping. Can reduce number of iterations
# cos on every walk of the list, the largest ends up bn at its right position
# Simple, efficient on small data, but bad on large data
# Not good for a reversed ordered list or list with smallest element at the rear
# good for sorted or almost sorted list
# Has the advantage of detecting when the input is already sorted (insertion sort does
# better with this though)
# elements move toward the end faster than toward the front
# best case - (n), average and worst case - (n^2)
def bubbleSort(arr):
n = len(arr)
swapped = True
while swapped: #repeat as long as there was a swap in previous iteration
swapped = False
for i in range(n - 1):
if arr[i] > arr[i + 1]:
temp = arr[i]
arr[i] = arr[i + 1]
arr[i + 1] = temp
swapped = True
# Optimize : reduce the num of iterations for the for loop be4 the next walkthrough of the list
n = n - 1
return arr
#INSERTION SORT
# Has 2 sections - sorted and unsorted and it inserts one element at a time.
# Great for small n and inplace sortin, and for final finishing off for nlgn algorithms(e.g quick sort)
# The first element is sorted(trivially) and you keep
# moving to the front (if necessary) till you find the right spot for
# a value.
# This method just rewrites a num when it does not have to be moved
# and it ceates space then write, when it has to be moved
# Best case(sorted list) is - (n) and avg and worst case is - (n^2) worst case is a reversed sorted list
def insertionSort(arr):
n = len(arr)
for i in range(1, n-1):
val = arr[i]
j = i - 1
# start by overwriting the spot where arr[i] is and make
# keep pushing nums over as you go
while j >= 0 and arr[j] > val : # while num you are looking at is greater than val
arr[j + 1] = arr[j] # move current j one step to the right
j = j - 1
arr[j + 1] = val # cos j ends up bn behind by 1 add 1 to get the spot for val
return arr
# SELECTION SORT
# Great for small sized list, useful for when swapping and writing is expensive.
# does no more than n swaps and writes.
# Looks for 1st smallest in list and moves it to pos 1, and does the same for 2nd, 3rd ...
# starts at a point and looks at elemnts from point+1 to the end for smaller value
# It is (n^2)
def selectionSort(arr):
n = len(arr)
for i in range(n):
indexOfMin = i #make it initial minimum
j = i + 1
for j in range(j,n): #search for another minimum if it exists
if arr[j] < arr[indexOfMin]:
indexOfMin = j
if indexOfMin != i: #if new minimum is not the previous minimum
arr[i], arr[indexOfMin] = arr[indexOfMin], arr[i]
return arr
# MERGE SORT
# breaks input down until it gets to one element and then
# merges them together
# Good for large list but could incur overhead in small list and is stable
# Best case - (n) when input is sorted, average and worst is(n^2)
def mergeSort(arr):
if len(arr) <= 1:
return arr
middle = len(arr)//2
left = arr[0:middle]
right = arr[middle:len(arr)]
left = mergeSort(left)
right = mergeSort(right)
return merge(left,right)
def merge(left, right):
newarr = []
i, j = 0,0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
newarr.append(left[i])
i = i + 1
else:
newarr.append(right[j])
j = j + 1
if j <= len(right)-1:
newarr = newarr + right[j:]
elif i <= len(left)-1:
newarr = newarr + left[i:]
return newarr
# QUICK SORT
# Divide and Conquer approach. Choose a pivot - best choice is median
# and divides the list by less than and greater than the pivot.
# It is in-place and has low overhead.It is unstable but fast. It uses lgn space
# Worst case - (n^2) when data is sorted and first or last element was chosen as pivot
# Best and average case - (nlgn) when a median or good pivot is chosen
# mostly used by languages and it uses insertion sort at the low level
# HEAP SORT
# Runs in (nlgn) time for all cases
if __name__ == "__main__" :
arr = [5, 1, 4, 2, 8, 9]
newarr = mergeSort(arr)
print(newarr)
newarr = bubbleSort(arr)
insertionSortarr = insertionSort(arr)
selectionSortarr = selectionSort(arr)
print ("bubble sort is - ", newarr)
print ("insertion sort is - ", insertionSortarr)
print("selection sort is - ", selectionSortarr)
|
2873a5a374c9a867ee52026da7361d893e258ccd | vibhorsingh11/hackerrank-python | /04_Sets/11_TheCaptainsRoom.py | 1,012 | 4.1875 | 4 | # Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
#
# One fine day, a finite number of tourists come to stay at the hotel.
# The tourists consist of:
# → A Captain.
# → An unknown group of families consisting of K members per group where K ≠ 1.
#
# The Captain was given a separate room, and the rest were given one room per group.
#
# Mr. Anant has an unordered list of randomly arranged room entries. The list consists of the room numbers for all of
# the tourists. The room numbers will appear times per group except for the Captain's room.
#
# Mr. Anant needs you to help him find the Captain's room number.
# The total number of tourists or the total number of groups of families is not known to you.
# You only know the value of and the room number list.
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
rooms = input().split()
rooms.sort()
capt_room = (set(rooms[0::2]) ^ set(rooms[1::2]))
print(capt_room.pop())
|
8bab9d1b985995535ccab28c4b306717abac0f1d | victormruiz/ASIR | /LM2/python/entrega1/ejercicio6.py | 691 | 3.765625 | 4 | from random import randint
print("JUEGO DE MULTIPLICACIONES")
vueltas = int(input("¿Cuantas multiplicaciones quieres hacer? "))
correctas=0
for i in range(vueltas):
num1 = randint(2, 10)
num2 = randint(2, 10)
resultado=num1*num2
respuesta=int(input("¿Cuanto es %d x %d?: " % (num1,num2)))
if respuesta==resultado:
print("¡Correcto!")
correctas=correctas+1
else:
print("¡Respuesta incorrecta!")
print("Has contestado correctamente %d preguntas de %d" % (correctas,vueltas))
nota=correctas/vueltas*10
if nota >= 5:
print("Enhorabuena, has aprobado con un %.1f" % nota)
else:
print("Lo siento pero has suspendido con un %.1f" % nota)
|
7d6f55e12d0a2b95ecdde65ee7fb0e38376210f5 | P01Alecu/LFA_Simulare-AFD | /simulare_afd.py | 2,735 | 3.71875 | 4 | ###########Simulare AFD
##in fisierul 'in.txt' se gasesc datele de intrare
##fisierul este de forma:
##stare_initiala Stari_finale
##cuvant cuvant cuvant......
##litera starea_din_care_pleaca starea_in_care_ajunge
##...
##litera starea_din_care_pleaca starea_in_care_ajunge
def parcurgere(start, sir):
ok = True
point = 0 #pointeaza litera pana la care s-a parcurs sirul
f = open("out.txt", "a")
f.write('Cuvantul: ' + str(sir) + '\n')
while (start != '-1' and start != '-2' and point<len(sir)):
f.write(str(start) + ' ' + str(sir[point:]) + "\n") #scrie in fisier
print(str(start) + ' ' + str(sir[point:])) #scrie in consola
start = cautare(sir[point], start, m)
if(start == -1 or start == -2):
ok = False
break
point = point+1
if(ok): #verifica daca starea in care s-a ajuns dupa parcurgerea cuvantului este finala
f.write(str(start) + ' ' + "''\n") #scrie in fisier
print(str(start) + ' ' + "''") #scrie in consola
ok = verificare(start, final)
if(ok):
f.write(str(start) + ' ' + "''\n")
print(str(start) + ' ' + "''")
f.write('Cuvantul este acceptat!\n')
print('Cuvantul este acceptat!')
else:
if (start == '-2'):
f.write('Automatul nu este afd!\n')
print('Automatul nu este afd!')
else:
f.write('Nu se poate!\n')
print('Nu se poate!')
f.write('\n')
f.close()
def cautare(litera, starea, text): #cauta starea a carei tranzitie accepta o litera anume, si in caz ca sunt gasite mai multe (automatul nu este afd) returneaza -2, in caz ca nu s-a gasit returneaza -1
start = '-1'
for i in range(0, len(text.splitlines())):
if(text.splitlines()[i][0] == litera and text.splitlines()[i][2] == starea):
if (start != '-1'):
start = '-2'
return start
else:
start = text.splitlines()[i][4]
return start
def verificare(vf, final): #verifica daca starea in care s-a ajuns este stare finala
ok = False
for i in range(0, len(final)):
if (final[i] == vf):
ok = True
return ok
f = open("in.txt", "r")
final = []
m = f.read()
start = str(m[0]) #starea initiala
final = m.splitlines()[0][2:].split() #vector cu starile finale
f.close()
sir = m.splitlines()[1].split()
f = open("out.txt", "w") #solutie simpla ptr a sterge un posibil vechi fisier "out.txt" si a creea unul nou in care se va face append
f.close()
for i in range(0, len(sir)):
print()
print(sir[i])
parcurgere(start, sir[i]) |
cc06a3e82dfb5ad0e06ee4a5177473727da338ad | pandarison/training2 | /w1_family/template.py3 | 355 | 3.734375 | 4 |
{USERCODE}
_,x,y = input().split(" ")
x = int(x)
y = int(y)
solution = Solution()
for i in range(x):
a, b = input().split(" ")
a = int(a)
b = int(b)
solution.setFamily(a, b)
for i in range(y):
a, b = input().split(" ")
a = int(a)
b = int(b)
if solution.isFamily(a, b):
print("Yes")
else:
print("No")
|
f9e7f1ac8dc5d3633a6b96a918164faf08628500 | asiffmahmudd/Python-Specialization-on-Coursera | /Programming for Everybody (Getting Started with Python)/Week 5/Assignment 1.py | 158 | 4.0625 | 4 | hrs = float(input("Enter Hours:"))
rate = float(input("Enter rate:"))
if hrs <= 40 :
print(hrs*rate)
else:
x = rate*40+rate*1.5*(hrs-40)
print(x) |
cf8de94dc427c04f3daeca65dde2f3057713e0f6 | xwind-h/coding-practice | /leetcode/ConvertSortedArrayToBinarySearchTree.py | 1,445 | 3.765625 | 4 | # Definition for a binary tree node.
from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums):
def toBST(l, u):
if l > u:
return None
m = (l + u) // 2
node = TreeNode(nums[m])
if l != u:
node.left = toBST(l, m - 1)
node.right = toBST(m + 1, u)
return node
return toBST(0, len(nums) - 1)
def sortedArrayToBST2(self, nums):
if (not nums) or len(nums) == 0:
return None
m = (len(nums) - 1) // 2
root = TreeNode(nums[m])
queue = deque()
queue.append((root, (0, m, len(nums) - 1)))
while len(queue) > 0:
node, index = queue.popleft()
if index[1] > index[0]:
m = (index[0] + index[1] - 1) // 2
node.left = TreeNode(nums[m])
queue.append((node.left, (index[0], m, index[1] - 1)))
if index[1] < index[2]:
m = (index[1] + 1 + index[2]) // 2
node.right = TreeNode(nums[m])
queue.append((node.right, (index[1] + 1, m, index[2])))
return root
if __name__ == "__main__":
nums = [-10,-3,0,5,9]
sl = Solution()
tree = sl.sortedArrayToBST(nums)
print(tree) |
8536f59d3ae9b45f9e550f5e14823bf614f224e8 | killedman/DoTheQuestion | /20200214_02.py | 1,208 | 3.90625 | 4 | #! /usr/bin/env python
"""
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# for i in nums:
# if nums.count(i) == 1:
# return i
# 以下方法针对测试时超出时间限制进行了优化
new_nums = sorted(nums)
while new_nums:
first = new_nums[0]
if new_nums.count(first) == 2:
new_nums = new_nums[2:]
elif new_nums.count(first) == 1:
return first
if __name__ == "__main__":
num_list = [4,1,2,1,2]
solution = Solution()
result = solution.singleNumber(num_list)
print(result)
|
0e6fde19a2a3519f88f94cd71d182569654dd697 | manshan/pyworkspace | /test1.py | 177 | 4.0625 | 4 | def fibonacci(i):
if i < 1:
return 1
if i == 1 or i == 2:
return i
return fibonacci(i-1) + fibonacci(i-2)
if __name__ == '__main__':
print fibonacci(10)
|
ab4604be0d7e732cfb94fd7045b5edb1f250eeb9 | VinogradovAU/myproject | /python_less/lesson-3/less-3-4.py | 941 | 4.125 | 4 | # -*-coding:utf8;-*-
"""
Программа принимает действительное положительное число x и целое отрицательное число y.
Необходимо выполнить возведение числа x в степень y.
Задание необходимо реализовать в виде функции my_func(x, y).
При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
"""
print("Задание 4")
def my_func(x,y):
print(f'Необходимо {x} возвести в степень {y}')
count = list(range(abs(y)))
num1 = x
for k in count[1:]:
#x = x * num1
num2 = x
for i in range(num1-1):
x = x + num2
#print(x)
#print(k, x)
print(f'Ответ: {1/x}')
my_func(3, -5)
|
e9542054423160f9126417e6aee4baa5f2f1f2e9 | crazy-learner-xyz/lc | /0547. Number of Provinces/solution.py | 970 | 3.546875 | 4 | import collections
class Solution(object):
def findCircleNum(self, isConnected):
"""
:type isConnected: List[List[int]]
:rtype: int
"""
# Reshape the data structure
diction = collections.defaultdict(list)
for i in range(len(isConnected)):
for j in range(i+1, len(isConnected[0])):
if isConnected[i][j] == 1:
diction[i] += [j]
diction[j] += [i]
traversed_lst = []
numIsland = 0
for i in range(len(isConnected)):
if i not in traversed_lst:
stack = [(i)]
while stack!= []:
i = stack.pop(-1)
for j in diction[i]:
if j not in traversed_lst:
stack.append((j))
traversed_lst.append(j)
numIsland += 1
return numIsland |
c984c502d22f8a4bb96ec6a19cf4df3bb59619b5 | yaseen-ops/python-practice2 | /21readFile.py | 535 | 3.8125 | 4 | employee_data = open("employee_file.txt", "r") # r=read; w=write; a=append; r+=read/write
# print(employee_data.readable()) # Check the file is readable or not
# print(employee_data.read()) #Read the whole file
# print("-------------------")
# print(employee_data.readline()) # Read by lines, prints the first line and moves the cursor to second line
# print(employee_data.readline()) # prints the second line and moves the cursor to third line
print(employee_data.readlines()[0]) # I can read a specific line
employee_data.close()
|
5001bafc9dd553b52500d1365dc79b33b8cb194b | yandre-dle/Catatan_PRGT_PYTHON | /PYTHON-1/5- Aplikasi Belanja/17. Control Flow/x1.py | 343 | 3.65625 | 4 | apple_price = 2
# Berikan 10 ke variable money
input_count = input('Mau berapa apel?: ')
count = int(input_count)
total_price = apple_price * count
print('Anda akan membeli ' + str(count) + ' apel')
print('Harga total adalah ' + str(total_price) + ' dolar')
# Tambahkan control flow berdasarkan perbandingan antara money dan total_price
|
6f266d2cccfb5d67c12e58af9b6b1a574ee58ffa | knight-byte/Codeforces-Problemset-Solution | /Python/A_Even_Subset_Sum_Problem.py | 558 | 3.578125 | 4 | '''
Author : knight_byte
File : A_Even_Subset_Sum_Problem.py
Created on : 2021-04-21 11:16:19
'''
def main():
n = int(input())
arr = list(map(int, input().split()))
odd = []
for i in range(n):
if arr[i] % 2 == 0:
print(f"1\n{i+1}")
break
else:
odd.append(str(i+1))
if len(odd) == 2:
print(f"2\n{' '.join(odd)}")
break
else:
print(-1)
if __name__ == '__main__':
T = int(input())
for _ in range(T):
main()
|
7bc6776a8298b2b0392cab478d94d9a7fa88e75b | CristianoFernandes/LearningPython | /exercises/Ex_013.py | 356 | 3.859375 | 4 | print('########## Exercícios de Python ##########')
print('########## Exercício 013 ##########')
salario = float(input('Digite o salário do funcionário: R$'))
reajuste = float(input('Digite o percentual para reajuste: '))
print('O salário do funcionário reajustado em {}% será de R${}'.format(reajuste, salario + (salario * reajuste / 100)))
|
f052e9746d0ec980e824a0450d49ca32907b7ced | lupomancer/Python | /Midterm/course_selector.py | 4,518 | 4.15625 | 4 | #! /usr/bin/env python3
"""
This module builds a program workload for a general interest computing
program. Courses are selected from a course calendar.
Being a general interest continuing studies program and there are no program
requirements either in number of, ordering, or specific required courses.
Once a user has completed course selections. the total program hours are
calculated based on the number of credits in each course. Each credit is
comprised of 14 hours of course work.
From the required hours the number of semesters is calculated based on a
semester length of 120 hours for part time studies and 360 hours for full time
studies.
The courses selected and the number of semesters required to finish the program
is printed for the user.
"""
import math
calendar = {
"CS101": 6.00,
"CS102": 6.00,
"CS103": 5.00,
"CS104": 5.00,
"MA101": 4.00,
"MA102": 4.00,
"CO101": 3.00,
"CO102": 3.00,
"OR101": 3.00,
"OR102": 3.00
}
def course_hours(course):
"""
Calculate the number of hours to complete a given course
Args:
course (str): the name of the course
Returns:
(float): the number of hours required to complete the course
"""
#Function body goes here
hours = calendar[course] * 14
return hours
def calculate_semesters(workload, attendance):
"""
Calculates the number of semester to complete the courseload and attendance
Based on the students delivery type ("pt" - Part Time or "ft" - Full Time)
calculate the number of semesters to complete their workload.
The number of hours in a course is calculated as follows:
course hours = credits * 14 hours per credit
The number of hours in a semester is specified as follows:
pt = 120
ft = 360
The number of semesters is calculated as follows:
(the total hours in program / hours in semester) rounded up to nearest
whole semester.
see 'math.ceil' for standard library method of performing rounding up
Args:
workload (List[str]): this is a list of course codes that comprise the
students workload
attendance (str): "pt" or "ft" indicating whether the student will be
attending part time or full time
Returns:
int: number of semesters to complete workload
"""
#Function body goes here
i = 0
for i in len(workload):
hours = sum(course_hours(workload(i)))
if attendance == 'ft':
semesters = math.ceil(360/hours)
if attendance == 'pt':
semesters = math.ceil(120/hours)
i += 1
return semesters
def build_program():
"""
Prompt the user for courses that they want to enroll in and add them to
their customized program
If the courses is not in the course catalogue inform them by printing:
"Sorry, $course_input isn't currently offered"
Where $course_input is the course code they entered at the prompt.
After a failed input attempt the user will be prompted to input another course code.
The user will continue to select courses until they enter 'done' when to
indicate that have finished adding courses.
Returns:
(List[str]): a list of courses to in which the student will be enrolled
"""
course = ""
program = []
while course != "done":
#body of processing loop
course = input("What course would you like register for - enter 'done' when finished:")
program.append(course)
print("Your program includes the following courses:")
print(program)
return program
def main():
"""
Build course program and select delivery type, then print the courses and
completion time in semesters
"""
#Function body goes here
#You need to properly populate the following variables:
# delivery_type: prompt the user for the desired delivery type
delivery_type = input("Will you be attending full time(ft) or part time (pt):")
# program: list of courses
program = build_program()
# semesters: number of semesters to complete courses
calculate_semesters(program, delivery_type)
# Following outputs the courses in the program
print("Your program includes the following courses:\n{}".format(program))
# Following outputs the number of semesters
print("It will take you {} semesters to complete".format(semesters))
if __name__ == "__main__":
main()
|
4b45806fcbbcde8c45565f0c6d49aecd37241328 | LuisAraujo/Simple-Unit-Testing | /www/code_examples/code2.py | 90 | 3.671875 | 4 | max = 0
for i in range(10):
valor =input()
if(valor > max):
max = valor
print(max) |
f1d3bfe43edd5b471ec066a4a4ff77d862949986 | lighttransport/nanosnap | /tests/gen/common_util.py | 1,160 | 3.625 | 4 | import numpy
# NOTE(LTE): We cannot use numpy.iscomplex() whether input value is complex-value,
# since it will return False for complex-value whose imaginary part is zero.
#
# arr : numpy 1D or 2D array
def print_c_array(arr):
c_arr = []
if numpy.isfortran(arr):
arr = numpy.transpose(arr)
if len(arr.shape) == 1:
for i in arr:
if isinstance(i, complex) or isinstance(i, numpy.complex) or isinstance(i, numpy.complex64):
c_arr.append(str(float(i.real)) + 'f')
c_arr.append(str(float(i.imag)) + 'f')
else:
c_arr.append(str(float(i)) + 'f')
c_str = ', '.join(c_arr)
elif len(arr.shape) == 2:
for row in arr:
for i in row:
if isinstance(i, complex) or isinstance(i, numpy.complex) or isinstance(i, numpy.complex64):
c_arr.append(str(float(i.real)) + 'f')
c_arr.append(str(float(i.imag)) + 'f')
else:
c_arr.append(str(float(i)) + 'f')
c_str = ', '.join(c_arr)
else:
# Unsupported.
raise
return c_str
|
5a9f033a0b63bd6149e84d70f24b706a7f073105 | estradanorlie09/hello-python | /hello.py | 646 | 3.890625 | 4 | print("Hello, World!")
print("My name is {}. I am {} y/o."\
.format("Norlie",16))
print("Adnu", 2018, sep="-", end="")
print("CSNHS")
print("My spirit animal is".format(data["animal"]))
print("my reason{}".format(data["reason"]))
print("my hobby{}".format(data["hobby"]))
print("my profession{}".format(data["profession"]))
input Num = input("Enter a comma separated list of numbers:")
import sys
windintensity =float{sys.argv][1]}
if sustained_wind >= 200:
print("Super Typhoon")
elif sustained_wind >= 118:
print("typhoon")
elif sustained_wind >= 89:
print("severiral tropical storm")
elif sustained_wind >= 89: |
6da7023392314e57c75508daec871a5643857d13 | ledbagholberton/holbertonschool-machine_learning | /supervised_learning/0x10-nlp_metrics/1-ngram_bleu.py | 2,484 | 3.828125 | 4 | #!/usr/bin/env python3
"""
references is a list of reference translations
each reference translation is a list of the words in the translation
sentence is a list containing the model proposed sentence
n is the size of the n-gram to use for evaluation
Returns: the n-gram BLEU score
"""
import numpy as np
def ngram_bleu(references, sentence, n):
"""
calculates the n-gram BLEU score for a sentence
"""
row_sen = len(sentence)
row_ref = len(references)
col_ref = len(references[0])
close = col_ref
# create the n-gram lists based on sentences and n
list_gram = [None] * (n+1)
list_gram[n] = []
# creates the n-grams for the sentence
for i in range(row_sen - n + 1):
ngram = ''
for j in range(n):
ngram = ngram + ' ' + sentence[i + j]
list_gram[n].append(ngram)
# creates the n-grams in the references and stores it in new_list
new_list = [[] for y in range(row_ref)]
# iterate on each reference
for i in range(row_ref):
col_ref = len(references[i])
# iterates on each word in each reference
for j in range(col_ref - 1):
new_word = ''
# built the n-gram. Sum n times the word with the nexts
for k in range(n):
new_word += ' ' + references[i][j + k]
new_list[i].append(new_word)
list_size = len(list_gram[n])
new_dict = {word: [0]*(row_ref+1) for word in list_gram[n]}
# print(new_dict)
for key in new_dict:
for iter in range(row_ref):
for iter_ngram in range(len(new_list[iter])):
if key == new_list[iter][iter_ngram]:
new_dict[key][iter] += 1
for key in new_dict:
for n_gram in list_gram[n]:
if key == n_gram:
new_dict[key][row_ref] += 1
sen_dict = {word: [0]*(row_ref+1) for word in sentence}
for key in sen_dict:
for iter_ref in range(row_ref):
col_ref = len(references[iter_ref])
if abs(row_sen - close) > abs(col_ref - close):
close = len(references[iter_ref])
if row_sen <= col_ref:
BP = np.exp((1 - (close/row_sen)))
else:
BP = 1
values = np.array(tuple(new_dict.values()))
num = np.sum(np.max(values[:, 0:2], axis=1))
den = np.sum(values[:, -1])
pn = num / den
bleu = BP * np.exp(np.log(pn))
return bleu
|
50e7818b9cf109b389cad6920dc123329535c411 | barakbanin/varonis | /test1.py | 302 | 3.515625 | 4 | class MagicList:
def __init__(self):
self.lst = list()
self.counter=0
def __setitem__(self, i, item):
if len(self.lst)==0:
self.lst.append(item)
self.counter+=1
def __getitem__(self, i):
return self.lst[i]
|
52a1eb439c48f96fbee45170ca77e6d31c84a906 | ayushgarg95/python_scripts | /input_space_separated.py | 243 | 4.3125 | 4 | #!/usr/bin/env python
x=raw_input('Enter a list of numbers separated by space: ')
# nums is an array which has each element of input
nums=x.split()
for i in nums:
if not i.isdigit():
print ' Not a number :',i
else:
print 'Numer :',i
|
a5f4d37c09fcbc4d531d666bec92b4623854ffae | br71/py_examples | /nth_fibonacci.py | 765 | 3.765625 | 4 |
# Recursive solution
# O(n^2) time | O(n) space
def get_nth_fib1(n):
if n == 2:
return 1
elif n == 1:
return 0
else:
return get_nth_fib1(n - 1) + get_nth_fib1(n - 2)
# Recursive solution with dictionary
# O(n) time | O(n) space_
def get_nth_fib2(n, mem={1: 0, 2: 1}):
if n in mem:
return mem[n]
else:
mem[n] = get_nth_fib2(n - 1, mem) + get_nth_fib2(n - 2, mem)
return mem[n]
# Iterative solution
# O(n) time | O(1) space_
def get_nth_fib3(n):
last_two = [0, 1]
counter = 3
while counter <= n:
next_fib = last_two[0] + last_two[1]
last_two[0] = last_two[1]
last_two[1] = next_fib
counter += 1
return last_two[1] if n > 1 else last_two[0]
|
a8926f72e29d6058f357533d1746b5faa91aae6c | souradeepta/PythonPractice | /code/12-16/binary-search-recurrsive.py | 1,271 | 3.875 | 4 | from typing import List, Any
def binary_search_recurrsive(input: List, target: Any) -> None:
"""Binary search with Time O(Log(n)) and Space O(Log(n))"""
if not input:
return None
left = 0
right = len(input)
return helper(input, target, left, right)
def helper(input: List, target: Any, left: int, right: int):
mid = left + (right - left) // 2
if input[mid] == target:
return mid + 1
elif input[mid] < target:
return helper(input, target, mid, right)
else:
return helper(input, target, left, mid)
return None
if __name__ == "__main__":
input_integers = [1, 2, 3, 4]
input_integer_repeats = [1, 2, 2, 4, 9, 12]
input_strings = ["1who", "2what", "3where"]
input_floats = [0.222, 0.44444444444444444444444444444, 0.9]
print(
f"target 2 on list {input_integers} is at {binary_search_recurrsive(input_integers, 2)}")
print(
f"target 2 on list {input_integer_repeats} is at {binary_search_recurrsive(input_integer_repeats, 2)}")
print(
f"target '3where' on list {input_strings} is at {binary_search_recurrsive(input_strings, '3where')}")
print(
f"target 0.9 on list {input_floats} is at {binary_search_recurrsive(input_floats, 0.9)}")
|
e3c077a91dc270641f7b8b82ec36e6e42e222e0c | aloyalways/Competitive-Programming-DSA-in-Python- | /Tree/Height of BT.py | 495 | 3.796875 | 4 | class Node:
def __init__(self,key):
self.left=None
self.right=None
self.val=key
def height(self,root):
if root is None:
return 0
lheight=root.height(root.left)
rheight=root.height(root.right)
if lheight>rheight:
return lheight+1
else:
return rheight+1
root=Node(3)
root.left=Node(9)
root.right=Node(20)
root.right.left=Node(15)
root.right.right=Node(7)
print(root.height(root)) |
89ac6fdabbe5bebd9f41e511ca325af79a5bad29 | mjoze/kurs_python | /kurs/03_kolekcje/tuple_set.py | 180 | 3.515625 | 4 | """Utwórz dowolną krotkę, w której elementy mogą się powtarzać. Przekształć ją w set."""
a = ("a", "w", "reksio", "e", "e", 1, 1, "reksio")
print(a)
b = set(a)
print(b)
|
a7c08e1e9db6afc9377a9cd823a6111774c74e87 | MrNierda/SpeechRecognition | /audio_to_text.py | 1,532 | 3.515625 | 4 | import speech_recognition as sr
# from operation_produced import main
import operation_produced
import language
def recognize_audio(spoken_language=language.Language.FR):
"""
Activate microphone to listen to the user
Return the audio as a string
"""
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
print('Audio listened!')
try:
text = r.recognize_google(audio, language=spoken_language)
print("Text: " + text)
return text
except:
print('Audio not recognized!')
def language_selection():
languages = language.get_languages()
print(f'Say the language you want to use among those {list(languages.keys())}')
selected_language = recognize_audio()
if selected_language not in list(languages.keys()):
print("I didn't find the desired language")
language_selection()
print(f'\nSelected language is {selected_language}')
commands_for_lang = list(language.get_command_for_lang(selected_language).values())
print(f'\nHere the existing command for the current language {commands_for_lang}')
return languages.get(selected_language)
def main():
print('Starting...')
selected_language = language_selection()
print(f'\nYou selected {selected_language}')
print('\nWhat do you want to do?')
activity = recognize_audio(selected_language)
operation_produced.main(activity)
if __name__ == '__main__':
main() |
07a52959e6445acb083827b64f0326356341ea73 | la-ursic/redtape | /lists.py | 2,921 | 4.21875 | 4 | '''
list1 = [1,2,3,4,5,2,32,53,4,333,57,90]
list2 = ["A","B"]
list3 = ["A",1,2,3,4,5,6,7,8,9]
list4 = [list1,list2,list3]
#print(list4)
list1.append(6)
print(list1)
list1.extend([7,8])
print(list1)
list1.insert(2,"melon")
print(list1)
list1.pop(3)
print("POP")
print(list1)
list3.reverse()
print("REVERSE")
print(list3)
print("COUNT")
print(list1.count(333))
print("INDEX")
print(list1.index(333))
print("Let's get this machine to create a 100 hundred var list")
oneHundredList = [1]
for i in range(2,101):
oneHundredList.append(i)
print (oneHundredList)
tableToBuild = int(input("Now we'll build a multiplication table. Please, enter an integer \n"))
multiplicationTable = [0]
for i in range(1,11):
multiplicationTable.append(i * tableToBuild)
print(multiplicationTable)
print("Sum of two lists' elements")
firstList = [4,76,3,12,65,3]
firstListSum = 0
for i in firstList:
firstListSum = firstListSum + i
secondList = [234,222,523,65]
secondListSum = 0
for i in secondList:
secondListSum = secondListSum + i
print(firstListSum + secondListSum)
print("Second version of the previous exercise")
firstListB = [4,76,3,12,65,3]
secondListB = [234,222,523,65]
concatenatedList = []
concatenatedList.extend(firstListB)
concatenatedList.extend(secondListB)
print(concatenatedList)
concatenatedListSum = 0
for i in concatenatedList:
concatenatedListSum = concatenatedListSum + i
print(concatenatedListSum)
print("Hagamos una lista de palabras")
wordCount = int(input("Cuantas palabras quieres que tenga tu lista? \n"))
if wordCount < 1:
print ("Imposible!")
else:
words = []
for _ in range(wordCount):
words.append(str(input("Ingresa la palabra: ")))
print(words)
print("Hagamos una lista de palabras - segunda manera")
wordCount = int(input("Cuantas palabras quieres que tenga tu lista? \n"))
if wordCount < 1:
print ("Imposible!")
else:
words = [str(input("Ingresa una palabra: ")) for _ in range(wordCount)]
print(words)
find_word = str(input("que palabra quiere buscar? \n"))
if words.count(find_word) > 0:
#print("tu palabra aparece" & str(words.count(find_word)) & "veces")
print("tu palabra aparece {} veces".format(str(words.count(find_word))))
else:
print("no esta en la lista")
words.index(find_word)
replacement = str(input("porque palabra quieres reemplazar? \n"))
print("porque palabra quieres reemplazar?")
words.insert(words.index(find_word),replacement)
words.remove(find_word)
print(words)
'''
print("Hagamos una lista de palabras en la que se elimina una palabra")
wordCount = int(input("Cuantas palabras quieres que tenga tu lista? \n"))
if wordCount < 1:
print ("Imposible!")
else:
words = [str(input("Ingresa una palabra: ")) for i in range(wordCount)]
print(words)
find_word = str(input("que palabra quiere eliminar? \n"))
if words.count(find_word) > 0:
for count in range(words.count(find_word)):
words.remove(find_word)
print(words)
else:
print("no esta en la lista") |
c33b82fa7c19dabcfdfd10b761583ffd860812e9 | JF-Ar/processos-seletivo | /exercicios de treino/aula14/exe60.py | 499 | 3.984375 | 4 | '''from math import factorial
n = int(input('Digite um numero para calcularmos o seu fatorial: '))
fat = factorial(n)
print('{}! é igual a {}'.format(n, fat))'''
'''from math import factorial'''
n = int(input( 'Digite um numero para calcularmos o seu fatorial: '))
c = n
fatorial = 1
print('Calculando {}! ->'.format(n), end=' ')
while c > 0:
print('{}'.format(c), end='')
print('x ' if c > 1 else ' = ', end='')
fatorial *= c
c -= 1
print('{}'.format(fatorial)) |
ab345d2b899c8a84a4b6dfd02cca6b02f76208c3 | BarisAkkus/Main | /Sezon1/Ders12-Blocks.py | 549 | 4.03125 | 4 | name = input("Please enter your name: ")
age = int(input("How old are you, {0}".format(name)))
print(age)
#if age >=18:
# print("You can vote")
# print("Please put an X in the b0x")
#else:
# print("Please come back in {0} years".format(18-age))
#elif age ==900:
# print("Sorry , Yoda, you die in Return of the")
if age <18:
print("Hi {1} Please come back in {0} years".format(18-age,name))
elif age ==900:
print("Sorry , Yoda, you die in Return of the")
else:
print("You can vote")
print("Please put an X in the b0x")
|
3d02f3a418d344cec6357d8488dd876d90c0fc51 | ArnoutAllaert/Informatica5 | /Toets/Verkeersdrukte.py | 578 | 3.515625 | 4 | #input
dv = float(input('verkeersdichtheid van het vrachtvervoer op het eerste rijvak: '))
vv = float(input('snelheid van het vrachtverkeer op het eerste rijvak: '))
da = float(input('verkeersdichtheid van het personenvervoer op het tweede rijvak: '))
va = float(input('snelheid van de personenwagens op het tweede rijvak: '))
#berekening
pv = min((dv * vv)/40,1)
pa = min((da * va)/40,1)
if min(pv,pa) > 0.7:
mes = 'zwart'
elif max(pv,pa) > 0.7 and abs(pv - pa) < 0.2:
mes = 'rood'
elif abs(pv - pa) > 0.7:
mes = 'geel'
else:
mes = 'groen'
#uitvoer
print(mes) |
e72ffc302b0b54369ae0349655ee4e980f2d76dc | mukasama/portfolio | /Python Codes/lab 2.py | 901 | 3.984375 | 4 | import turtle
import time
n = int(input("Enter the number of sides for the polygon: "))
print(n)
turtle.down()
r=int(input("Enter amount of red: "))
if r<0 or r>1:
print("Number not between or equal to 0 and 1. Run Program again.")
g=int(input("Enter amount of green: "))
if g<0 or g>1:
print("Number not between or equal to 0 and 1. Run Program again.")
b=int(input("Enter amount of blue: "))
if b<0 or b>1:
print("Number not between or equal to 0 and 1. Run Program again.")
turtle.begin_fill()
for i in range(n):
turtle.color(r,g,b)
turtle.forward(100)
turtle.right(180-(180*(n-2))/n)
turtle.end_fill()
turtle.up()
turtle.goto(0, 250)
turtle.down()
turtle.begin_fill()
count=0
while count < n:
count= count+1
turtle.color(r,g,b)
turtle.forward(100)
turtle.right(180-(180*(n-2))/n)
turtle.end_fill()
|
ff6fea0c935540d60596820b3f7883356b9c7ac5 | LuisTavaresJr/cursoemvideo | /ex23.py | 229 | 3.703125 | 4 | n = int(input('Digite um número entre 0 e 9999: '))
u = n // 1 % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
print(f'A unidade é {u}')
print(f'A dezena é {d}')
print(f'A centena é {c}')
print(f'A milhar é {m}')
|
d38c414fac8ab751d1748d31142c55121a1784bb | LiuJunb/PythonStudy | /book/section-5-条件/01-if语句.py | 557 | 4.15625 | 4 | # 1.if 语句的使用
cars = ['bm', 'ca', 'bc', 'jl']
for value in cars:
if value == 'bm':
print('宝马')
elif value == 'ca':
print('长安')
else:
print('其它')
if True:
print('True')
# 2.比较字符窜是否相等
print('bm' == cars[0]) # True
print('ca' == cars[1]) # True
print('CA' == cars[1]) # False 区分大小写
print('CA' == cars[1].upper()) # True
# 3.多个条件
if cars[0] == 'bm' and cars[1] == 'ca':
print('True')
if cars[0] == 'bm' or cars[1] == 'CA':
print('True')
|
85c728489cfac207918b6e979a93f3443d8f92a9 | JeanneBM/Python | /Owoce Programowania/R13/15. Hello_world.py | 606 | 3.84375 | 4 | # Ten program wyświetla etykietę wraz z tekstem.
import tkinter
class MyGUI:
def __init__(self):
# Utworzenie widżetu okna głównego.
self.main_window = tkinter.Tk()
# Utworzenie widżetu Label zawierającego
# komunikat 'Witaj, świecie!'
self.label = tkinter.Label(self.main_window,
text='Witaj, świecie!')
# Wywołanie metody pack() widżetu Label.
self.label.pack()
# Wejście do pętli głównej tkinter.
tkinter.mainloop()
# Utworzenie egzemplarza klasy MyGUI.
my_gui = MyGUI()
|
0eae6b87fd426ee83c716ff93a1e570b29d8f01f | BayoOlawumi/DS | /functions/class_et_object3.py | 756 | 3.78125 | 4 | class Food:
def __init__(self, name,klass, color, taste, quality):
self.name =name
self.klass = klass
self.color = color
self.taste = taste
self.supplement = False
self.quality =quality
self.supplement_food()
def change_taste(self, new_taste):
self.taste = new_taste
def supplement_food(self):
if self.quality < 65 or self.quality > 100 :
self.supplement = True
if self.supplement:
print(self.name + " is being supplemented")
else:
print(self.name + " is not being supplemented")
yam = Food('Yam', 'carbonhydrate', 'white', 'bitter', 45)
beans = Food('beans', 'protein', 'chocolate', 'sweet', 70)
|
0d74d05756e14982f5d2c2d2dc591da67abb0966 | AHartNtkn/Hash-Tables | /applications/word_count/word_count.py | 499 | 4.03125 | 4 | from collections import Counter
import re
def word_count(s):
c = Counter()
for w in re.split("\s", s):
if w not in '":;,.-+=/\\|[]{}()*^&':
c[w.lower().strip('":;,.-+=/\\|[]{}()*^&')] += 1
return dict(c)
if __name__ == "__main__":
print(word_count(""))
print(word_count("Hello"))
print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.'))
print(word_count('This is a test of the emergency broadcast network. This is only a test.')) |
b07afb9dfee5f0a117d142526586d2b746c0687a | adeshosho/python-THW- | /ex6.py | 558 | 3.96875 | 4 | types_of_people = 10
x = f"There are {types_of_people} types of people"
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}"
print(x)
print(y)
print(f"I said: {x}") # imprimimos lo que esta en X
print(f"I also said: '{y}'")#imprimimos lo que esta en y
hilarious = False #valor booleano
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious)) #Imprimimos mediante una caracteristica una variable
w = "This is the left side of ..."
e = "a string will a right side."
print(w + e)
|
cce5ce57ba5f714f8cc8ba9b72be21234bbd8fb2 | DanielGaszczyk/AdventOfCode2020 | /Day2/Day2.py | 990 | 4.0625 | 4 | #Opening and reading file
def readFile(fileName):
inputFile = open(fileName, 'r')
inputNumbers = inputFile.read().splitlines()
inputFile.close()
return inputNumbers
def findAns():
numbersArray = readFile("inputDay2.txt") #replace with your file with data
result = 0
for y in range(len(numbersArray)-1):
stringToDivide = numbersArray[y]
#preparing string to spliting
stringToDivide = stringToDivide.replace(':','')
stringToDivide = stringToDivide.replace('-',' ')
dividedString = stringToDivide.split(" ")
#Placing divided strings and chars into variables
atLeastNumber = dividedString[0]
mostNumber = dividedString[1]
neededChar = dividedString[2]
# the frequency of occurrence of the sign in between atLeastNumber and mostNumber
if int(atLeastNumber) <= (stringToDivide.count(neededChar)-1) <= int(mostNumber):
result = result+1
print(result)
findAns() |
e7de2e2de1c81d20c6801bf96b3e774bf63cd727 | Dropssie/learningpython | /helloworld.py | 113 | 3.859375 | 4 | print('Hello, World!')
for i in range(10):
print(i)
# Example while
while i < 50:
print(i)
i += 1
|
4ceabfdaf9a481139ea60d06c5182cdbf64dde41 | frombeck/Programming-Using-Python | /prime_numbers.py | 267 | 4.125 | 4 | max=int(input("Find primes upto what numbers?"))
primeList=[]
for x in range(2,max+1):
isPrime=True
for y in range(2,int(x**0.5)+1) :
if x%y==0:
isPrime=False
break
if isPrime:
primeList.append(x)
print(primeList)
|
a288b5089d5e48673abe537d104fd524a21eb865 | acp21/WMU-Accessability | /acess.py | 768 | 3.96875 | 4 | # This is a very simple program that simply removes a certain line of characters from a text file
# It was written for accesability reasons as certain character strings can cause problems with screen readers
# Written by Adam Pohl
import sys
# Get name of file to edit
fileName = sys.argv[1]
# Get fileName without file extension
data = fileName.split(".")
# Prepare output name by appending "out.py" to end of filename
out = data[0] + "out.py"
# Create two files, one for input and one for output
fin = open(fileName, "rt")
fout = open(out, "wt")
# Go through file and replace all long comment lines with nothing
for line in fin:
if "#" in line and "-" in line:
fout.write(line.replace("-", ""))
else:
fout.write(line)
fin.close()
fout.close()
|
7b2f37b83036df7d2fee1e8258309b66cdaaff6b | meighanv/05-Python-Programming | /lab-set-lecture.py | 1,577 | 4.375 | 4 | #Set contains a collection of unique values
#and works like a mathematical set
#All the elements in a set must be unique, no two elements can have the same value
#Sets are unordered
#Elements stored in a set can be of different data types
mySet= set(['a','b','c'])
print(mySet)
mySet2 = set('abc')
print(mySet2)
mySet3 = set('aabbcc')
print(mySet3)
#All of the above appear the same when printed
#set can only take on arg
#mySet4 = set('one','two','three') is invalid
mySet4 = set('one,two,three')
print(mySet4)
newSet = set()
newSet.add(1)
newSet.add(2)
newSet.add(3)
print('newSet', newSet)
newSet.update([4,5,6])
newSet2 = ([7,8,9])
newSet.update(newSet2)
newSet.remove(1)
#using for loop to iterate
newSet3 = set('abc')
for val in newSet3:
print(val)
numbers_set([1, 2, 3])
if 1 in numbers_set:
print('The value {} is in the set'.format(val))
if 99 not in numbers_set:
print('The value {} is not in the set'.format(val))
#unions
set1= set([1,2,3,4])
set2= set([3,4,5,6])
set3= set1.union(set2)
print(set1)
print(set2)
print(set3)
set5= set1|set2
#Find intersection
set4= set1.intersection(set2)
print(set4)
set6= set1&set2
charSet = ('abc')
charSetUpper = ('ABC')
#difference
set7 = set1.difference(set2)
set8 = set2.difference(set1)
print(set1)
print(set2)
set9 = set1-set2
print(set9)
#Finding symmetric differences of sets
set10 = set1.symmetric_difference(set2)
print(set10)
set11 = set1 ^ set2
print(set11)
#Finding subset
set12 = set([1,2,3,4,5,6])
set13 = set([1,2,3])
print(set13.issubset(set12))
print(set12.issuperset(set13))
|
ee92376a0d42ab400cc1af7094c662a2f7c35824 | damiano1996/DataIntelligenceApplications | /project/dia_pckg/Utils.py | 842 | 3.546875 | 4 | """
Here we have general functions that are used in different classes.
"""
import os
import numpy as np
def check_if_dir_exists(path, create=False):
"""
:param path: directory path
:param create: create dir if does not exist?
:return:
"""
if not os.path.isdir(path):
if create:
os.mkdir(path)
return False
else:
return True
def check_if_file_exists(path, create=False):
"""
:param path: file path
:param create: create file if does not exist?
:return:
"""
if not os.path.exists(path):
if create:
file = open(path, 'w')
file.close()
return False
else:
return True
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
|
ceddc5cbac679bdaa65976a9e89c14a999143d5c | yemgunter/inscrutable | /write_rand_numbers.py | 313 | 3.84375 | 4 | #### This program writes 100 random numbers to a file
##
##
import random
# Open a file.
myfile = open('numbers.txt', 'w')
# Write 100 random numbers to the file.
for count in range(100):
number = random.randint(1,100)
myfile.write(str(number) + '\n')
# Close the file.
myfile.close()
print('Done')
|
e683f0cf6706dbe6aae9b300e94d4cf531467f62 | twbot/Random_Python_Files | /hackrank.py | 638 | 3.703125 | 4 | #!/usr/bin/python
import sys
"""def main():
L = []
for x in range(int(raw_input())):
s = raw_input().split()
if s[0] == 'insert':
L.insert(s[1], s[2])
elif s[0] == 'print':
print L
elif s[0] == 'remove':
L.remove(s[1])
elif s[0] == 'append':
L.append(s[1])
elif s[0] == 'sort':
L.sort()
elif s[0] == 'pop':
L.pop()
elif s[0] == 'reverse':
L.reverse()
"""
class vector2d():
def __init__(self, x, y):
self.x = x
self.y = y
def main():
vect = vector2d(5, 6)
print 'X:', vect.x, ' Y:', vect.y
if __name__ == '__main__':
main() |
e451f375860076dc1ad8ae9f39ae96abc3b0f667 | m1ckey/cryptopals | /lib/bit.py | 1,990 | 3.5 | 4 | def xor(b0, b1):
"""
xor, if one is shorter it is repeated
:param b0: bytes
:param b1: bytes
:return: xor'ed bytes
"""
length = len(b0) if len(b0) >= len(b1) else len(b1)
output = bytearray(length)
for i in range(length):
output[i] = b0[i % len(b0)] ^ b1[i % len(b1)]
return output
def xor_ljust(b0, b1):
"""
xor, if one is shorter it is adjusted to the left and filled with null bytes
:param b0: bytes
:param b1: bytes
:return: xor'ed bytes
"""
# dont simply adjust it because python is stupid and would create a copy
length = len(b0) if len(b0) >= len(b1) else len(b1)
if len(b0) < length:
b0 = b0.ljust(length, b'\0')
if len(b1) < length:
b1 = b1.ljust(length, b'\0')
return xor(b0, b1)
def xor_rjust(b0, b1):
"""
xor, if one is shorter it is adjusted to the right and filled with null bytes
:param b0: bytes
:param b1: bytes
:return: xor'ed bytes
"""
# dont simply adjust it because python is stupid and would create a copy
length = len(b0) if len(b0) >= len(b1) else len(b1)
if len(b0) < length:
b0 = b0.rjust(length, b'\0')
if len(b1) < length:
b1 = b1.rjust(length, b'\0')
return xor(b0, b1)
def brute_byte_xor(b):
"""
xor bytes with every byte (0x00 - 0xff)
:param b: bytes
:return: list of every possibility
"""
result = []
for i in range(256):
result.append(xor(b, bytes([i])))
return result
def hamming_distance_byte(b0, b1):
"""
calculate the binary hamming distance
eg (0x00, 0xF0) -> 4
:param b0: bytes
:param b1: bytes
:return: integer hamming distance
"""
if len(b0) != len(b1):
raise Exception('hamming distance for unequal length is undefined')
d = 0
for i in range(len(b0)):
for j in range(8):
if (b0[i] & (2 ** j)) != (b1[i] & (2 ** j)):
d += 1
return d
|
af32d314c5f1119b45cc1623f66db61bf17f766e | Linkin-1995/test_code1 | /day03/exercise04.py | 305 | 3.84375 | 4 | # 练习:
# 在终端中获取一个性别
# 如果是男,提示您好,先生。否则如果是女,提示您好,女士。否则提示性别未知.
sex = input("请输入性别:")
if sex == "男":
print("您好,先生")
elif sex == "女":
print("您好,女士")
else:
print("性别未知")
|
3698dba818e41ae1674a857e274f252619c037d3 | saikiranreddygangidi/Apriori_datamining | /sample_apriori.py | 957 | 3.5 | 4 |
import pandas as pd
import numpy as np
from apyori import apriori
data = pd.read_excel('path_of_excel_file')
df=pd.DataFrame(np.array(data),columns=['list_of_column_names'])
records = []
shape=df.shape()
for i in range(0, shape[0]):
records.append([str(data.values[i,j]) for j in range(0, shape[1])])
print(records)
association_rules = apriori(records, min_support=1, min_confidence=1)
association_results = list(association_rules)
for items in association_results:
# first index of the inner list Contains base item and add item
pair = items[0]
item = [x for x in pair]
if(len(pair)>1):
print("Rule: " + items[0] + " -> " + items[1])
else:
print("Rule: " + items[0] )
#second index of the inner list
print("Support: " + str(item[1]))
#third index of the list located at 0th of the third index of the inner list
print("Confidence: " + str(item[2][0][2]))
print("Lift: " + str(item[2][0][3]))
|
7e4174de64cc55727cf64e6fd254dc7c47174cc0 | madeibao/PythonAlgorithm | /py根据数字来分割链表.py | 984 | 3.671875 | 4 |
# leetcode 86
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
# 创建了两个虚拟的节点值。
dummy1 = ListNode(-1)
dummy2 = ListNode(-1)
p1 = dummy1
p2 = dummy2
while head:
if head.val < x:
p1.next = head
p1 = p1.next
else:
p2.next = head
p2 = p2.next
head = head.next
p1.next = dummy2.next
p2.next = None
return dummy1.next
if __name__ == "__main__":
s = Solution()
n2 = ListNode(1)
n3 = ListNode(4)
n4 = ListNode(3)
n5 = ListNode(2)
n6 = ListNode(5)
n7 = ListNode(2)
n2.next=n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
n7.next = None
res = s.partition(n2,3)
while res:
print(res.val, end="->")
res = res.next
|
a1c0e5d021b49782a5980423518fd0d326d3b7ad | elguerandrea/CS241 | /checkpoints/check05b/check05b.py | 1,161 | 3.671875 | 4 | """
CS 241 Checkpoint 5B
Written by Chad Macbeth
"""
"""
File: check05b.py
Author: Br. Burton
Use this file to practice debugging in PyCharm.
"""
class Money:
"""
Holds a dollars and cents value.
"""
def __init__(self, dollars = 0, cents = 0):
self.dollars = dollars
self.cents = cents
def add_cents(self, cents):
self.cents += cents
self.check_overflow()
def check_overflow(self):
if self.cents > 100:
self.dollars += self.cents // 100
self.cents %= 100
def display(self):
print("${}.{:02d}".format(self.dollars, self.cents))
def main():
"""
The main function tests the Money class
"""
account1 = Money(87, 15)
account2 = Money(5, 5)
account3 = Money(99, 99)
# Display each account balance
account1.display()
account2.display()
account3.display()
# Now add 20 cents to each
account1.add_cents(20)
account2.add_cents(20)
account3.add_cents(20)
# Display each account balance again
print()
account1.display()
account2.display()
account3.display()
if __name__ == "__main__":
main() |
cadf4cb0e15ef5bb84b1f5d4f696a1a43c4a7f54 | FeiZhan/Algo-Collection | /answers/leetcode/Simplify Path/Simplify Path.py | 648 | 3.609375 | 4 | class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
path_list = []
prev = 0
for i in range(len(path) + 1):
if len(path) == i or '/' == path[i]:
if prev + 2 == i and '.' == path[i - 2] and '.' == path[i - 1]:
if len(path_list):
path_list.pop()
elif i - prev > 0 and not (prev + 1 == i and '.' == path[prev]):
path_list.append(path[prev : (i if i < len(path) else i + 1)])
prev = i + 1
return '/' + '/'.join(path_list)
|
01c3c16084eaf7979b36d092087a803c5d1db3e4 | brunodantas/coding-questions | /subsequence.py | 1,268 | 3.59375 | 4 | # https://techdevguide.withgoogle.com/resources/find-longest-word-in-dictionary-that-subsequence-of-given-string
def init_pdict(words):
pdict = dict()
for w in words:
prefix = w[1][0]
if prefix not in pdict:
pdict[prefix] = [w]
else:
pdict[prefix].append(w)
return pdict
def update_pdict(pdict, c):
subsequences = []
if c in pdict:
l = pdict[c]
pdict[c] = []
for e in l:
e[1] = e[1][1:] # remove first character
if e[1] == "":
subsequences.append(e[0])
else:
prefix = e[1][0]
if prefix not in pdict:
pdict[prefix] = [e]
else:
pdict[prefix].append(e)
return subsequences
def longest_subsequence(s, d):
longest = (None, 0)
words = [[id,d[id]] for id in range(len(d))]
pdict = init_pdict(words)
for c in s:
subsequences = update_pdict(pdict, c)
for sub in subsequences:
w = d[sub]
x = len(w)
if x > longest[1]:
longest = (w,x)
return longest[0]
s = "abppplee"
d = ["able", "ale", "apple", "bale", "kangaroo"]
print(longest_subsequence(s,d))
|
29395f5eb4a7c631a23449e5eda020051cc2c321 | Candlemancer/Junior-Year | /CS 3430 - Python and Perl/Class Practice/Strings and Operators.py | 1,397 | 4.125 | 4 | # Jonathan Petersen
# A01236750
# Strings and Operators
# Operators
x = 56;
y = 80;
print(x + y);
print(x - y);
print(x * y);
print(x ** y);
print(x / y);
print(x // y);
print(x % y);
x, y = 34, 66;
# ^x ^y
x, y = y, x; # Swap
# Strings
firstName = "Gerard";
lastName = "Umulat";
#Similar to printf. Use a % and make sure the arguments are contained in ()'s
print( "My name is %s %s, and I am %d years old." % (firstName, lastName, x) );
#import string
#string.upper("Hello");
print("Explode!11!1".upper());
#string.strip("x");
print(" Chiasmatic ".strip());
# String Buildilng
A = [ 'U', 'n', 'i', 'f', 'i', 'c', 'a', 'tion' ];
civilWar = '';
for i in A:
civilWar += i;
print(civilWar);
laborUnion = "".join(A);
print(laborUnion);
# String function
paragraph = '''Whatever you can do,
Or dream you can, Begin it!
Boldness has Genius, Power, and Magic in it.''';
print(paragraph[9].upper() + paragraph[10:16] + ".");
print(paragraph.find("Begin"));
print(paragraph.find("Begin", paragraph.find("Begin") + 1)); # With iniPos specifier.
B = paragraph.split("\n");
print B;
p4r4gr4ph = paragraph.replace("i", "1");
p4r4gr4ph = p4r4gr4ph.replace("l", "1");
p4r4gr4ph = p4r4gr4ph.replace("a", "4");
p4r4gr4ph = p4r4gr4ph.replace("o", "0");
p4r4gr4ph = p4r4gr4ph.replace("s", "$");
p4r4gr4ph = p4r4gr4ph.replace("e", "3");
p4r4gr4ph = p4r4gr4ph.replace(" ", "");
print p4r4gr4ph;
|
cc42c5936af0d80b80ca43fcfe99852a3a2f6ed9 | Ironjanowar/Python | /TalkingBot/talking_bot.py | 1,923 | 3.65625 | 4 | import random
#./talkingLib.txt
leFile = open("talkingLib.txt")
txt = leFile.readlines()
'''def selectRandomLine(filerino):
num = random.randint(0, 10)
while num < 5:
filerino.readline()
leString = filerino.readline()
return leString'''
def init_bot(respuestas):
while 1:
inp = input('>').lower()
if inp.startswith('hola'):
print(random.choice(respuestas['saludos']))
continue
elif inp.startswith('que tal'):
print('Muy bien y tu?');
continue
elif inp.startswith('adios'):
print(random.choice(respuestas['despedidas']))
break
elif inp.startswith("cuentame un cuento"):
i = 0
while i < 10:
print (" " + random.choice(txt))
i += 1
leFile.close()
continue
elif inp.endswith('?'):
print(random.choice(respuestas['cortas']))
continue
else:
print(random.choice(respuestas['largas']))
continue
return
def main():
respuestas_largas = ["Te escucho!",
"Esta claro...",
"Que interesante.",
"Vaya por dios!",
"Que bien!"]
respuestas_cortas = ["Si.",
"No.",
"Claro!",
"Tal vez.",
"Podria ser."]
saludos = ["Well hello!",
"Weeeeeh!",
"Eeeeeh que passsssa!!"]
despedidas = ["Venga a pastar!",
"Ale hasta luego!"]
dict = {'largas':respuestas_largas,'cortas':respuestas_cortas,'saludos':saludos,'despedidas':despedidas}
print("Hey! Esto es un pequeño TalkingBot, dile adios para cerrar el programa.")
init_bot(dict)
if __name__ == "__main__":
main()
|
d3b289dd484be51c0efaa46fc517963ee6a2aa4d | arthur-e/suntransit | /suntransit/__init__.py | 8,008 | 3.71875 | 4 | '''
Module for calculating sunrise and sunset times and, more importantly, for the
length of a day (in hours). The core algorithm is `sunrise_sunset()`.
'''
import datetime
import numpy as np
# The sunrise_sunset() algorithm was written for degrees, not radians
_sine = lambda x: np.sin(np.deg2rad(x))
_cosine = lambda x: np.cos(np.deg2rad(x))
_tan = lambda x: np.tan(np.deg2rad(x))
_arcsin = lambda x: np.rad2deg(np.arcsin(x))
_arccos = lambda x: np.rad2deg(np.arccos(x))
_arctan = lambda x: np.rad2deg(np.arctan(x))
def ecliptic_longitude(true_anomaly, omega = 102.937348):
'''
The longitude of the sun, in ecliptic coordinates, based on the true
solar anomaly and omega, the argument of the perihelion.
See also:
Meeus, J. (1991). Astronomical Algorithms. Willman-Bell Inc.
Parameters
----------
true_anomaly : float or numpy.array
omega : float
Returns
-------
float or numpy.array
'''
return (true_anomaly + 180 + omega) % 360
def equation_of_center(anomaly):
'''
Obtains the angular difference, in degrees, between the true anomaly and
the mean solar anomaly, based on the eccentricity of the earth. This is
a two-degree Taylor series expansion, from:
U.S. Naval Observatory. (1990). Almanac for Computers.
The Nautical Almanac Office, U.S. Naval Observatory, Washington, D.C.
Parameters
----------
anomaly : float or numpy.array
The mean solar anomaly
Returns
-------
float or numpy.array
'''
return (1.916 * _sine(anomaly)) + (0.02 * _sine(2 * anomaly))
def julian_day(year, month, day):
'''
Returns the Julian day using the January 1, 2000 epoch. Taken from
Equation 7.1 in Meeus (1991).
Parameters
----------
year : int
month : int
day : int
Returns
-------
float
'''
# Dates in January, February are considered to be on 13th, 14th month
# of preceding year
if month < 3:
year -= 1
month += 12
a = np.floor(year / 100)
b = 2 - a + np.floor(a / 4)
return np.floor(365.25 * (year + 4716)) +\
np.floor(30.6001 * (month + 1)) + day + b - 1524.5
def obliquity(t_solar):
'''
Obliquity of the ecliptic as a function of mean solar time; valid only for
years in 2000 +/- 10,000 years. Taken from Equation 21.2 in Meeus (1991).
Parameters
----------
t_solar : float
Mean solar time
'''
return 23.43929 - (0.01300416 * t_solar) -\
(1.638e-7 * np.power(t_solar, 2)) +\
(5.0361e-7 * np.power(t_solar, 3))
def solar_noon_zenith_angle(coords, dt):
'''
The solar zenith angle (angular difference between the vertical and the
sun's incident rays) at solar noon (i.e., when this difference is at its
minimum).
Parameters
----------
coords : list or tuple
The (latitude, longitude) coordinates of interest; coordinates can
be scalars or arrays (for times at multiple locations on same date)
dt : datetime.date
The date on which sunrise and sunset times are desired
Returns
-------
float
'''
lat, lng = coords
assert -90 <= lat <= 90, 'Latitude error'
assert -180 <= lng <= 180, 'Longitude error'
doy = int(dt.strftime('%j'))
# Appoximate transit time (longitudinal average)
tmean = doy + ((12 - lng / 15.0) / 24)
# Solar mean anomaly at rising, setting time
anomaly = (0.98560028 * tmean) - 3.289
lng_sun = ecliptic_longitude(anomaly + equation_of_center(anomaly))
# Sun's declination (using 0.39782 = sine of Earth's obliquity)
# retained as sine and cosine
declination = _arcsin(0.39782 * _sine(lng_sun))
# At solar noon, SZA is equal to latitude minus solar declination
return lat - declination
def sunrise_sunset(coords, dt, zenith = -0.83):
r'''
Returns the hour of sunrise and sunset for a given date. Hours are on the
closed interval [0, 23] because Python starts counting at zero; i.e., if
we want to index an array of hourly data, 23 is the last hour of the day.
If the sun never rises or never sets at the specific location and on the
specified date, returns -1.
Recommended solar zenith angles for sunrise and sunset are -6 degrees for
civil sunrise/ sunset; -0.5 degrees for "official" sunrise/sunset; and
-0.83 degrees to account for the effects of refraction. A zenith angle of
-0.5 degrees produces results closest to those of `Observer.next_rising()`
and `Observer.next_setting()` in `pyephem`. This calculation does not
include corrections for elevation or nutation nor does it explicitly
correct for atmospheric refraction. Source:
- U.S. Naval Observatory. "Almanac for Computers." 1990. Reproduced by
Ed Williams. https://www.edwilliams.org/sunrise_sunset_algorithm.htm
The algorithm is based on the derivation of the approximate hour angle of
sunrise and sunset, as described by Jean Meeus (1991) in *Astronomical
Algorithms*, based on the observer's latitude, `phi`, and the declination
of the sun, `delta`:
$$
\mathrm{cos}(H_0) =
\frac{\mathrm{sin}(h_0) -
\mathrm{sin}(\phi)\mathrm{sin}(\delta)}{\mathrm{cos}(\phi)\mathrm{cos}(\delta)}
$$
Parameters
----------
coords : list or tuple
The (latitude, longitude) coordinates of interest; coordinates can
be scalars or arrays (for times at multiple locations on same date)
dt : datetime.date
The date on which sunrise and sunset times are desired
zenith : float
The sun zenith angle to use in calculation, i.e., the angle of the
sun with respect to its highest point in the sky (90 is solar noon)
(Default: -0.83)
Returns
-------
tuple
2-element tuple of (sunrise hour, sunset hour)
'''
lat, lng = coords
assert -90 <= lat <= 90, 'Latitude error'
assert -180 <= lng <= 180, 'Longitude error'
doy = int(dt.strftime('%j'))
# Calculate longitude hour (Earth turns 15 degrees longitude per hour)
lng_hour = lng / 15.0
# Appoximate transit time (longitudinal average)
tmean = doy + ((12 - lng_hour) / 24)
# Solar mean anomaly at rising, setting time
anomaly = (0.98560028 * tmean) - 3.289
# Calculate sun's true longitude by calculating the true anomaly
# (anomaly + equation of the center), then add (180 + omega)
# where omega = 102.634 is the longitude of the perihelion
lng_sun = ecliptic_longitude(
anomaly + equation_of_center(anomaly), omega = 102.634)
# Sun's right ascension (by 0.91747 = cosine of Earth's obliquity)
ra = _arctan(0.91747 * _tan(lng_sun)) % 360
# Adjust RA to be in the same quadrant as the sun's true longitude, then
# convert to hours by dividing by 15 degrees
ra += np.subtract(
np.floor(lng_sun / 90) * 90, np.floor(ra / 90) * 90)
ra_hours = ra / 15
# Sun's declination (using 0.39782 = sine of Earth's obliquity)
# retained as sine and cosine
dec_sin = 0.39782 * _sine(lng_sun)
dec_cos = _cosine(_arcsin(dec_sin))
# Cosine of the sun's local hour angle
hour_angle_cos = (
_sine(zenith) - (dec_sin * _sine(lat))) / (dec_cos * _cosine(lat))
# Correct for polar summer or winter, i.e., when the sun is always
# above or below the horizon
if hour_angle_cos > 1 or hour_angle_cos < -1:
if hour_angle_cos > 1:
return (-1, -1) # Sun is always down
elif hour_angle_cos < -1:
return (0, 23) # Sun is always up
hour_angle = _arccos(hour_angle_cos)
# Local mean time of rising or setting (converting hour angle to hours)
hour_rise = ((360 - hour_angle) / 15) + ra_hours -\
(0.06571 * (tmean - 0.25)) - 6.622
hour_sets = (hour_angle / 15) + ra_hours -\
(0.06571 * (tmean + 0.25)) - 6.622
# Convert to UTC
return (
(hour_rise - lng_hour) % 24,
(hour_sets - lng_hour) % 24)
|
a9a7fc6b9fef95134ad61ed411c16ce752a374ed | kaichunchou/Python-Review | /Exercise_14/Exercise_14.py | 1,241 | 4.15625 | 4 | '''
Exercise 14
Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.
Extras:
- Write two different functions to do this - one using a loop and constructing a list, and another using sets.
- Go back and do Exercise 5 using sets, and write the solution for that in a different function.
'''
#Using hash look up table to make the complexity to O(n+m)
from random import randint
def main():
list_1 = gen_list()
result_1 = set_method(list_1)
result_2 = loop_method(list_1)
list_1.sort() #sort for human to check for mistake(O(nlogn)
result_1.sort()
result_2.sort()
print('List 1: {}'.format(list_1))
print('Set method: {}'.format(result_1))
print('Loop method: {}'.format(result_2))
def gen_list():
return [randint(0,20) for r in range(randint(0,20))]
def loop_method(list_):
result = []
if list_ == []:
return result
for x in range(0, len(list_)):
if list_[x] not in result:
result.append(list_[x])
return result
def set_method(list_):
return list(set(list_))
if __name__ == "__main__":
main()
|
308053e5783335869c16f294849509a733d1b14f | vpc20/leetcode-may-2020 | /CourseSchedule.py | 3,377 | 3.96875 | 4 | # There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. Some courses may
# have prerequisites, for example to take course 0 you have to first take course 1, which is expressed
# as a pair: [0, 1]
#
# Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
#
# Example 1:
# Input: numCourses = 2, prerequisites = [[1, 0]]
# Output: true
# Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is
# possible.
#
# Example 2:
# Input: numCourses = 2, prerequisites = [[1, 0], [0, 1]]
# Output: false
# Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to
# take course 0 you should also have finished course 1. So it is impossible.
#
# Constraints:
# The input prerequisites is a graph represented by a list of edges, not adjacency matrices.Read more about how a
# graph is represented.
# You may assume that there are no duplicate edges in the input prerequisites.
# 1 <= numCourses <= 10 ^ 5
from collections import defaultdict
WHITE = 0 # undiscovered
GRAY = 1 # discovered
BLACK = 2 # finished
def can_finish(n, preqs):
def dfs(u):
colors[u] = GRAY
for v in g[u]:
if colors[v] == WHITE:
if not dfs(v):
return False
elif colors[v] == GRAY:
return False
colors[u] = BLACK
return True
if not preqs:
return True
g = defaultdict(list) # graph for prerequisites
for v, u in preqs: # directed graph
g[u].append(v)
# print(g)
colors = {} # vertex colors
for u in range(n):
colors[u] = WHITE
for u in list(g):
if colors[u] == WHITE:
if not dfs(u):
return False
return True
# def can_finish(n, preqs):
# def dfs(u):
# visited.add(u)
# cycles.add(u)
# for v in g[u]:
# if v not in visited:
# if not dfs(v):
# return False
# elif v in cycles:
# return False
# cycles.remove(u)
# return True
#
# if not preqs:
# return True
# g = defaultdict(list) # graph for prerequisites
# for i in range(n):
# g[i] = []
# for v, u in preqs: # directed graph
# g[u].append(v)
# print(g)
#
# visited = set()
# cycles = set()
# for u in list(g):
# if u not in visited:
# if not dfs(u):
# return False
# return True
# print(can_finish(1, []))
# print(can_finish(2, [[1, 0]]))
# print(can_finish(3, [[2, 1], [1, 0]]))
# print(can_finish(4, [[3, 2], [2, 1], [1, 0]]))
# print(can_finish(4, [[1, 2], [3, 2], [2, 1], [1, 0]]))
# print(can_finish(5, [[1, 0], [2, 1], [3, 4], [4, 3]]))
# print(can_finish(5, [[1, 0], [2, 1], [4, 3], [2, 4]]))
# print(can_finish(20, [[0, 10], [3, 18], [5, 5], [6, 11], [11, 14], [13, 1], [15, 1], [17, 4]]))
assert can_finish(2, [[1, 0], [0, 1]]) is False
assert can_finish(3, [[1, 0], [2, 1], [0, 2]]) is False
assert can_finish(4, [[1, 0], [2, 0], [3, 1], [3, 2]]) is True
# l = [[0, 10], [3, 18], [5, 5], [6, 11], [11, 14], [13, 1], [15, 1], [17, 4]]
# l = [[1, 0], [2, 0], [3, 1], [3, 2]]
# print([(e[1], e[0]) for e in l])
|
8c9fdb8152729becc92d04ef62dfdacd14d5e37d | kushinoyuya/Python_Project | /05_lesson.py | 824 | 3.59375 | 4 | print("##########演習5-1##########")
def display_investory(investory):
print('持ち物リスト:')
item_total = 0
for k,v in investory.items():
print(str(investory[k])+ ' ' + k)
item_total += v
print("アイテム総数:" + str(item_total))
stuff = {'ロープ':1, 'たいまつ':6, '金貨':42, '手裏剣':1, '矢':12}
display_investory(stuff)
print("##########演習5-2##########")
dragon_loot = ['金貨', '手裏剣', '金貨', '金貨', 'ルビー']
def add_to_investory(investory, added_items):
for i in added_items:
investory.setdefault(i, 0)
investory[i] += 1
return investory
inv = {'金貨': 42, 'ロープ': 1}
dragon_loot = ['金貨', '手裏剣', '金貨', '金貨', 'ルビー']
inv = add_to_investory(inv, dragon_loot)
display_investory(inv)
|
2917024d4e1ae8208ac9d7c17e3faaf3c637455a | shjang1013/Algorithm | /BAEKJOON/큐, 덱/18258_큐2.py | 1,240 | 3.65625 | 4 | # queue.pop(0)에서 시간초과
import sys
N = int(input())
queue = []
for _ in range(N):
command = sys.stdin.readline().split()
if command[0] == 'push':
queue.append(command[1])
elif command[0] == 'pop':
print(queue.pop(0)) if len(queue) else print("-1")
elif command[0] == "size":
print(len(queue))
elif command[0] == 'empty':
print("0") if len(queue) else print("1")
elif command[0] == 'front':
print(queue[0]) if len(queue) else print("-1")
elif command[0] == 'back':
print(queue[-1]) if len(queue) else print("-1")
# 수정한 코드
import sys
from collections import deque
N = int(input())
queue = deque([])
for _ in range(N):
command = sys.stdin.readline().split()
if command[0] == 'push':
queue.append(command[1])
elif command[0] == 'pop':
print(queue.popleft()) if len(queue) else print("-1")
elif command[0] == "size":
print(len(queue))
elif command[0] == 'empty':
print("0") if len(queue) else print("1")
elif command[0] == 'front':
print(queue[0]) if len(queue) else print("-1")
elif command[0] == 'back':
print(queue[-1]) if len(queue) else print("-1")
|
c448ba82dc784564e4da2a1c014475ca8f006509 | oneInsect/simple_automl | /server/feature_select/ts_feature_select.py | 2,020 | 3.5625 | 4 | """
CreateTime : 2019/6/3 19:43
Author : X
Filename : ts_feature_select.py
"""
from tsfresh.feature_selection import select_features
def feature_selector(X, y, ml_task='auto', n_jobs=0):
"""
Calculate the relevance table for the features contained in feature matrix `X` with respect to target vector `y`.
The relevance table is calculated for the intended machine learning task `ml_task`.
To accomplish this for each feature from the input pandas.DataFrame an univariate feature significance test
is conducted. Those tests generate p values that are then evaluated by the Benjamini Hochberg procedure to
decide which features to keep and which to delete.
:param X: Feature matrix in the format mentioned before which will be reduced to only the relevant features.
It can contain both binary or real-valued features at the same time.
:param y: Target vector which is needed to test which features are relevant. Can be binary or real-valued.
:param ml_task: The intended machine learning task. Either `'classification'`, `'regression'` or `'auto'`.
Defaults to `'auto'`, meaning the intended task is inferred from `y`.
If `y` has a boolean, integer or object dtype, the task is assumend to be classification,
else regression.
:param n_jobs: Number of processes to use during the p-value calculation
:return: A pandas.DataFrame with each column of the input DataFrame X as index with information on the significance
of this particular feature. The DataFrame has the columns
"Feature",
"type" (binary, real or const),
"p_value" (the significance of this feature as a p-value, lower means more significant)
"relevant" (True if the Benjamini Hochberg procedure rejected the null hypothesis [the feature is
not relevant] for this feature)
"""
return select_features(X, y, ml_task=ml_task, n_jobs=n_jobs)
|
ec6bd1821c015bbcadcdf35fb02471c5d5d648ca | seNpAi-code/My_first_pythonProgram | /first.py | 338 | 3.90625 | 4 |
# My_first_pythonProgram
#my first python program
myName="Allen"
myAge="19"
print("My name is " + myName + ".")
print("I'm " + myAge + " years old.")
title="Naruto Shippuden"
print(title+ " is my favourite anime")
playerName="Auspiousjester69"
print("My gaming handle is " +playerName)
print(playerName.lower())
print(playerName.upper())
|
39e395ffa92e4540902fc4acbaed691b34a8c0af | lonsty/online-programing | /remove_chars_appear_least.py | 759 | 3.765625 | 4 | # Author: Allen
# Date: 2020-4-15 22:47:55
"""
实现删除字符串中出现次数最少的字符,若多个字符出现次数一样,则都
删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。
注意每个输入文件有多组输入,即多个字符串用回车隔开
"""
def remove_least_chars(string):
counter = {}
for c in string:
if c not in counter:
counter[c] = 1
else:
counter[c] += 1
minimum = min(counter.values())
return ''.join([c for c in string if counter[c] != minimum])
while 1:
try:
string = input()
if not string:
break
print(remove_least_chars(string))
except:
break
|
ff3cf0ab81f18d51dd1b02e8942164bb9cb8e54a | dalexach/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/5-momentum.py | 699 | 4 | 4 | #!/usr/bin/env python3
"""
Momentum
"""
import numpy as np
def update_variables_momentum(alpha, beta1, var, grad, v):
"""
Function that updates a variable using the gradient descent with momentum
optimization algorithm:
Arguments:
- alpha is the learning rate
- beta1 is the momentum weight
- var is a numpy.ndarray containing the variable to be updated
- grad is a numpy.ndarray containing the gradient of var
- v is the previous first moment of var
Returns:
The updated variable and the new moment, respectively
"""
V = np.multiply(beta1, v) + np.multiply((1 - beta1), grad)
Var = var - np.multiply(alpha, V)
return Var, V
|
f8bb056e12192479ab92907394f9f1426fc4b66f | KimEklund13/SeleniumWD-with-Python3x | /basicsSyntax/methods_homework.py | 1,399 | 4.34375 | 4 | """
Tax in US based on states:
Create a method, which takes the state and gross income as arguments
and returns the net income after deducting tax based on the state.
Assume federal tax: 10%
Assume state tax of your residence
You don't have to do this for all states, just take 3-4 to solve the purpose
of the exercise
"""
# def calculate_tax(state, gross):
# federal_rate = .10
# state_rate = 0
#
# if state == "california" or state == "oregon":
# state_rate = .10
# elif state == "south carolina":
# state_rate = .07
# else:
# state_rate = .08
#
# return gross - (gross * (federal_rate + state_rate))
#
# my_check = calculate_tax("california", 1000)
# print(my_check)
# Better solution:
def calculate_net_income(gross, state):
"""
Calculate the net income after federal and state tax
:param gross: Gross Income
:param state: State name
:return: Net income
"""
state_tax = {"CA": 10, "NY": 9, "TX": 0, "NJ": 6}
# Calculate the net income after federal tax
net = gross - (gross * .10)
# Calculate net income after state tax
if state in state_tax:
net = net - (gross * state_tax[state] / 100)
print("Your net income after all the heavy taxes is: " + str(net))
return net
else:
print("State not in the list")
return None
calculate_net_income(100000, "CA") |
0697bc29e182d04ba41f2051893d55e8ee4bea90 | NamanJain14101999/DSA_USING_PYTHON | /TREES_WITH_PYTHON/BST_IN_PYTHON.py | 2,642 | 3.84375 | 4 | class BinarySearchTreeNode:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def add_child(self,data):
if data == self.data:
return
if data<self.data:
if self.left:
self.left.add_child(data)
else:
self.left = BinarySearchTreeNode(data)
if data>self.data:
if self.right:
self.right.add_child(data)
else:
self.right = BinarySearchTreeNode(data)
def in_order_traversal(self):
value=[]
if self.left:
value+=self.left.in_order_traversal()
value.append(self.data)
if self.right:
value+=self.right.in_order_traversal()
return value
def search(self,value):
if self.data==value:
return True
if value<self.data:
if self.left:
return self.left.search(value)
else:
return False
if value>self.data:
if self.right:
return self.right.search(value)
else:
return False
def max_tree(self):
while self.right!=None:
return self.right.max_tree()
return self.data
def min_tree(self):
if self.left is None:
return self.data
return self.left.min_tree()
def delete(self,value):
if self.data>value:
if self.left:
self.left=self.left.delete(value)
elif value > self.data:
if self.right:
self.right=self.right.delete(value)
else:
#delete leaf node
if self.left is None and self.right is None:
return None
#delete one child node
elif self.right is None:
return self.left
elif self.left is None:
return self.right
#delete two child
min_val = self.right.min_tree()
self.data=min_val
self.right=self.right.delete(min_val)
return self
def build_tree(numbers):
print("print tree elements ",numbers)
root = BinarySearchTreeNode(numbers[0])
for i in range(1,len(numbers)):
root.add_child(numbers[i])
return root
numbers = [17,4,1,20,9,23,8,34]
tree = build_tree(numbers)
print(tree)
print(tree.in_order_traversal())
print(tree.search(20))
print("max element is ,",tree.max_tree())
print(tree.delete(17))
print(tree.in_order_traversal())
|
3dbc5e8594bd733f9600fd0cea409201feb7707c | yangyang5214/note | /bricks/1725.py | 518 | 3.625 | 4 | # -*- coding: utf-8 -*-
from typing import List
def countGoodRectangles(rectangles: List[List[int]]) -> int:
m = {}
max_flag = 0
for _ in rectangles:
side = min(_[0], _[1])
max_flag = max(max_flag, side)
if side in m:
m[side] = m[side] + 1
else:
m[side] = 1
return m[max_flag]
if __name__ == '__main__':
rectangles = [[5, 8], [3, 9], [5, 12], [16, 5]]
rectangles = [[2,3],[3,7],[4,3],[3,7]]
print(countGoodRectangles(rectangles))
|
5b1c98568a19e5add88017b6c8c08bdf9e7339f2 | CheungChan/tensorflowtest | /chapter3/chapter3_2.py | 1,000 | 3.734375 | 4 | import tensorflow as tf
"""
通过TensorFlow训练神经网络模型
"""
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
# tf.assign(w1, w2, validate_shape=False)
# x = tf.constant([[0.7, 0.9]])
# 定义placeholder作为存放输入数据的地方。这里维度也不一定要定义。但如果维度是确定的,那么给出维度可以降低出错的概率。
x = tf.placeholder(tf.float32, shape=(None, 2), name="input")
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
sess = tf.Session()
init_op = tf.global_variables_initializer()
sess.run(init_op)
# print(sess.run(y))
# You must feed a value for placeholder tensor 'input' with dtype float and shape [1,2]
print(sess.run(y, feed_dict={x: [[0.7, 0.9]]}))
# 会跟上一节输出一样的结果 [[ 3.95757794]]
print(sess.run(y, feed_dict={x: [[0.7, 0.9], [0.1, 0.4], [0.5, 0.8]]}))
# [[ 3.95757794]
# [ 1.15376544]
# [ 3.16749239]]
sess.close()
|
b2bd7d6eedbb0de1c6116268ebdd6a1afdbb8bea | mr-sige/user-test | /python/clock.py | 142 | 3.5 | 4 | from datetime import datetime
today = datetime.now().strftime("%B %d, %Y")
time = datetime.now().time().strftime("%H:%M")
print(today, time) |
e877703bdc155faf21fb8da6da8cef0ed7791eae | romersjesusds/trabajo | /verificador nro 03.py | 451 | 3.890625 | 4 | #CALCULADORA nro3
# Esta calculadora realiza el calculo del Trabajo en Newton*metro
# Declaracion de la variable
fuerza2,distancia,trabajo=0.0,0.0,0.0
# Calculadora
fuerza2=10
distancia=20
trabajo=fuerza2*distancia
#mostrar datos
print("fuerza2 = ", fuerza2)
print("distancia = ", distancia)
print("trabajo = ", trabajo)
#verificador
trabajo_elevado=(trabajo==200)
print("el trabajo es igual a 200 joules?", trabajo_elevado)
|
768b32fc8fc571afe7820cc46aeb1e034daf20bf | DarkAlexWang/leetcode | /ReferenceSolution/821.shortest-distance-to-a-character.151072700.ac.py | 1,083 | 3.828125 | 4 | #
# [841] Shortest Distance to a Character
#
# https://leetcode.com/problems/shortest-distance-to-a-character/description/
#
# algorithms
# Easy (62.90%)
# Total Accepted: 6.7K
# Total Submissions: 10.7K
# Testcase Example: '"loveleetcode"\n"e"'
#
# Given a string S and a character C, return an array of integers representing
# the shortest distance from the character C in the string.
#
# Example 1:
#
#
# Input: S = "loveleetcode", C = 'e'
# Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
#
#
#
#
# Note:
#
#
# S string length is in [1, 10000].
# C is a single character, and guaranteed to be in string S.
# All letters in S and C are lowercase.
#
#
#
class Solution(object):
def shortestToChar(self, S, C):
prev = float('-inf')
ans = []
for i, x in enumerate(S):
if x == C:
prev = i
ans.append(i - prev)
prev = float('inf')
for i in xrange(len(S) - 1, -1, -1):
if S[i] == C:
prev = i
ans[i] = min(ans[i], prev - i)
return ans
|
9bd48cf83830ca838da07d405e2370c1b61bb71e | ReeceBank/DemandPagingAlgorithms | /paging.py | 6,822 | 3.96875 | 4 | #by Reece van der Bank
# writen in python 3.6.4
# FIFO, LRU, and OPT paging algorithms in python.
#----- IMPORTS ------------------------------------------------------------------------------------------
import sys
import random
#----- MAIN (just for the sequence and calls each function) ---------------------------------------------
def main():
#~~~<three different ways to load in a sequence>~~~
pages = stringToArray(85625354235326256856234213754315) #for using a already made sequence, any number greater than 0 works
pages = [5,9,4,2,4,2,6,9,7,0,7,6,3,9,6,1,6,9,6,1,9,9,8,2,1,5,7,3,5,0] #can also simply set the pages as a already made array
pages = randArray(32) #creates a random sequence of size 16. change for greater sizes
#just comment out/remove the ones not wanting to be used
#~~~</three different ways to load in a sequence>~~~
size = int(sys.argv[1])
print ("FIFO", FIFO(size,pages), "page faults.")
print ("LRU", LRU(size,pages), "page faults.")
print ("OPT", OPT(size,pages), "page faults.")
#----- FIFO START ---------------------------------------------------------------------------------------
def FIFO(size,pages):
pagefaults = 0
fifoList = [] #page frame
fifoAge = [] # tracks the current age of the pages in the frame. this is the same as order of them going in as the fist page will always be the oldest, second will be second oldest etc.
for i in pages:
if i in fifoList: #fifo doesnt care if a page is already in frame, but lru does
continue
else:
pagefaults+=1 #page was not in the frame so a fault occured
if (len(fifoList)<size): #sees if theres empty space in the frame, if there is then it just adds the page and tracks its order/age
fifoList.append(i)
fifoAge = [x+1 for x in fifoAge]
fifoAge.append(0)
else:
fifoList.pop(fifoAge.index(max(fifoAge))) #if the frame is full then it finds and removes the oldest page from both the frame and age tracking list
fifoAge.pop(fifoAge.index(max(fifoAge)))
fifoList.append(i)
fifoAge = [x+1 for x in fifoAge] #ages all the other pages up by one
fifoAge.append(0) #newest added page is given an age of zero
return pagefaults
#----- LRU START ---------------------------------------------------------------------------------------
# lru is almost idential to fifo except when a page is fround thats already in the frame is just resets that pages age and ages all the other pages up by one
def LRU(size,pages):
pagefaults = 0
lruList = [] #page frame
lruAge = [] #tracks the least recently used
for i in pages:
if i in lruList:
lruAge = [x+1 for x in lruAge] # increase the age of each page by 1
lruAge[lruList.index(i)] = 0 #when a page has been found and is a hit then it resets the counter for that page since lru wants to remove the least recently used page, and this one was just used
else:
pagefaults+=1
if (len(lruList)<size): #the page frame has space for more pages so it just adds that page
lruList.append(i)
lruAge = [x+1 for x in lruAge] #ages every other page up by one
lruAge.append(0) #and then sets the newest pages age to zero
else:
lruList.pop(lruAge.index(max(lruAge))) #if the frame is full then it finds and removes the least recently used page from both the frame and age tracking list
lruAge.pop(lruAge.index(max(lruAge)))
lruList.append(i)
lruAge = [x+1 for x in lruAge] #ages all the other pages up by one
lruAge.append(0) #newest added page is given an age of zero
return pagefaults
#----- OPT START -----------------------------------------------------------------------------------------
def OPT(size,pages):
pagefaults = 0
optList = [] #page frame
popList = pages[:] #makes a copy of the full sequence to remove them step by step to help keep track of which value is furthest away from being used. used as a basic list queue
for i in pages:
if i in optList:
popList.remove(i)
continue
else:
pagefaults+=1
if (len(optList)<size): # the frame still has space so it just slots the next one in and go along the popList 'queue'
optList.append(i)
popList.remove(i)
else:
choppingblockList = [] #chopping block is dynamic and will only be used if every number in current frame appears later on. theyre added as the program finds which ones are still in the sequence and their distance from the start.
popList.remove(i)
for x in optList:
if(x not in popList): #poplist is constaly reduced so as to not find pages already loaded in
optList.remove(x)
optList.append(i)
break #found a page in the frame that doesnt appear again, making it the easiest choice to remove
else:
choppingblockList.append(popList.index(x))
if (len(choppingblockList)==len(optList)):
optList.pop(choppingblockList.index(max(choppingblockList))) #will only be reached if every value in the frame appears again later in the sequence, then will find which one is furthest away and replaces it
optList.append(i)
return pagefaults
#----- Random number sequence generator -------------------------------------------------------------
# Used to make random strings of given length for running the algorithms
def randArray(length):
randList = []
for x in range(length):
randList.append(random.randint(0,9))
return randList
#convert a string to array
def stringToArray(string):
randarray = [int(i) for i in str(string)] #to convert a given string of numbers like 123194231 into a array of [1,2,3,1,9,4.. etc for the algorithms. just a simply QoL function
return randarray
#----- name=main ------------------------------------------------------------------------------------
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python paging.py [number of pages]")
elif (sys.argv[1]=='0'): #failsafing
print("Frame size cannot be smaller than 1")
else:
main()
|
e86d73fb62f51f9a6429c746010eb5b90fe9a3ff | Mandhularajitha/function | /calculater function.py | 337 | 3.734375 | 4 | def add(n1,n2):
x1=n1+n2
return x1
def sub(n1,n2):
x2=n1-n2
return x2
def mul(n1,n2):
x3=n1*n2
return x3
def div(n1,n2):
x4=n1%n2
return x4
def fname(a,b):
print(add(a,b))
print(sub(a,b))
print(mul(a,b))
print(div(a,b))
n1=int(input("enter num"))
n2=int(input("enter num"))
fname(n1,n2)
|
78c5de6539b5e7542352bb92d9fa315584d14d6c | kimanhta87/KimAnhTa-D4E17 | /session3/list_intro.py | 1,258 | 3.8125 | 4 | # quan_ao1 = 'hoodie'
# quan_ao2 = 'ao phong'
# quan_ao3 = 'quan bo'
# list_quan_ao = ['hoodie', 'ao phong', ' quan bo',]
# print(list_quan_ao)
# print(list_quan_ao[-1])
# list_quan_ao.append('ao ba lo') #create
# print(list_quan_ao)
# list_quan_ao[2] = 'ao bo' #update
# index = list_quan_ao('quan que') # find index of items
# print ('index of quan que is', index )
# list_quan_ao.pop(0)
# #C R U D
# #CREATE READ UPDATE DELETE
# #THEM SUA XOA
# List
quan_ao1 = 'hoodie'
quan_ao2 = 'ao phong'
quan_ao3 = 'quan bo'
list_quan_ao = ['hoodie', 'ao phong', 'quan bo', 'quần què']
list_quan_ao.append('áo ba lỗ') # Create
index = list_quan_ao.index('quần què') # find index of item
list_quan_ao[index] = 'áo mới' # update
removed_item = list_quan_ao.pop(0) # remove item and save it
print(removed_item)
list_quan_ao.remove('quan bo') # remove by item value
if 'ao phong' in list_quan_ao: # check if item in list
print('yeayy')
len_list_quan_ao = len(list_quan_ao)
for i in range(len_list_quan_ao): # Read all
print('item', list_quan_ao[i]) # Read
for item in list_quan_ao: # Read all
print(item)
# Create Read Update Delete
# print(list_quan_ao)
# print(quan_ao1)
# print(quan_ao2)
# print(quan_ao3) |
937877172d3a8cbde02040ba9bccfa24d93b1cd1 | sunil2982/python_core | /turtleChall.py | 515 | 4.28125 | 4 | import turtle
obj=turtle.Turtle()
sides = int(input("how many sides of polygone you want to drow"))
print("do you want to drow polygone into polygone?")
ans=input("yes or no?")
if ans.upper() == "YES" :
for steps in range(sides):
obj.forward(100)
obj.right(360/sides)
for steps in range(sides):
obj.forward(50)
obj.right(360/sides)
else:
for steps in range(sides):
obj.forward(50)
obj.right(360/sides)
turtle.done() |
ca29fe835136990e4bdc6020f6bd610a5a186065 | RomanAkhmedov/Python_basics | /lesson_1/task_04.py | 594 | 4.25 | 4 | # Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл
# while и другие арифметические операции.
user_number = int(input('Введите целое положительное число: '))
max_digit = user_number % 10
while user_number > 0:
if user_number % 10 > max_digit:
max_digit = user_number % 10
user_number //= 10
print(f'Наибольшая цифра в числе: {max_digit}')
|
51ae517c955efb334309e52c22225efe08330761 | namankitarana/SSW-555-GEDCOM-Project | /MK_Project03_Siddhart.py | 12,610 | 3.625 | 4 | """
=============================================================================
| Assignment: Project 3
| Author: Siddhart Lapsiwala (slapsiwa@stevens.edu)
| Grader: James Rowland
| Course: SW555 - Agile Methods of Software Dev.
| Instructor: James Rowland
| Due Date: Wednesday (06/10/2018) 10pm
| Language: Python
| Ex. Packages: N/A
| Deficiencies: None
| Functions: 1. file_reader(path)
===========================================================================
"""
from prettytable import PrettyTable
from datetime import datetime
import unittest
birthdate = []
marrdate = []
divdate = []
deathdate = []
alldates = birthdate + marrdate + divdate + deathdate
todaysdate = datetime.today().strftime('%Y-%m-%d')
def file_reader(path):
"""Read the contains of file"""
try:
fp = open(path, 'r')
except FileNotFoundError:
raise FileNotFoundError("File not found : ", path)
except IOError:
raise IOError("Error opening file : ", path)
else:
with fp:
for line_num, line in enumerate(fp):
fields = line.strip().split()
if len(fields) >= 3:
fields = line.strip().split(" ",2)
elif len(fields) < 1:
raise ValueError("Excepted number of fields is not present in row.")
else:
fields = line.strip().split()
fields.append("")
yield fields
class Individual:
"""Single Individual"""
def __init__(self, id):
self.id = id
self.name = ''
self.gender = ''
self.birthday = 'NA'
self.age = 'NA'
self.alive = 'TRUE'
self.death = 'NA'
self.child = set()
self.spouse = set()
def add_name(self, name):
self.name = name
def add_gender(self, gender):
self.gender = gender
def add_birthday(self,birthday):
self.birthday = birthday
def add_age(self,flag,current_tagdate):
if flag == 'Death':
birthday = datetime.strptime(self.birthday, '%Y-%m-%d')
end_date = datetime.strptime(current_tagdate, '%Y-%m-%d')
else:
birthday = datetime.strptime(self.birthday, '%Y-%m-%d')
end_date = datetime.today()
age = end_date.year - birthday.year - ((end_date.month, end_date.day) < (birthday.month, birthday.day))
self.age = age
def add_death(self, death):
self.death = death
def add_alive(self,alive):
self.alive = alive
def add_child(self, id):
self.child.add(id)
def add_spouse(self, id):
self.spouse.add(id)
def pt_row(self):
if len(self.child) == 0:
self.child = "NA"
if len(self.spouse) == 0:
self.spouse = "NA"
return [self.id, self.name, self.gender, self.birthday, self.age, self.alive, self.death, self.child, self.spouse]
class Family:
"""Single Family"""
def __init__(self, id):
self.id = id
self.marriage = 'NA'
self.divorced = 'NA'
self.husband_id = set()
self.husband_name = 'NA'
self.wife_id = set()
self.wife_name = 'NA'
self.children = set()
def add_marriage(self, marriage):
self.marriage = marriage
def add_divorce(self, divorced):
self.divorced = divorced
def add_husband_id(self, id):
self.husband_id.add(id)
def add_husband_name(self,name):
self.husband_name = name
def add_wife_id(self, id):
self.wife_id.add(id)
def add_wife_name(self,name):
self.wife_name = name
def add_children(self, id):
self.children.add(id)
def pt_row(self):
if len(self.children) == 0:
self.children = 'NA'
return [self.id, self.marriage, self.divorced, self.husband_id, self.husband_name, self.wife_id,
self.wife_name, self.children]
class Repository:
def __init__(self):
"""All information about Individual and Family"""
self.individual = dict()
self.family = dict()
def add_individual(self,level,argument,tag):
self.individual[argument] = Individual(argument)
def add_family(self,level,argument,tag):
self.family[argument] = Family(argument)
def individual_table(self):
pt = PrettyTable(
field_names=['ID', 'Name', 'Gender', 'Birthday', 'Age','Alive','Death','Child','Spouse'])
for key in sorted(self.individual.keys()):
pt.add_row(self.individual[key].pt_row())
print(pt)
def family_table(self):
pt = PrettyTable(
field_names=['ID', 'Married', 'Divorced', 'Husband ID', 'Husband Name', 'Wife ID','Wife Name','Children'])
for key in sorted(self.family.keys()):
pt.add_row(self.family[key].pt_row())
print(pt)
def main():
path = 'proj03test.ged' #input("Enter file name with extension: ")
repo = Repository()
for level, tag, argument in file_reader(path):
print(level, tag, argument)
result = list()
valid_tags = {'NAME': '1', 'SEX': '1','MARR': '1',
'BIRT': '1', 'DEAT': '1', 'FAMC': '1', 'FAMS': '1',
'HUSB': '1', 'WIFE': '1', 'CHIL': '1',
'DIV': '1', 'DATE': '2', 'HEAD': '0', 'TRLR': '0', 'NOTE': '0'}
special_valid_tags = {'INDI': '0','FAM': '0'}
valid_tag_level = False
if argument in ['INDI', 'FAM']:
special_tags = True
for current_tag, current_level in special_valid_tags.items():
if level == current_level and argument == current_tag:
valid_tag_level = True
break
else:
special_tags = False
for current_tag, current_level in valid_tags.items():
if level == current_level and tag == current_tag:
valid_tag_level = True
break
if valid_tag_level and special_tags:
result.append(level)
result.append(argument)
result.append("Y")
result.append(tag)
if argument in ["INDI"]:
repo.add_individual(level,tag,argument)
current_id = tag
else:
repo.add_family(level,tag,argument)
current_id = tag
elif not valid_tag_level and not special_tags:
result.append(level)
result.append(tag)
result.append("N")
result.append(argument)
elif valid_tag_level and not special_tags:
result.append(level)
result.append(tag)
result.append("Y")
result.append(argument)
if tag == "NAME":
repo.individual[current_id].add_name(argument)
elif tag == "SEX":
repo.individual[current_id].add_gender(argument)
elif tag == "FAMC":
repo.individual[current_id].add_child(argument)
elif tag == "FAMS":
repo.individual[current_id].add_spouse(argument)
elif tag in "HUSB":
repo.family[current_id].add_husband_id(argument)
repo.family[current_id].add_husband_name(repo.individual[argument].name)
elif tag in "WIFE":
repo.family[current_id].add_wife_id(argument)
repo.family[current_id].add_wife_name(repo.individual[argument].name)
elif tag in "CHIL":
repo.family[current_id].add_children(argument)
elif tag in ["BIRT", "DEAT", "DIV", "MARR"]:
check_date_tag = True
previous_tag = tag
elif tag == "DATE" and check_date_tag == True:
argument = datetime.strptime(argument, '%d %b %Y').strftime('%Y-%m-%d')
if previous_tag == "BIRT":
repo.individual[current_id].add_birthday(argument)
repo.individual[current_id].add_age('Birth', argument)
if argument < todaysdate:
birthdate.append(argument)
else:
repo.individual[current_id].add_birthday("Invalid Birthday")
elif previous_tag == "DEAT":
repo.individual[current_id].add_death(argument)
repo.individual[current_id].add_alive("False")
repo.individual[current_id].add_age('Death', argument)
if argument < todaysdate:
deathdate.append(argument)
else:
repo.individual[current_id].add_death("Invalid Death day")
elif previous_tag == "MARR":
repo.family[current_id].add_marriage(argument)
if argument < todaysdate:
marrdate.append(argument)
else:
repo.individual[current_id].add_marriage("Invalid Marriage day")
elif previous_tag == "DIV":
repo.family[current_id].add_divorse(argument)
if argument < todaysdate:
divdate.append(argument)
else:
repo.individual[current_id].add_divorse("Invalid Divorce day")
else:
result.append(level)
result.append(argument)
result.append("N")
result.append(tag)
print("|".join(result))
print("\n Individual Summary")
repo.individual_table()
print("\n Family Summary")
repo.family_table()
def before_current_date(date1, date2):
"""MK Test Function"""
firstdate = datetime.strptime(date1,'%Y-%m-%d')
seconddate =datetime.strptime(date2,'%Y-%m-%d')
if firstdate <= seconddate:
return True
else:
return False
class DateTestCase(unittest.TestCase):
""" MK Test for Sprint 1"""
"""US01 Dates before Current Date"""
def test_birth_dates_before_current(self):
individual = Individual("I01")
individual.add_birthday("1960-07-15")
future_date = "2500-06-23"
self.assertTrue(individual.id == "I01")
self.assertTrue(individual.birthday == "1960-07-15")
self.assertTrue(before_current_date(individual.birthday, todaysdate))
self.assertFalse(before_current_date(future_date, individual.birthday))
def test_death_dates_before_current(self):
""" MK Test for Sprint 1"""
"""US01 Dates before Current Date"""
individal = Individual("I01")
individal.add_death("2013-12-31")
self.assertTrue(individal.death == "2013-12-31")
self.assertTrue(before_current_date(individal.death, todaysdate))
def test_married_dates_before_current(self):
""" MK Test for Sprint 1"""
"""US01 Dates before Current Date"""
family = Family("I01")
family.add_marriage("1980-02-14")
self.assertTrue(family.marriage == "1980-02-14")
self.assertTrue(before_current_date(family.marriage, todaysdate))
def test_divorce_dates_before_current(self):
""" MK Test for Sprint 1"""
"""US01 Dates before Current Date"""
family = Family("I01")
family.add_divorce("1982-02-15")
self.assertTrue(family.divorced == "1982-02-15")
self.assertTrue(before_current_date(family.divorced, todaysdate))
def test_all_dates(self):
""" MK Test for Sprint 1"""
"""US01 Dates before Current Date"""
for eadates in alldates:
self.assertTrue(eadates < todaysdate)
def test_birth_before_marriage(self):
"""MK Test for sprint 1"""
"""US08 Birth Before Marriage of Parents"""
family = Family("F23")
individual = Individual("I19")
family.add_marriage("1980-02-14")
individual.add_birthday("1981-02-13")
self.assertTrue(before_current_date(family.marriage, individual.birthday))
self.assertFalse(before_current_date(individual.birthday, family.marriage))
if __name__ == '__main__':
main()
unittest.main(exit=False, verbosity=2)
|
a99fb376527ede447e50f2937903fd084eb1c36f | rohitprofessional/test | /CHAPTER 08/nested dict.py | 770 | 4.34375 | 4 | #---------NESTED DICTIONARY---------------
# Dictionary keys having another dictionary in them as values.
course = {
'python':{'duration':'3 months','fees':6500},
'php':{'duration':'2 months','fees':5000},
'java':{'duration':'3 months','fees':6500},
'machine learning':{'duration':'2 months','fees':7000},
'artificial intelligence':{'duration':'3 months','fees':8000}
}
print('------------------------------------')
print(course)
print('------------------------------------')
print(course['python'])
print('------------------------------------')
print(course['python']['fees']) # accessing nested dict. values
print('------------------------------------')
course['python']['fees'] = 8000
print('------------------------------------')
print(course) |
07a2725c3b70b1ec74a3624c972bc853d008fd63 | cragworks/python_sockets | /chattyc.py | 1,284 | 3.609375 | 4 | import tkinter as tk
from tkinter import *
import socket # Import socket module
import select
root = tk.Tk()
T = tk.Text(root, height=20, width = 50, state = NORMAL)
T.pack(side=TOP)
T2 = tk.Text(root, height=1, width=50)
T2.pack(side=LEFT)
T2.insert(tk.END, "")
def buttonclick():
task()
def buttonclient():
pass
def buttonserver():
pass
button1 = Button(root, text = "SEND", fg = "black", bg = "white", command = buttonclick)
button1.pack(side=RIGHT)
buttonc = Button(root, text = "client", fg = "black", bg = "white", command = buttonclient)
buttonc.pack(side=RIGHT)
buttons = Button(root, text = "server", fg = "black", bg = "white", command = buttonserver)
buttons.pack(side=RIGHT)
T.insert(tk.END, "\n I'm client")
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
def task():
text = T2.get("1.0", "2.0")
s.send(text.encode())
#print("HI SERVER")
def listen():
s.setblocking(0)
ready = select.select([s], [], [], 0.1)
if ready[0]:
T.insert(tk.END, "\nServer: "+str(s.recv(1024)))
root.after(1000, listen)
root.after(1000, listen)
tk.mainloop() |
d5e70c8eba43bb6c10ede574f9bb20416f421dc7 | redashu/pywinter2019 | /file_ops.py | 353 | 3.953125 | 4 | #!/usr/bin/python3
import sys
# to create a empty files
file_names=sys.argv[1:]
for i in file_names:
f=open(i,'w')
# f.write("hello world")
f.close()
# alternate way
for i in file_names:
with open(i,'w') as f:
f.write("hey python \n")
# like appending in a file
with open("aa.txt",'a') as f:
f.write("this line is appended \n")
|
e00e02ecd3f087eab977d0808f0fdb325839a8c1 | EddyATorresC/read_numbers | /image_server/Neural_Network_Testores_to_run.py | 4,172 | 3.515625 | 4 | import numpy as np
import scipy as sc
from matplotlib import pyplot as plt
import pandas as pd
import time
from IPython.display import clear_output
import cv2
re_train = True
#Funciones y clases
#Capa neuronal
class neural_layer():
def __init__(self, n_conn, n_neur):
self.b = np.random.rand(1,n_neur) * 2 -1
self.W = np.random.rand(n_conn,n_neur) * 2 -1
#Estructuración de la red
def create_neural_network(topology):
nn = []
for l, layer in enumerate(topology[:-1]):
nn.append(neural_layer(topology[l],topology[l+1]))
return nn
#Funciones de activación
def relu(x):
return np.maximum(0,x)
def sigmoid(x):
return (1/(1+ np.e ** (-x)))
def der_sigmoid(x):
return (sigmoid(x) * (1-sigmoid(x)))
def cost(predicted, real):
return np.mean((real-predicted)**2)
def der_cost(predicted,real):
return(predicted-real)
#función de entrenamiento o predicción
def train(neural_net, x_values, labels, lr = 0.001, train = True):
out = [(None, x_values)]
#Forward Pass
for l, layer in enumerate(neural_net):
z = out[-1][1] @ neural_net[l].W + neural_net[l].b
a = sigmoid(z)
out.append((z,a))
#print(l2_cost[0](out[-1][1],Y))
if train:
#Backward pass
deltas = []
for l in reversed(range(0, len(neural_net))):
z = out[l+1][0]
a = out[l+1][1]
if l == len(neural_net) - 1:
#Calcular delta de la ultima capa
deltas.insert(0,der_cost(a,labels)* der_sigmoid(a))
#print("not out of bounds")
else:
#Calcular delta respecto a capa previa
deltas.insert(0,deltas[0] @ _W.T * der_sigmoid(a))
_W = neural_net[l].W
#Gradeint Descent
neural_net[l].b = neural_net[l].b - np.mean(deltas[0], axis=0, keepdims = True)*lr
neural_net[l].W = neural_net[l].W - out[l][1].T @ deltas[0] * lr
return out[-1][1], neural_net
#Variables de inicio
T_1 = np.array([247, 249, 228, 231, 245, 129, 200, 243, 236, 242, 135, 156, 207, 237])
p = len(T_1)
topology = [p,512,128,512,128,64,2]
neural_n = create_neural_network(topology)
data = pd.read_csv("/home/eddy/Descargas/db.csv", delimiter = " ", dtype = np.float64).to_numpy()
data = data[:,0:266]
labels = data[:,256:266]
zero = np.array([1,0,0,0,0,0,0,0,0,0])
one = np.array([0,1,0,0,0,0,0,0,0,0])
zero_vector = []
one_vector = []
whole_vector = []
true_labels = []
for i in range(0, len(data)):
if(sum(labels[i] == zero) ==10):
zero_vector.append(data[i])
whole_vector.append(data[i])
true_labels.append([1,0])
elif(sum(labels[i] == one) ==10):
one_vector.append(data[i])
whole_vector.append(data[i])
true_labels.append([0,1])
testor_data = []
for i in range(0,len(whole_vector)):
for element in T_1:
testor_data.append([whole_vector[i][element]])
testor_data=np.reshape(np.asarray(testor_data),(len(whole_vector),14))
whole_vector=np.asarray(whole_vector)
# Proceso de entrenamiento
loss = []
train_values = testor_data[:161][:]
train_labels = true_labels[:161][:]
para_predecir = testor_data[162][:]
if(re_train):
for i in range(200):
pY,neural_n = train(neural_n, train_values, train_labels, lr = 0.001)
if i%25 == 0:
prediction = train(neural_n, para_predecir, train_labels, lr = 0.05, train = False)
print(prediction[0])
#Prorcentaje de aciertos
count = 0
for i in range(162,322):
para_predecir = testor_data[i][:]
prediction = train(neural_n, para_predecir, labels, lr = 0.01, train = False)
index = np.argmax(np.asarray(prediction[0]))
if(true_labels[i][index] == 1):
count = count +1
print(count/161)
#Predicción neta
plt.rcParams['image.cmap'] = 'gray'
im = cv2.imread("/home/eddy/Descargas/zero.png",1)
gray_img=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
gray_img = cv2.resize(gray_img,(16,16))
# plt.imshow(gray_img)
# plt.show()
first_try = (np.reshape(gray_img, (1,256))==255)*1
test_1=[]
for element in T_1:
test_1.append([first_try[0][element]])
test_1 = np.reshape(np.asarray(test_1),14)
print(test_1)
prediction = train(neural_n, test_1, labels, lr = 0.01, train = False)
print(prediction[0][0][0])
|
84cc6b69d6b4d278224c8bff3442df0f4d294723 | romeo-25-04/hellion_tools | /src/systems.py | 793 | 3.765625 | 4 | from src.orbit import Coordinates
import json
"""
name is what u see on the map
"""
class SpaceObject:
def __init__(self, name, coordinates=Coordinates()):
self.name = name
self.coordinates = coordinates
self.objects = {}
def add_object(self, obj):
self.objects[obj.name] = obj
def del_object_by_name(self, name):
if name in self.objects:
del self.objects[name]
def to_json(self):
return json.dumps(self,
default=lambda o: o.__dict__,
sort_keys=True, indent=2)
class System(SpaceObject):
DESCRIPTION = "Main Star"
class Planet(SpaceObject):
DESCRIPTION = "In orbit of a Star"
class Asteroid(SpaceObject):
DESCRIPTION = "In orbit of a Planet"
|
3f900fe35b7b4ce10df34976ffbbe1a15d58e3ac | AgamalARM/python | /ToggleGUI.py | 989 | 3.75 | 4 | ##################################################
### Author : Ahmed Gama ####
### Description : Toggle Function GUI ####
### ####
### Date : 6 Dec 2020 ####
### Version : v1 ####
##################################################
from tkinter import *
flag = 0
def TogFn() :
global flag
if flag == 0 :
print(0)
flag = 1
else :
print(1)
flag = 0
# create a tkinter window
root = Tk()
root.title("Toggle Function GUI")
# Open window having dimension 100x100
root.geometry('400x100')
# Create a Button
btn = Button(root, text = 'Toggle', bd = '5', command = TogFn)
btn1 = Button(root, text = 'EXIT', bd = '5', command = root.destroy)
# Set the position of button on the top of window.
btn.pack(side = 'top')
btn1.pack(side = 'top')
root.mainloop() |
7d380d70b43c850dc66a31568537c6956d90570d | Gabriel716/Term-1-End | /Python code/python calculator.py | 2,434 | 3.984375 | 4 | #Gabriel Harrison
#10/3/2018
#python password
#get user input and check for errors
def get_input(message):
var_value=input(message)
return var_value
def get_int_input(message):
var_value=input(message)
if var_value.isdigit():
var_value=int(var_value)
return var_value
else:
display_output("That was not a number")
get_in_input(message)
#solve for addition,subtraction,division,multiplication
def add(num1,num2):
sum_plus= num1 + num2
return sum_plus
def subtract(num1,num2):
difference= num1 - num2
return difference
def multiply(num1,num2):
product= num1 * num2
def divide(num1,num2):
if num !=0:
quotiant=num2/num1
return quotiant
else:
return 0
#remainder
def remainder(num1,num2):
if num1 !=0:
remainder=num2 % num1
return remainder
else:
return 0
#check math
def check_math(test_valuce, operator, num1, num2):
if operator == "+":
checked_value=num1 + num2
elif operator == "-":
checked_value= num1 - num2
elif operator == "%":
checked_value == num1 % num2
elif operator == "/":
checked_value= num1 / num2
elif operator == "*":
checked_value= num1 * num2
#display answer
def display_output(message):
print(message)
#main
def main():
num1 = get_int_input("Please enter a number.")
num2 = get_int_input("Please enter a number.")
operator = get_input("What is your operation? Enter + - * / or % only.")
if operator == "+":
test_value=add(num1,num2)
elif operator == "-":
test_value=subtract(num1,num2)
elif operator == "*":
test_value=multiply(num1,num2)
elif operator == "/":
test_value=divide(num1,num2)
elif operator == "%":
test_value=remainder(num1,num2)
else:
display_output("This is not one of the correct operators")
main()
if check_math(test_value, operator, num1, num2):
display_output("After a second check the correct answer is" +str(test_value)
else:
display_output("something in the calculation was wrong try it again")
main()
main()
|
8e104bf35367b6150fa4256e4468c841424d58b6 | wang55www/pythonStudy | /section8/8_3_7_3.py | 484 | 3.65625 | 4 | #coding:utf-8
class FruitShop(object):
"水果商店"
def __init__(self,fruits=[]):
self.fruits=fruits
def __getitem__(self,item):
return self.fruits[item]
def __str__(self):
return self.__doc__
def __call__(self): #对象可以看成一个函数来调用
print("FruitShop call")
if __name__ == "__main__":
shop = FruitShop(["apple","banana","pear"])
shop()
print(shop)
for item in shop:
print(item) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.