blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
7a5c8b5a95127944ea4364fc0ea35b6376eda6ec | Luiti/etl_utils | /etl_utils/itertools_utils.py | 2,010 | 3.5 | 4 | # -*- coding: utf-8 -*-
from .design_pattern import singleton
@singleton()
class ItertoolsUtilsClass(object):
def split_seqs_by_size(self, seqs1, size1, inspect=False):
"""
Combinations of split seqs by special size.
Breadth-first version, see examples at bottom.
Thanks @fuchaoqun for the recursion idea.
"""
if inspect:
print "[split_seqs_by_size]", seqs1, size1
seqs_len = len(seqs1)
assert seqs_len >= size1, "seqs1 len should greater or equal than size1."
assert size1 > 0, "size1 should greater than zero.."
final_result = []
def func(seqs2, size2, pre_result2=[]):
if inspect:
print
print "pre_result2", pre_result2
if size2 == 1:
return final_result.append(pre_result2 + [seqs2])
for idx3 in range(len(seqs2) - size2 + 1):
idx4 = idx3 + 1
if inspect:
print ["size2", size2, "idx4", idx4]
if inspect:
print "[loop seqs2]", seqs2[:idx4], seqs2[idx4:]
# generate a new result object
current_result = pre_result2 + [seqs2[:idx4]]
if len(current_result) == size1:
final_result.append(current_result)
else:
func(seqs2[idx3 + 1:], size2 - 1, current_result)
func(seqs1, size1)
if inspect:
print "\n" * 2
return final_result
ItertoolsUtils = ItertoolsUtilsClass()
"""
Iterator space analysis.
seqs_len, chunk_size, index_times
5, 5, 1
5, 4, 2
5, 3, 3
5, 2, 4
5, 1, 1
4, 4, 1
4, 3, 2
4, 2, 3
4, 4, 1
"""
|
1aa4ab328870d608ae4f67526ef7802ff7e0a59f | ShivaniAgarwal21/Python | /Conditionals and Booleans.py | 3,273 | 4.65625 | 5 | if True:
print('condition was true') # condition was true
if False:
print('condition was true') #Nothing happens .. it says PATH: command not found
#Comparisions:
#Equal: ==
#Not Equal !=
#Greater Than >
#Less Than <
#Greater or Equal >=
#Less or Equal <=
#Object Identity is
#Boolean operations:
#and
#or
#not
# to determine what python evaluates to be true or false: its easier to find what are false evaluation and then we know rest are true
# False Values:
#False
#None
#Zero of any numeric type
#Any empty sequence.For example, '',(),[]
#Any empty mapping. For example, {}
condition = False
if condition:
print('Evaluated to True')
else:
print('Evaluated to False') # Evaluated to False
condition = None
if condition:
print('Evaluated to True')
else:
print('Evaluated to False') # Evaluated to False
# zero will evaluted to false
condition = 0
if condition:
print('Evaluated to True')
else:
print('Evaluated to False') # Evaluated to False
condition = 5
if condition:
print('Evaluated to True')
else:
print('Evaluated to False') # Evaluated to True
condition = []
if condition:
print('Evaluated to True')
else:
print('Evaluated to False') # Evaluated to False
condition = {}
if condition:
print('Evaluated to True')
else:
print('Evaluated to False') # Evaluated to False
# rest all the conditions other than above will evaluate to be true. For Ex:
condition = 'Test'
if condition:
print('Evaluated to True')
else:
print('Evaluated to False') # Evaluated to True
#Comparisions:
language = 'Python'
if language == 'Python':
print('Language is Python') #condition was true Language is Python
else:
print('No Match') # Language is Python
language = 'Java'
if language == 'Python':
print('Language is Python') #condition was not true
else:
print('No Match') # No Match
if language == 'Python':
print('Language is Python') #condition was not true
elif language == 'Java':
print('Language is Java') #condition was true - Language is Java
else:
print('No Match') #condition was not true
#is when two objects are equal but not same in the memory
a = [1,2,3]
b = [1,2,3]
print(a == b) # True
print( a is b) # False
# to print the location of these two objects use id() function
print(id(a)) # 4317924888
print(id(b)) # 4317925320
print( a is b) # False
# if we would have define them differently then:
a = [1,2,3]
b = a
print(id(a)) # 4517043376
print(id(b)) # 4517043376
print( a is b) # True
# now both of them have same id's because now they are same objects in the memory
print(id(a) == id(b)) # True
#Boolean
#and
user = 'Admin'
logged_in = True
if user == 'Admin' and logged_in:
print('Admin Page') # Admin Page
else:
print('Bed Creds')
user = 'Admin'
logged_in = False
if user == 'Admin' and logged_in:
print('Admin Page') # condition not true
else:
print('Bed Creds') # Bed Creds
# or
user = 'Admin'
logged_in = False
if user == 'Admin' or logged_in:
print('Admin Page') # Admin Page
else:
print('Bed Creds')
#not
user = 'Admin'
logged_in = True
if not logged_in:
print('Please Log in')
else:
print('Welcome') # Welcome
user = 'Admin'
logged_in = False
if not logged_in:
print('Please Log in') # Please Log in
else:
print('Welcome')
|
9c0a343267722249bd81eb7a55760c9540c5c92f | fengzige1993/PythonData | /com/python/unittest_test1/test_search.py | 3,480 | 4.0625 | 4 | """
test_search 模块里有两个类 :TestSearch1 & TestSearch2
"""
import unittest
class Search:
#被测试方法
def search_func(self):
print("search")
return True
#继承unittest里的TestCase类
class TestSearch1(unittest.TestCase):
#在测试类TestSearch调用之前,定义一个 (加@classmethod装饰器)类方法:setUpClass,传参(cls)
@classmethod
def setUpClass(cls) -> None:
#实例化Search()类,后面就可以用self. 实例参数去调用
print("setup class_1")
cls.search = Search()
@classmethod
def tearDownClass(cls) -> None:
print("teardown class_1")
def setUp(self) -> None:
print("set up")
self.search = Search()
def tearDown(self) -> None:
print("tear down")
def test_search1(self):
print("test search1")
# search = Search()
assert True == self.search.search_func()
def test_search2(self):
print("test search2")
# search = Search()
assert True == self.search.search_func()
def test_search3(self):
print("test search3")
# search = Search()
assert True == self.search.search_func()
class TestSearch2(unittest.TestCase):
#在测试类TestSearch调用之前,定义一个 (加@classmethod装饰器)类方法:setUpClass,传参(cls)
@classmethod
def setUpClass(cls) -> None:
#实例化Search()类,后面就可以用self. 实例参数去调用
print("setup class_2")
cls.search = Search()
@classmethod
def tearDownClass(cls) -> None:
print("teardown class_2")
def setUp(self) -> None:
print("set up")
self.search = Search()
def tearDown(self) -> None:
print("tear down")
def test_search1(self):
print("test search1")
# search = Search()
assert True == self.search.search_func()
def test_search2(self):
print("test search2")
# search = Search()
assert True == self.search.search_func()
def test_search3(self):
print("test search3")
# search = Search()
assert True == self.search.search_func()
def test_equal(self):
print("断言相等")
self.assertEqual(1,1,"判断 1 == 1")
#命名规范case名字前面加 test 关键字表示一个测试case
def test_notequal(self):
print("断言表达式1==1是否相等")
# print("断言不相等")
# self.assertNotEqual(1,2,"判断 1 != 2")
#判断表达式是否相等
self.assertTrue(1==1,"verify 判断表达式是否相等")
if __name__ == '__main__':
#方法一:执行当前文件所有的unittest测试用例(执行当前测试页面所有测试类用例)
unittest.main()
#方法二:执行指定的测试用例,将要执行的测试用例添加到测试套件里面,批量执行
#创建一个测试套件,testsuite
suite = unittest.TestSuite()
suite.addTest(TestSearch1("test_search1"))
suite.addTest(TestSearch1("test_search2"))
unittest.TextTestRunner().run(suite)
#方法三:执行某个测试类,将测试类添加到测试套间里面,批量执行测试类
suite1 = unittest.TestLoader().loadTestsFromTestCase(TestSearch1)
suite2 = unittest.TestLoader().loadTestsFromTestCase(TestSearch2)
suite = unittest.TestSuite([suite1,suite2])
unittest.TextTestRunner(verbosity=2).run(suite) |
10eed68a00ae77681de10bff09f8ebf45efd87dd | adrianbeloqui/Python | /alphabet_rangoli.py | 1,287 | 3.53125 | 4 | LETTERS = ['a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'x', 'y', 'z'
]
def print_rangoli(size):
printed = list()
width = ((size * 2) - 1) + (size - 1) * 2
for i in range(size - 1, -1, -1):
result = "-".join(printed) + "-" + LETTERS[i] + "-" + "-".join(reversed(printed))
print(result.center(width, "-"))
printed.append(LETTERS[i])
printed.pop()
last_letter = printed.pop()
for i in range(1, size):
result = "-".join(printed) + "-" + last_letter + "-" + "-".join(reversed(printed))
print(result.center(width, "-"))
if printed:
last_letter = printed.pop()
import string
def sol2(N):
mid = N - 1
for i in range(N-1, -1, -1):
row = ['-'] * (2 * N - 1)
for j in range(N - i):
row[mid - j] = row[mid + j] = string.ascii_lowercase[j + i]
print '-'.join(row)
for i in range(0, N):
row = ['-'] * (2 * N - 1)
for j in range(0, N - i):
row[mid - j] = row[mid + j] = string.ascii_lowercase[j + i]
print '-'.join(row)
if __name__ == '__main__':
n = int(raw_input())
#print_rangoli(n)
sol2(n)
|
f88cb973550b169862745505c1dcc537eda2058e | ivankahnybediuk/python_12 | /homework.py | 6,989 | 4.03125 | 4 | import math
"""
Task 1
Method overloading.
Create a base class named Animal with a method called talk and then create two subclasses: Dog and Cat, and make their
own implementation of the method talk be different. For instance, Dog’s can be to print ‘woof woof’, while Cat’s can be
to print ‘meow’.
Also, create a simple generic function, which takes as input instance of a Cat or Dog classes and performs talk method
on input parameter.
"""
class Animal:
def __init__(self, name):
self.name = name
def talk(self):
raise NotImplementedError("Субклас должен имплементировать абстрактій метод!")
class Cat(Animal):
voice = "Meov"
def __init__(self, name):
super().__init__(name)
def talk(self):
print(self.name + " says " + self.voice)
class Dog(Animal):
voice = "Woof"
def __init__(self, name):
super().__init__(name)
def talk(self):
print(self.name + " says " + self.voice)
def changeVoice(animal):
animal.voice = input("Enter new animal voice ")
if __name__ == "__main__":
cat = Cat("Cat")
dog = Dog("Dog")
cat.talk()
changeVoice(cat)
cat.talk()
"""
Task 2
Library
Write a class structure that implements a library. Classes:
1) Library - name, books = [], authors = []
2) Book - name, year, author (author must be an instance of Author class)
3) Author - name, country, birthday, books = []
Library class
Methods:
- new_book(name: str, year: int, author: Author) - returns an instance of Book class and adds the book to the books
list for the current library.
- group_by_author(author: Author) - returns a list of all books grouped by the specified author
- group_by_year(year: int) - returns a list of all the books grouped by the specified year
All 3 classes must have a readable __repr__ and __str__ methods.
Also, the book class should have a class variable which holds the amount of all existing books
```
class Library:
pass
class Book:
pass
class Author:
pass
"""
class Library:
def __init__(self, name, books, authors):
self.name = name
self.books = books
self.authors = authors
def new_book(self, book):
original = False
if self.books:
for item in self.books:
if item == book:
item.amountBooks += 1
original = False
else:
original = True
else:
original = True
if original:
self.books.append(book)
self.authors.add(book.author.name)
book.author.books.append(book.name)
def __str__(self):
for book in self.books:
print(book)
def group_by_author(self, author):
for book in self.books:
if book.author.name == author:
print(book)
def group_by_year(self, year):
for book in self.books:
if book.year == year:
print(book)
class Book:
amountBooks = 1
def __init__(self, name, year, author):
self.name = name
self.year = int(year)
self.author = author
def __str__(self):
return f"Название: {self.name}\nГод: {self.year}\nАвтор: {self.author.name}\nКоличество: {self.amountBooks}\n" \
f"Книги этого автора: {self.author.books}\n\n"
def __eq__(self, other):
if isinstance(other, Book):
return self.name == other.name
class Author:
def __init__(self, name, country, birthday, books):
self.name = name
self.country = country
self.birthday = birthday
self.books = books
def __str__(self):
return f"Имя: {self.name}\nСтрана: {self.country}\nДень рождения: {self.birthday}\n\n" \
f"books: {self.books}"
if __name__ == "__main__":
rowling = Author("Джоан Роулинг", "Великобритания", "31 июля 1965г", [])
king = Author("Стивен Кинг", "США", "21 сентября 1947г", [])
orwell = Author("Джордж Оруел", "Великобритания", "25 июня 1903г", [])
firstLibrary = Library("FirstLibrary", [], set())
firstLibrary.new_book(Book("Гарри Поттер и философский камень", 1997, rowling))
firstLibrary.new_book(Book("Гарри Поттер и философский камень", 1997, rowling))
firstLibrary.new_book(Book("Гарри Поттер и тайная комната", 1998, rowling))
firstLibrary.new_book(Book("Стрелок", 1982, king))
firstLibrary.new_book(Book("Извлечение троих", 1987, king))
firstLibrary.new_book(Book("Скотный двор", 1945, orwell))
firstLibrary.new_book(Book("1984", 1949, orwell))
firstLibrary.new_book(Book("1984", 1949, orwell))
firstLibrary.new_book(Book("1984", 1949, orwell))
firstLibrary.new_book(Book("1984", 1949, orwell))
firstLibrary.__str__()
firstLibrary.group_by_author("Джордж Оруел")
firstLibrary.group_by_year(1997)
"""
Task 3
Fraction
Create a Fraction class, which will represent all basic arithmetic logic for fractions (+, -, /, *)
with appropriate checking and error handling
```
class Fraction:
pass
x = Fraction(1/2)
y = Fraction(1/4)
x + y == Fraction(3/4)
"""
class Fraction:
def __init__(self, number):
self.number = number.split('/')
self.num = int(self.number[0])
self.det = int(self.number[1])
def __add__(self, other):
if self.det == other.det:
num = self.num + other.num
det = self.det
else:
num = self.num * other.det + other.num * self.det
det = self.det * other.det
i = math.gcd(num, det)
num = num // i
det = det // i
return f'{num}/{det}'
def __sub__(self, other):
if self.det == other.det:
num = self.num - other.num
det = self.det
else:
num = self.num * other.det - other.num * self.det
det = self.det * other.det
i = math.gcd(num, det)
num = num // i
det = det // i
return f'{num}/{det}'
def __mul__(self, other):
num = self.num * other.num
det = self.det * other.det
i = math.gcd(num, det)
num = num // i
det = det // i
return f'{num}/{det}'
def __floordiv__(self, other):
num = self.num * other.det
det = self.det * other.num
i = math.gcd(num, det)
num = num // i
det = det // i
if det != 1:
return f'{num}/{det}'
else:
return num
def __str__(self):
return f"{self.num} / {self.det}"
if __name__ == "__main__":
x = Fraction('1/2')
y = Fraction('1/4')
print(x + y)
print(x - y)
print(x * y)
d = x // y
print(d)
|
8ef04c052caafdf1cfd966b7e69106b43cf07ca1 | Pranay2309/Test2_Corrections | /Question_29.py | 45 | 3.546875 | 4 | a=[0,1,2,3]
for a[-1] in a:
print(a[-1])
|
438b9d731e3a8ed1616b781d9f209d3a2841d98b | undergrowthlinear/learn_python | /test/practice/firstthirdpackage/content/mock_person.py | 282 | 3.734375 | 4 | # encoding=utf-8
class Person(object):
def __init__(self, name, age) -> None:
self.name = name
self.age = age
def __str__(self) -> str:
return super().__str__() + "\t" + self.name + "\t" + str(self.age)
person = Person('under', 18)
print(person)
|
e4821e2a3314c5da564404d8b52bf12529f54873 | wasi0013/Python-CodeBase | /ACM-Solution/SHAKTI.py | 89 | 3.6875 | 4 | for i in [0]*int(input()):print("Sorry Shaktiman" if int(input())%2 else "Thankyou Shaktiman")
|
a8095814987564b0d127c641b104c442cf99a899 | 1715974253/learned-codes | /28列表推导式.py | 233 | 4.03125 | 4 | # while循环
list1 = []
i = 0
while i < 10:
list1.append(i)
i += 1
print(list1)
# for循环
list2 = []
for j in range(0, 10):
list2.append(j)
print(list2)
# 列表推导式
list3 = [k for k in range(0, 10)]
print(list3)
|
d17c0e5c05816885cfb70c0ba81ca7e819a2d828 | ziuLGAP/2021.1-IBMEC | /exercicio3_20.py | 326 | 3.6875 | 4 | """
Exercicio 3-20
Luiz Guilherme de Andrade Pires
Engenharia de Computação
Matrícula: 202102623758
"""
def determina_primo(valor):
for num in range(2, valor + 1):
if valor == 2:
print(True)
elif valor % num == 0:
print(False)
print(True)
determina_primo(2) |
75d9efa0cea5169a63ca374bedf73b982d64681e | aquatiger/LaunchCode | /class point.py | 1,101 | 4.15625 | 4 | import math
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
""" Create a new point at the given coordinates. """
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return math.sqrt((self.x ** 2) + (self.y ** 2))
def reflect(self, v, w):
return (v, -w)
def slope(self, otherP):
try:
return (otherP.getY() / otherP.getX())
except:
return None
def move(self, z, a): #These are units of measurement, not coordinates
self.x += z
self.y += a
return (self.x, self.y)
def distanceFromPoint(self, otherP):
dx = (otherP.getX() - self.x)
dy = (otherP.getY() - self.y)
return math.sqrt(dy**2 + dx**2)
p = Point(3, 3)
q = Point(0, 7)
print(p.getX())
print(p.getY())
print(q.reflect(3, -5))
print(q.slope(q))
print(p.distanceFromPoint(q))
print(p.move(0, 7))
|
fdf6b4824cacca6e660fac184eff1fd67631619c | ccoo/Multiprocessing-and-Multithreading | /Multi-processing and Multi-threading in Python/Multi-threading/Locks and Sync Blocking/wait_blocking.py | 1,228 | 3.703125 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test module to implement wait blocking to address race condition, using
threading.Condition and threading.Event.
"""
__author__ = 'Ziang Lu'
import time
from threading import Condition, Event, Thread, current_thread
# Condition
product = None # 商品
condition = Condition()
def producer() -> None:
while True:
if condition.acquire():
global product
if not product:
# 生产商品
print('Producing something...')
product = 'anything'
condition.notify()
condition.wait()
time.sleep(2)
def consumer() -> None:
while True:
if condition.acquire():
global product
if product:
# 消耗商品
print('Consuming something...')
product = None
condition.notify()
condition.wait()
time.sleep(2)
prod_thread = Thread(target=producer)
cons_thread = Thread(target=consumer)
prod_thread.start()
cons_thread.start()
# Output:
# Producing something...
# Consuming something...
# Producing something...
# Consuming something...
# ...
|
260b3fe8dcd748de23b8bcbc72c1e10d49a2042b | changsman/changs | /practice/sort.py | 636 | 3.546875 | 4 | a=[1,10,2,6]
a.sort() ##오름차순 정렬
print(a)
a.sort(reverse=True) ##내림차순
print(a)
b=1423434 ###숫자를 문자열로 반환하여, 배열로 변환(str, list)
print(list(str(b))) ##해당 숫자를 배열로 변환
c= list(str(b))
print(c)
c.sort(reverse=True) #내림차순 하기(sort로 오름차순 정렬 후, reverse로 내림차순)
print(c)
d="".join(c) #join으로 배열합치기
print(d)
#e=d(reverse=True)
def solution(n):
ls = list(str(n))
ls.sort(reverse = True)
return int("".join(ls))
#####연습#####
number=(int(input('숫자를 입력하시오\n')))
print(solution(number))
|
2570ba4dfd2120ef14ebb56df60c035dd9053e50 | hermespara/internship1 | /check_for_RNA.py | 526 | 3.53125 | 4 | #!/usr/bin/python3.6
import csv
all_data_path = "/home/hermesparaqindes/Bureau/internship1/complete.txt"
all_data = open(all_data_path, "r")
all_data_csv = csv.reader(all_data, delimiter='\t')
for row in all_data_csv:
analysis = row[4]
blood = row[2]
if ' RNA' in analysis and 'lymphocytes' in row[3] or ' Skin' in blood or ' Brain' in blood:
#print(row)
print(row[0], '\t', row[1], '\t', row[2], '\t', row[3], '\t' ,row[4], '\t' ,row[5], '\t' ,row[6], '\t' ,row[7], '\t' , row[8], '\t', row[9])
|
b18b2c8ad2353293a222726d7070ff9e0f8919ec | key70/mlTest | /lambdaTest.py | 286 | 3.765625 | 4 | # def add(a,b):
# r = a + b
# return r
#연습)위의 함수를 람다식으로 만들어 봅니다.
add = lambda a,b: a+b
print(add(5,7))
# def max(a,b):
# r = a
# if b > r:
# r = b
# return r
# max = lambda a,b : a if a>b else b
#
# print(max(5,30)) |
e3f0e32a1a40862af5e0e66eb205a164db7f7626 | vsriram1987/python-training | /src/setsorter.py | 988 | 4.0625 | 4 | '''
Created on 06-Jan-2019
@author: vsrir
'''
import string
from _sre import ascii_tolower
def checkalph(stringval):
varset = ""
#list will convert set to list
#set will take unique values in map
#map has a lambda to convert all characters to lower case
#the list passed to the map is a filter
#filter has a lambda to only take characters and ignore everything else from the input string
varlist = list(set(map(lambda str:str.lower(),filter(lambda a:a in string.ascii_lowercase + string.ascii_uppercase,stringval))))
#then sort the alphabets and convert to string
varlist.sort()
varset = "".join(varlist)
alphset = string.ascii_lowercase
#now do the comparison and return true or false
print(varset)
print(alphset)
if varset == alphset.lower():
return True
return False
print(checkalph("the quicKest #superquick Brown coloured fox jumped over the lazy dogs yet did not Succeed!!!"))
|
77ebc84432d0bc8f911562e79a80d50b43fea7c2 | pranavkvc/Hand-Cricket-Game | /Handcricket/Handcricket.py | 19,072 | 4.125 | 4 | import time,random
user_score=0
computer_score=0
overs=0
balls=1
user_duck=True
computer_duck=True
user_out=False
computer_out=False
toss=['1','2']
bat_or_bowl=["Bat","Bowl"]
print("Toss time!")
choice=input("Head/Tails?\n1.Heads\n2.Tails\nEnter your choice: ")
if choice=='1' or choice=='2':
who=random.choice(toss)
#User won the toss!
if who==choice:
print("Hurray you won the toss!")
option=input("What do you wish to do?\n1.Bat\n2.Bowl\nEnter the option: ")
if option=='1' or option=='2':
#User choses to bat
if option=='1':
print("You chose to bat!")
print("Let's begin!")
user_input=int(input("Enter a number between 1-6:"))
computer_input=random.randint(1,6)
if user_input==computer_input:
computer_out=True
break
if user_input!=computer_input:
user_score+=user_input
if user_input<=0 or user_input>6:
print("Invalid input!")
user_score=0
balls=0
else:
print()
print("Your input is: ",user_input," and computer input is: ",computer_input)
print()
print("Current score:",user_score)
print("Overs:",overs,".",balls)
print()
print()
while user_input!=computer_input:
user_duck=False
user_input=int(input("Enter a number between 1-6:"))
if user_input<=0 or user_input>6:
print("Invalid input!")
continue
computer_input=random.randint(1,6)
user_score+=user_input
balls+=1
if balls%6==0:
overs+=1
if balls==6:
balls=0
print()
print("Your input is",user_input," and computer input is ",computer_input)
print()
print("Current score:",user_score)
print("Overs:",overs,".",balls)
print()
print("Out!!!")
if user_duck:
user_score=0
if user_score==0:
print("Duck!!!")
else:
if overs<=1:
print("You scored ",user_score," from ",overs," over and",balls," balls.")
else:
print("You scored ",user_score," from ",overs," overs and",balls," balls.")
#User's turn to bowl
balls=1
overs=0
print("Now your turn to bowl\n\nNever allow the opponent to cross your score\nAll the best!")
user_input=int(input("Enter a number between 1-6:"))
computer_input=random.randint(1,6)
computer_score+=computer_input
if computer_score!=user_score:
computer_duck=False
else:
computer_score=0
if user_input<=0 or user_input>6:
print("Invalid input!")
computer_score=0
balls=0
else:
print("Your input is: ",user_input," and computer input is: ",computer_input)
print("Current score:",computer_score)
print("Overs:",overs,".",balls)
while computer_score<user_score:
user_input=int(input("Enter a number between 1-6:"))
if user_input<=0 or user_input>6:
print("Invalid input!")
continue
computer_input=random.randint(1,6)
if user_input==computer_input:
break
computer_score+=computer_input
balls+=1
if balls%6==0:
overs+=1
if balls==6:
balls=0
print()
print("Your input is",user_input," and computer input is ",computer_input)
print("Current score:",computer_score)
print("Overs:",overs,".",balls)
print()
if computer_out:
print("Out!!!")
if computer_duck:
computer_score=0
if overs<=0:
print("Computer scored ",computer_score," from ",overs," over and",balls+1," balls")
else:
print("Computer scored ",computer_score," from ",overs," overs and",balls+1," balls")
if user_score>computer_score:
print("You won!")
print("Scores:\nYou:",user_score,"\nComputer:",computer_score)
else:
print("Computer won!!!\nBetter luck next time")
print("Scores:\nComputer:",computer_score,"\nYou:",user_score)
#User choses to bowl
else:
print("You chose to bowl!")
user_input=int(input("Enter a number between 1-6:"))
computer_input=random.randint(1,6)
computer_score+=computer_input
if computer_input!=user_input:
computer_duck=False
else:
computer_score=0
if user_input<=0 or user_input>6:
print("Invalid input!")
computer_score=0
balls=0
else:
print()
print("Your input is: ",user_input," and computer input is: ",computer_input)
print("Current score:",computer_score)
print("Overs:",overs,".",balls)
print()
while computer_input!=user_input:
user_input=int(input("Enter a number between 1-6:"))
if user_input<=0 or user_input>6:
print("Invalid input!")
continue
computer_input=random.randint(1,6)
if computer_input==user_input:
break
computer_score+=computer_input
balls+=1
if balls%6==0:
overs+=1
if balls==6:
balls=0
print()
print("Your input is",user_input," and computer input is ",computer_input)
print("Current score:",computer_score)
print("Overs:",overs,".",balls)
print()
print("Out!!!")
if computer_duck:
computer_score=0
if computer_duck:
print("Duck!!!")
else:
if overs<=0:
print("Computer scored ",computer_score," from ",overs," over and",balls+1," balls")
else:
print("Computer scored ",computer_score," from ",overs," overs and",balls+1," balls")
#User's turn to bat
overs=0
balls=1
print("Now it's your turn to bat\nTry to defeat the oppponent\nAll the best!")
print("Let's begin!")
user_input=int(input("Enter a number between 1-6:"))
computer_input=random.randint(1,6)
if user_input!=computer_input:
user_score+=user_input
if user_input<=0 or user_input>6:
print("Invalid input!")
user_score=0
balls=0
else:
print()
print("Your input is: ",user_input," and computer input is: ",computer_input)
print()
print("Current score:",user_score)
print("Overs:",overs,".",balls)
print()
print()
while user_score<computer_score:
user_duck=False
user_input=int(input("Enter a number between 1-6:"))
if user_input<=0 or user_input>6:
print("Invalid input!")
continue
computer_input=random.randint(1,6)
if user_input==computer_input:
user_out=True
break
user_score+=user_input
balls+=1
if balls%6==0:
overs+=1
if balls==6:
balls=0
print()
print("Your input is",user_input," and computer input is ",computer_input)
print()
print("Current score:",user_score)
print("Overs:",overs,".",balls)
print()
if user_out:
print("Out!!!")
if user_duck:
user_score=0
if overs<=0:
print("You scored ",user_score," from ",overs," over and",balls+1," balls")
else:
print("You scored ",user_score," from ",overs," overs and",balls+1," balls")
if user_score>computer_score:
print("You won!")
print("Scores:\nYou:",user_score,"\nComputer:",computer_score)
elif computer_score>user_score:
print("Computer won!!!\nBetter luck next time")
print("Scores:\nComputer:",computer_score,"\nYou:",user_score)
else:
print("Tie!!!")
print("No one gives up!")
else:
print("Invalid option begin given!")
#Computer won the toss!
else:
computer_option=random.choice(bat_or_bowl)
print("Bad luck! computer won the toss and chose to ",computer_option)
print("Let the battle begin!!!")
#If computer choses batting
if computer_option=="Bat":
print("Computer bats!")
user_input=int(input("Enter a number between 1-6:"))
computer_input=random.randint(1,6)
computer_score+=computer_input
if computer_input!=user_input:
computer_duck=False
else:
computer_score=0
if user_input<=0 or user_input>6:
print("Invalid input!")
computer_score=0
balls=0
else:
print()
print("Your input is: ",user_input," and computer input is: ",computer_input)
print("Current score:",computer_score)
print("Overs:",overs,".",balls)
print()
while computer_input!=user_input:
user_input=int(input("Enter a number between 1-6:"))
if user_input<=0 or user_input>6:
print("Invalid input!")
continue
computer_input=random.randint(1,6)
if computer_input==user_input:
break
computer_score+=computer_input
balls+=1
if balls%6==0:
overs+=1
if balls==6:
balls=0
print()
print("Your input is",user_input," and computer input is ",computer_input)
print("Current score:",computer_score)
print("Overs:",overs,".",balls)
print()
print("Out!!!")
if computer_duck:
print("Duck!!!")
computer_score=0
else:
if overs<=0:
print("Computer scored ",computer_score," from ",overs," over and",balls+1," balls")
else:
print("Computer scored ",computer_score," from ",overs," overs and",balls+1," balls")
#Computer's turn to bowl
overs=0
balls=1
print("Computer bowls!")
user_input=int(input("Enter a number between 1-6:"))
computer_input=random.randint(1,6)
if user_input!=computer_input:
user_score+=user_input
if user_input<=0 or user_input>6:
print("Invalid input!")
user_score=0
balls=0
else:
print()
print("Your input is: ",user_input," and computer input is: ",computer_input)
print()
print("Current score:",user_score)
print("Overs:",overs,".",balls)
print()
print()
while user_score<=computer_score:
user_duck=False
user_input=int(input("Enter a number between 1-6:"))
if user_input<=0 or user_input>6:
print("Invalid input!")
continue
computer_input=random.randint(1,6)
if user_input==computer_input:
user_out=True
break
user_score+=user_input
balls+=1
if balls%6==0:
overs+=1
if balls==6:
balls=0
print()
print("Your input is",user_input," and computer input is ",computer_input)
print()
print("Current score:",user_score)
print("Overs:",overs,".",balls)
print()
if user_out:
print("Out!!!")
if user_duck:
user_score=0
if overs<=0:
print("You scored ",user_score," from ",overs," over and",balls+1," balls")
else:
print("You scored ",user_score," from ",overs," overs and",balls+1," balls")
#Announcing the winner
if user_score>computer_score:
print("You won!")
print("Scores:\nYou:",user_score,"\nComputer:",computer_score)
elif computer_score>user_score:
print("Computer won!!!\nBetter luck next time")
print("Scores:\nComputer:",computer_score,"\nYou:",user_score)
else:
print("Tie!!!")
print("No one gives up!")
#If computer choses to bowl
else:
print("Computer bowls!")
user_input=int(input("Enter a number between 1-6:"))
computer_input=random.randint(1,6)
if user_input!=computer_input:
user_score+=user_input
if user_input<=0 or user_input>6:
print("Invalid input!")
user_score=0
balls=0
else:
print()
print("Your input is: ",user_input," and computer input is: ",computer_input)
print()
print("Current score:",user_score)
print("Overs:",overs,".",balls)
print()
print()
while user_input!=computer_input:
user_duck=False
user_input=int(input("Enter a number between 1-6:"))
if user_input<=0 or user_input>6:
print("Invalid input!")
continue
computer_input=random.randint(1,6)
if user_input==computer_input:
user_out=True
break
user_score+=user_input
balls+=1
if balls%6==0:
overs+=1
if balls==6:
balls=0
print()
print("Your input is",user_input," and computer input is ",computer_input)
print()
print("Current score:",user_score)
print("Overs:",overs,".",balls)
print()
if user_out:
print("Out!!!")
if user_duck:
user_score=0
if overs<=0:
print("You scored ",user_score," from ",overs," over and",balls+1," balls")
else:
print("You scored ",user_score," from ",overs," overs and",balls+1," balls")
#Computer's turn to bat
overs=0
balls=1
print("Computer bats!")
user_input=int(input("Enter a number between 1-6:"))
computer_input=random.randint(1,6)
computer_score+=computer_input
if computer_input!=user_input:
computer_duck=False
else:
computer_score=0
if user_input<=0 or user_input>6:
print("Invalid input!")
computer_score=0
balls=0
else:
print()
print("Your input is: ",user_input," and computer input is: ",computer_input)
print("Current score:",computer_score)
print("Overs:",overs,".",balls)
print()
while computer_score<=user_score:
computer_duck=False
user_input=int(input("Enter a number between 1-6:"))
if user_input<=0 or user_input>6:
print("Invalid input!")
continue
computer_input=random.randint(1,6)
if computer_input==user_input:
computer_out=True
break
computer_score+=computer_input
balls+=1
if balls%6==0:
overs+=1
if balls==6:
balls=0
print()
print("Your input is",user_input," and computer input is ",computer_input)
print("Current score:",computer_score)
print("Overs:",overs,".",balls)
print()
if computer_out:
print("Out!!!")
if computer_duck:
print("Duck!!!")
computer_score=0
else:
if overs<=0:
print("Computer scored ",computer_score," from ",overs," over and",balls+1," balls")
else:
print("Computer scored ",computer_score," from ",overs," overs and",balls+1," balls")
#Announcing the winner
if user_score>computer_score:
print("You won!")
print("Scores:\nYou:",user_score,"\nComputer:",computer_score)
elif computer_score>user_score:
print("Computer won!!!\nBetter luck next time")
print("Scores:\nComputer:",computer_score,"\nYou:",user_score)
else:
print("Tie!!!")
print("No one gives up!")
else:
print("Invalid option given!")
|
5ed1168c6daa809a0d2e8373f1dab54ae662f419 | Brunorodrigoss/pytest_structure | /tests/test_math.py | 2,107 | 3.96875 | 4 | import pytest
"""
This module contains basic unit tests for math operations.
Their purpose is to show how to use the pytest framework by example.
"""
# ------------------------------------------------------------------------
# A most basic test funcion
# ------------------------------------------------------------------------
@pytest.mark.math
def test_one_plus_one():
assert 1 + 1 == 2
# ------------------------------------------------------------------------
# A test function to show assertion instrospection
# ------------------------------------------------------------------------
@pytest.mark.math
def test_one_plus_two():
a = 1
b = 2
c = 3
assert a + b == c
# ------------------------------------------------------------------------
# A test function that verifies an exception
# ------------------------------------------------------------------------
@pytest.mark.math
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError) as e:
num = 1 / 0
assert 'division by zero' in str(e.value)
# ------------------------------------------------------------------------
# Parametrized Tests Cases
# Multiplication test ideas
# - two positive integers
# - indentity: multiplying any number by 1
# - zero: multiplying any number by 0
# - positive by a negative
# - negative by a negative
# - multiplying floats
@pytest.mark.math
def test_multiply_two_positive_ints():
assert 2 * 3 == 6
@pytest.mark.math
def test_multiply_identity():
assert 1 * 99 == 99
@pytest.mark.math
def test_multiply_zero():
assert 0 * 100 == 0
# DRY Principle: Don't repeat Yoursealf!
# ------------------------------------------------------------------------
products = [
(2, 3, 6), # positive numbers
(1, 99, 99), # identity
(0, 99, 0), # zero
(3, -4, -12), # positive by negative
(-5, -5, 25), # negative by negative
(2.5, 6.7, 16.75), # floats
]
@pytest.mark.math
@pytest.mark.parametrize('a, b, product', products)
def test_multiplication(a, b, product):
assert a * b == product
|
692d6a97de0ca6363085c0466c2338aceee9c3b4 | FVerg/Simple-Python-Exercises | /04_Math_Operators/04_MathOperators.py | 968 | 4.625 | 5 | # In this lecture, we'll cover the usage of math operators
# First of all, let's see how some different operators used together work
result = 20-10/5*3**2
print (result)
# Python will execute the operations in this order:
# 1. Exponential (**): 2**3 equals to 2^3 = 2*2*2 = 8
# 2. Division and multiplication (On the same level: what comes first from left to right is executed first)
# 3. Addition and subtractions (On the same level: what comes first from left to right is executed first)
# So, this line of code will do:
# 3**2 = 9
# 10/5 = 2
# 20 - (2*9) = 20-18 = 2.0
# The result will be 2.0 (a float) and not just 2 (an int) because of the presence
# of the division (10/5). In Python 3 the division always outputs a float
# Obviously the result changes if we use the brackets:
result = (20-10)/5*3**2
print (result)
# This way, the operations in the brackets gets executed first, so, in order:
# 20 - 10 = 10
# 10 / 5 = 2.0
# 3**2 = 9
# 2.0 * 9 = 18.0
|
75c07465135f9f00dd04c6d6aec444e709318e3a | huangyingw/submissions | /288/288.unique-word-abbreviation.233520184.Accepted.leetcode.py | 612 | 3.59375 | 4 | from collections import defaultdict
class ValidWordAbbr(object):
def __init__(self, dictionary):
self.dictionary = set(dictionary)
self.freq = defaultdict(int)
for word in self.dictionary:
self.freq[self.abbreviate(word)] += 1
def isUnique(self, word):
abbr = self.abbreviate(word)
if word in self.dictionary:
return self.freq[abbr] == 1
else:
return abbr not in self.freq
def abbreviate(self, word):
n = len(word)
if n < 3:
return word
return word[0] + str(n - 2) + word[-1]
|
c2257328d46536e5f51db962e03b97e82c1fd89c | RaguTeja/LinkedList-in-python | /LL.py | 4,576 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 18:43:35 2021
@author: dell
"""
class Node:
def __init__(self,data,next):
self.data=data
self.next=next
class LinkedList:
def __init__(self):
self.head=None
def length_ll(self):
count=0
if self.head==None:
return 0
itr=self.head
while itr:
count=count+1
itr=itr.next
return count
def insert_at_beginning(self,data):
node=Node(data,self.head)
self.head=node
def insert_at_end(self,data):
if self.head==None:
self.insert_at_beginning(data)
else:
itr=self.head
while itr.next:
itr=itr.next
node=Node(data,None)
itr.next=node
def insert_at_anypos(self,data,pos):
if self.head==None and pos>1:
raise 'INVALID INSERTION'
elif pos==1:
return self.insert_at_beginning(data)
elif pos==self.length_ll()+1:
return self.insert_at_end(data)
elif pos>self.length_ll()>+1:
raise 'INVALID INSERTION'
else:
itr=self.head
count=1
while itr:
count=count+1
if count==pos:
itr.next=Node(data,itr.next)
return
itr=itr.next
def remove_at(self,pos):
if self.head==None and pos>=1:
raise 'Invalid removal'
elif pos==self.length_ll()+1:
raise 'Invalid removal'
else:
if pos==1:
self.head=self.head.next
return
count=1
itr=self.head
while itr:
count=count+1
if count==pos:
itr.next=itr.next.next
return
itr=itr.next
def print_ll(self):
if self.head==None:
print('No elements are there in the linked list')
return
itr=self.head
while itr:
print(itr.data,end=" ")
itr=itr.next
def insert_values(self,lst):
for i in lst:
ll.insert_at_end(i)
def insert_after_value(self,data_after,data_to_insert):
if self.head==None:
raise 'INVALID OPERATION'
itr=self.head
flag=0
while itr:
if itr.data==data_after:
node=Node(data_to_insert,itr.next)
itr.next=node
flag=1
return
itr=itr.next
if flag==0:
raise "Data doesn't exist"
def remove_by_value(self,data):
if self.head==None:
raise 'INVALID OPERATION'
if self.length_ll()==1 and self.head.data==data:
self.head=None
return
elif self.head.data==data:
self.head=self.head.next
return
itr=self.head
flag=0
while itr.next:
if itr.next.data==data:
itr.next=itr.next.next
flag=1
return
itr=itr.next
if flag==0:
raise 'INVALiD DATA'
ll=LinkedList()
ll.insert_values(['banana','apple','strawberry'])
ll.print_ll()
print()
ll.insert_at_anypos(12, 1)
ll.insert_at_anypos(11, 2)
ll.insert_at_anypos(13, 1)
ll.insert_at_anypos('blueberry', 5)
ll.print_ll()
print()
ll.insert_at_anypos(18, 4)
ll.insert_at_anypos(20, 3)
ll.print_ll()
print()
ll.remove_at(5)
ll.print_ll()
print()
ll.insert_after_value('banana','grapes')
ll.print_ll()
print()
ll.insert_after_value('strawberry','raghu')
ll.print_ll()
print()
ll.insert_after_value(13,14)
ll.print_ll()
print()
ll.remove_by_value(13)
ll.print_ll()
print()
'''
ll.insert_at_beginning(5)
ll.insert_at_beginning(10)
ll.insert_at_end(20)
print(ll.length_ll())
ll.insert_at_anypos(12, 2)
ll.insert_at_beginning(16)
ll.print_ll()
'''
|
db71670a929003b93ba7330682847cf65a7280f2 | gabriellaec/desoft-analise-exercicios | /backup/user_005/ch128_2020_04_01_16_44_34_377244.py | 332 | 3.828125 | 4 | x = input('Está se movendo?:')
if x == 's':
y = input('Deveria se mover?:')
if y == 'n':
print ('Silver tape')
if y == 's':
print ('Sem problemas!')
if x == 'n':
w = input ('Deveria estar parado?:')
if w == 'n':
print ('WD-40')
if w == 's':
print ('Sem problemas!')
|
f783eb67fce72502d836672bf4d9d9c8c8b8568d | shuowenwei/LeetCodePython | /Easy/LC896MonotonicArray.py | 999 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/monotonic-array/
"""
class Solution(object):
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
increasing = True
decreasing = True
for i in range(len(A)-1):
if A[i] > A[i+1]:
increasing = False
if A[i] < A[i+1]:
decreasing = False
return increasing or decreasing
"""
if len(A) <= 2:
return True
increaseFlag = False
decreaseFlag = False
for i in range(1, len(A)):
# as long as there's one pair incresing
if A[i] > A[i-1]:
increaseFlag = True
# as long as there's oen pair decreasing
if A[i] < A[i-1]:
decreaseFlag = True
if increaseFlag and decreaseFlag:
return False
return True
""" |
4376d952d29de5a0c2388eb8bd50a98b5613431f | manimanis/LeetCode | /May2021/sol_06.py | 1,674 | 3.859375 | 4 | """Convert Sorted List to Binary Search Tree.
https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/598/week-1-may-1st-may-7th/3733/
"""
from common.nodelist import TreeNode, ListNode
from common.testcases import make_tests
test_cases = [
(([-10, -3, 0, 5, 9],), [0, -3, 9, -10, None, 5]),
(([],), []),
(([0],), [0]),
(([1, 3], ), [3, 1]),
(([1, 2, 3, 4, 5, 6, 7],), [4, 2, 6, 1, 3, 5, 7])
]
class Solution:
@staticmethod
def list_size(start, end=None):
if start is None or start == end:
return 0
l = 1
p = start
while p.next != end:
l += 1
p = p.next
return l
@staticmethod
def get_center(start, end=None):
if start is None or start == end:
return None
mid = Solution.list_size(start, end) // 2
p = start
while mid > 0 and p.next != end:
p = p.next
mid -= 1
return p
def sortedListToBST(self, head: ListNode, right: ListNode = None) -> TreeNode:
c = Solution.get_center(head, right)
if c is not None:
#print(c.val)
node = TreeNode(c.val)
#print()
node.left = self.sortedListToBST(head, c)
node.right = self.sortedListToBST(c.next, right)
return node
return None
if __name__ == '__main__':
def prepare_data(arr):
return (ListNode.build(arr),)
def prepare_res(res):
if res is not None:
return res.toList()
return []
make_tests(test_cases, Solution, 'sortedListToBST',
prepare_data, prepare_res)
|
e69bca8b1c4602a265bf41d13af8bbb8a320604f | Carina6/algorithms | /common_algorithms/move_left_m.py | 504 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-03-28 21:41
# @Author : hlliu
from random import choice
# 左移m位
def move(arr, m):
n = len(arr)
m = m % n
return arr[m:]+arr[:m]
def rand(arr, n):
res = []
for i in range(n):
index = choice(range(len(arr) - i))
res.append(arr[index])
arr[index] = arr[len(arr) - i - 1]
return res
if __name__ == '__main__':
# print(move([1,2,3,4,5,6],1))
print(rand([1,2,3,4,5,6],4))
|
f33cca90ce99a1a47530eea8edff37c7733853cf | JonasSatkauskas/codewars | /list_filtering.py | 379 | 4.1875 | 4 | '''In this kata you will create a function
that takes a list of non-negative integers and strings
and returns a new list with the strings filtered out.'''
def filter_list(l):
final_list = []
for element in l:
if type(element)==int:
final_list.append(element)
else:
pass
return final_list
print(filter_list([1,'l', True, '2', 'b', 2])) |
7715b2009385ca0002b5d859adda39453b311f4a | Amandapoor/cmpt120poor | /IntroProgramming-Labs/evens.py | 155 | 4.125 | 4 | # a simple loop
# a program that prints out all the even integers from 2 through 20
def main():
for i in range(2, 21, 2):
print(i)
main()
|
e8f121bb85df42d7b71c5e277dbcf344256296e4 | adithirgis/DeepLearningFromFirstPrinciples | /Chap1-LogisticRegressionAsNeuralNetwork/DLfunctions1.py | 2,980 | 3.90625 | 4 | # -*- coding: utf-8 -*-
##############################################################################################
#
# Created by: Tinniam V Ganesh
# Date : 4 Jan 2018
# File: DLfunctions1.py
#
##############################################################################################
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
# Define the sigmoid function
def sigmoid(z):
a=1/(1+np.exp(-z))
return a
# Initialize weights and biases
def initialize(dim):
w = np.zeros(dim).reshape(dim,1)
b = 0
return w
# Compute the loss
# Inputs: numTraining
# : Y
# : A
# Ouputs : loss
def computeLoss(numTraining,Y,A):
loss=-1/numTraining *np.sum(Y*np.log(A) + (1-Y)*(np.log(1-A)))
return(loss)
# Execute the forward propagation
# Inputs: w
# : b
# : X
# : Y
# Ouputs : gradients, loss (dict)
def forwardPropagation(w,b,X,Y):
# Compute Z
Z=np.dot(w.T,X)+b
# Determine the number of training samples
numTraining=float(len(X))
# Compute the output of the sigmoid activation function
A=sigmoid(Z)
#Compute the loss
loss = computeLoss(numTraining,Y,A)
# Compute the gradients dZ, dw and db
dZ=A-Y
dw=1/numTraining*np.dot(X,dZ.T)
db=1/numTraining*np.sum(dZ)
# Return the results as a dictionary
gradients = {"dw": dw,
"db": db}
loss = np.squeeze(loss)
return gradients,loss
# Compute Gradient Descent
# Inputs: w
# : b
# : X
# : Y
# : numIerations
# : learningRate
# Ouputs : params, grads, losses,idx
def gradientDescent(w, b, X, Y, numIerations, learningRate):
losses=[]
idx =[]
# Iterate
for i in range(numIerations):
gradients,loss=forwardPropagation(w,b,X,Y)
#Get the derivates
dw = gradients["dw"]
db = gradients["db"]
w = w-learningRate*dw
b = b-learningRate*db
# Store the loss
if i % 100 == 0:
idx.append(i)
losses.append(loss)
# Set params and grads
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, losses,idx
# Predict the output for a training set
# Inputs: w
# : b
# : X
# Ouputs : yPredicted
def predict(w,b,X):
size=X.shape[1]
yPredicted=np.zeros((1,size))
Z=np.dot(w.T,X)
# Compute the sigmoid
A=sigmoid(Z)
for i in range(A.shape[1]):
#If the value is > 0.5 then set as 1
if(A[0][i] > 0.5):
yPredicted[0][i]=1
else:
# Else set as 0
yPredicted[0][i]=0
return yPredicted
#Normalize the data
# Predict the output for a training set
# Inputs: x
# Ouputs : x (normalized)
def normalize(x):
x_norm = None
x_norm = np.linalg.norm(x,axis=1,keepdims=True)
x= x/x_norm
return x
|
478f9b8fc9e7f088f35c1d0b1fb45fb6ae90889b | cankutergen/Other | /totalFruit.py | 851 | 3.546875 | 4 | class Solution:
def totalFruit(self, tree: List[int]) -> int:
if tree is None or len(tree) is 0:
return 0
last_fruit = -1
second_last_fruit = -1
last_fruit_count = 0
current_max = 0
global_max = 0
for fruit in tree:
if fruit == last_fruit or fruit == second_last_fruit:
current_max += 1
else:
current_max = last_fruit_count + 1
if fruit == last_fruit:
last_fruit_count += 1
else:
last_fruit_count = 1
second_last_fruit = last_fruit
last_fruit = fruit
global_max = max(global_max, current_max)
return global_max
|
8eb29d6de6bd1ae276c566b99a22073d7094bbba | jsweeney3937/PRG105 | /Nested_If_Statements.py | 1,464 | 3.96875 | 4 | # Sweeney
# Assignment: Mobile Service Provider
userPackage = input("What package do you use, package A,B, or C? ").upper()
minutesUsed = int(input("How many minutes did you use? "))
price = float
if userPackage == "A" and minutesUsed <= 450:
price = 39.99
print("With package", userPackage, "and ", minutesUsed, " minutes used your total comes out to $", format(price, ',.2f'))
else:
if userPackage == "A" and minutesUsed > 450:
price = 39.99 + ((minutesUsed % 450) * .45)
print("With package", userPackage, "and ", minutesUsed, " minutes used your total comes out to $", format(price, ',.2f'))
else:
if userPackage == "B" and minutesUsed <= 900:
price = 59.99
print("With package", userPackage, "and ", minutesUsed, " minutes used your total comes out to $", format(price, ',.2f'))
else:
if userPackage == "B" and minutesUsed > 900:
price = 59.99 + ((minutesUsed % 900) * .4)
print("With package", userPackage, "and ", minutesUsed, " minutes used your total comes out to $", format(price, ',.2f'))
else:
if userPackage == "C":
price = 69.99
print("With package", userPackage, "and ", minutesUsed, " minutes used your total comes out to $", format(price, ',.2f'))
else:
print("You did not enter a valid package")
|
2050592709109f1bb341ce56c1c503632998c983 | LucasReboucas/lancamento_dados_simulacao | /simulacao.py | 3,335 | 3.65625 | 4 | ########################################################################################################
# Este arquivo simula "LANCAMENTOS" lancamentos de "DADOS" dados com "LADOS" lados e mostra a frequência dos possiveis resultados obtidos
# Autor: Lucas Rebouças
########################################################################################################
from random import randint
import matplotlib.pyplot as plt
import statistics
import numpy as np
DADOS = 2
LADOS = 6
LANCAMENTOS = 100000
class LancamentosDados(object):
# construtor do objeto
def __init__(self, dados, lados, lancamentos):
self.dados = dados
self.lados = lados
self.lancamentos = lancamentos
self.resultados = []
self.frequencias = []
self.soma_minima = self.dados
self.soma_maxima = self.dados*self.lados
# metodo que retorna o resultado do lancamento lancamentos de dados
def lancar(self):
lancamentos = self.lancamentos
while(lancamentos >0):
soma_obtida = 0
for count in range(self.dados):
aux = randint(1, self.lados)
soma_obtida += aux
self.resultados.append(soma_obtida)
lancamentos -= 1
for count in range(self.soma_minima, self.soma_maxima + 1):
self.frequencias.append(self.resultados.count(count))
return [self.resultados, self.frequencias]
# metodo que retorna as somas obtidas obtidas ao utilizar o metodo "lancar"
def obter_resultados(self):
return self.resultados
# metodo que retorna as frequencias obtidas ao utilizar o metodo "lancar"
def obter_frequencias(self):
return self.frequencias
#Retorna um histograma acrescido de media, mediana e desvio padrao
def run_histograma(self):
freq_media = round(statistics.mean(self.resultados), 2)
freq_mediana = round(statistics.median(self.resultados), 2)
freq_desv_pad = round(statistics.stdev(self.resultados), 2)
esp_amostral = list(range(self.soma_minima, self.soma_maxima+1))
frequencia = self.frequencias
titulo_grafico = "Resultado obtido ao jogar " + str(self.dados) + " dado(s) de " + str(self.lados) + " lados " + str(self.lancamentos) + " vez(es)"
estatisticas = "Estatisticas: " + "Média " + str(freq_media) + "," " Mediana " + str(freq_mediana) + ", Desvio padrão " + str(freq_desv_pad)
titulo_eixo_y = "Freq. Absoluta"
titulo_eixo_x = "Resultados"
plt.bar(esp_amostral, frequencia, width=0.9, alpha=0.6)
plt.title(titulo_grafico)
plt.xticks(esp_amostral)
plt.yticks([]) #remove y axis
plt.ylim([0, max(frequencia)*1.2]) #set y axis limits
plt.ylabel(titulo_eixo_y)
plt.xlabel(titulo_eixo_x)
for x,y in zip(esp_amostral, frequencia):
label = frequencia[x-self.dados]
plt.annotate(label, (x,y), textcoords="offset points", xytext=(0,10), ha='center')
plt.show()
print(estatisticas)
return None
def main():
jogo = LancamentosDados(DADOS, LADOS, LANCAMENTOS)
jogo.lancar()
jogo.run_histograma()
if __name__ == "__main__":
main()
|
a2f16117572a14c3e60f07dd950b019c1a963ab6 | juliazhu09/Intro2Python | /Intro2Python.py | 21,498 | 4.46875 | 4 | # =================================
# === Python Programming Basics ===
# === Xiaojuan Zhu ===
# === [email protected] ===
# =================================
# ---HOW TO PREPARE YOUR COMPUTER---
# FOR THIS WORKSHOP
#
# ---STEP 1. INSTALLING SPYDER ---
# What is Spyder?
# A PYTHON IDE BUILT FOR ANALYZING DATA.
# Install Spyder from this sites:
# https://www.spyder-ide.org/
#
# Spyder has three windows:
# Syntax window: show you the python syntax, you can edit and store the syntax
# variable explorer window: show the variables created by the syntax
# Ipython Console window: run the python syntax and show the output
# ---STEP 2. STORE WORKSHOP FILES---
#
# In your "Documents" folder,
# create a new folder named "Intro2Python"
# unzip the files and store them there.
#
# Run Spyder and open Intro2Python.py file.
# ---STEP 3. INSTALL ADD-ON PACKAGES---
#%%
# A Python package refers to a directory of Python
# module(s). A module in python is a .py file that
# defines one or more function/classes which you
# intend to reuse in different codes of your program.
# Use PIP to install a package either in a command prompt
# window or in Anaconda.
# To use them, we import them. Submodeles/functions can be stored
# in packages, and accessed with dot syntax.
# Some packages, such as sys and os, have already been installed
# in python, you do not need to install it again. We can import
# it directly.
# Official Python description of modules and importing them:
# https://docs.python.org/2/tutorial/modules.html
# Check where is python installed and used by Rodeo/Spyder
import sys
print(sys.executable)
# Install a package using Anaconda Prompt
# python -m pip install pacakagename
# For example:
# python -m pip install seaborn
# For apps user to install a package, go to OIT Knowledge Base for instruction
# https://help.utk.edu/kb/index.php?func=show&e=2473
# Install a package using windows CMD
# pip install pacakagename
# C:\Users\XZHU8\AppData\Local\Continuum\anaconda3\python -m pip install seaborn
# reference: https://www.youtube.com/watch?v=Z_Kxg-EYvxM&t=4s
# install a package using script
from pip._internal import main
main(['install', '<package>', '--user'])
import package
#for example
from pip._internal import main
main(['install', 'seaborn==0.11.2', '--user'])
# restart the spyder
import seaborn
seaborn.__version__
#%%
# other options -does not work on Julia's machine
import sys
import subprocess
import conda.cli.python_api as Conda
# implement conda as a subprocess:
try:
import scipy
except:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'scipy==1.6.0'])
# subprocess.check_call([sys.executable, '-m', 'conda', 'install', 'scipy==1.6.0'])
import scipy
scipy.__version__
# Show all of the packages installed under Python
import pkg_resources
packages = [d for d in pkg_resources.working_set]
packages
# ---STEP 4. TEST YOUR INSTALLATION---
#
# Open this file in Spyder,
# select the following commands
# and click "Run Current Cell" or "Run Current Line". If you see
# the output, you're set.
# If not, don't worry, we only use the packages
# in the last section of the workshop.
#%%
import os
import sys
import pandas as pd
import matplotlib
import numpy as np
import scipy as sp
import seaborn as sns
print('Python version ' + sys.version)
print('Pandas version: ' + pd.__version__)
print('Matplotlib version ' + matplotlib.__version__)
print('Numpy version: ' + np.__version__)
print('Scipy version: ' + sp.__version__)
print('Seaborn version ' + sns.__version__)
# ---RUNNING PYTHON COMMANDS---
#
# As you've done above, you can
# Use File> Open or File> New
# to enter Python commands into a
# "script" file and run them.
#
# You can also enter commands one at a time
# in the terminal window at the bottom right.
# Do this sparingly as you can't save
# commands easily.
# ---TERMINAL WINDOW PROMPTS---
#
# ">>>" is the standard command prompt
#
# "..." is the prompt when continuing on a new line
#
# If you see "..." prompt when not trying to
# continue, look for a missing ")"
#
# To get rid of an unexpected "..." continuation
# prompt
# -Submit the missing piece of the command, or
# use Ctrl+C
# ipython use ESC key
# ---DOCUMENTING YOUR PROGRAMS---
# Comments go from "#" to the end of the line
# ---IMPORTING A PACKAGE TO PYTHON ---
#
# You only install a package once,
# but you need to import it from the package
# each time when you start python
#
# I do it repeatedly in this workshop to
# emphasize that a package is being used.
#
import os
import sys
import pandas as pd
#%%
# ---ASSIGNMENT OPERATOR---
#
# When creating objects, you give them
# values using the assignment operator
# "=" as here:
x = 1
# ---OBJECTS & THEIR NAMES---
#
# Python is object oriented
#
# Everything: data, functions (procedures), models,
# etc. are objects, with its properties/attributes
# and methods(like functions).
#
# The object names should begin with a letter
# and can contain letters, numbers,
# underscores.
# But cannot have space or period.
# Case matters, e.g. myvar is not MyVar
#
# ---OBJECT ATTRIBUTES AND METHODS---
#
# To access a variable/attraibute or a method, use dot syntax.
# # use pandas to create mydata as a dataframe object.
import pandas as pd
mydata = pd.DataFrame(data={'id': [1, 2, 3, 4, 5, 6, 7, 8],
'workshop': [1, 2, 1, 2, 1, 2, 1, 2],
'gender' : ['f', 'f', 'f', '' ,'m', 'm', 'm', 'm',]})
mydata
# access an attribute or variable from mydata
mydata.workshop
# For example, mean() is a method of a dataframe
mydata.mean()
# list all the attributes and methods of mydata.
dir(mydata)
#---PYTHON VARIABLES---
#
# Python's variable Types:
# Number (int, long, float, Complex)
# String
# Boolean: True or False
# List
# Tuple
# Dictionary
# We focus on list today. For details, see
# https://www.tutorialspoint.com/python/python_variable_types.htm
# Example
x = 1
type(x)
y = 1.2
print(type(y))
a = "string"
print(type(a))
#%%
## exercise 1 ##
## Write a program that assigns three variables, one of each types: string, int,
## and float. Variable names and values can be arbitrary.
## Print each variable out to the screen.
#%%
# create a list
# A list contains items separated by commas and enclosed within square brackets ([]).
id = [1, 2, 3, 4, 5, 6, 7, 8]
# Note: first item's index is 0 not 1.
# Show the first item of id.
id[0]
id[7]
# Items can be mixed types in a list.
mixlist = ["a", 1]
print(mixlist)
#%%
## exercise 2##
# The top five highest mountain peaks on Earth, according to Wikipedia, are as follows:
# 1) Mount Everest / Sagarmatha / Chomolungma 8,848 m
# 2) K2 / Qogir / Godwin Austen 8,611 m
# 3) Kangchenjunga 8,586 m
# 4) Lhotse 8,516 m
# 5) Makalu 8,485 m
# Use five mountain names, but store them as only names in a list (you
# can use one name of your choice for those with multiple names).
# Then, print to the screen the name of Kangchenjunga by referencing
# its index position in the list.
# Hint Mtn = ["K2", "Kangchenjunga" ]
#%%
# Tuples:Like lists, contains several items enclosed within parenthesis.
# but immutable, and usually used for smaller sequences
# of things that are related to each other.
# Think of Cartesian coordinates:(x, y, z)
# The differences between tuples and lists are, the tuples cannot be changed
# unlike lists, tuples use parentheses, whereas lists use square brackets.
aTuple = ("foo", "bar")
len(aTuple)
# Following action is not valid for tuples
# aTuple[0] = 100
aTuple[0] = 100
# list can be changed.
alist=["foo", "bar"]
alist[0] = 100
print(alist)
#%%
## exercise 3 ##
# create a tuple use Kangchenjunga's name and height and then query the height
# of the Kanchenjunga
# hint: mtn = ("K2", 8611)
#%%
# Dicitonairy: A collection of variables indexed by other, "key" variables.
# Instead of using numeric or default index in python, if you want to
# create your own index, you need to use dictionary.
# "Curly Braces" are used in Python to define a dictionary.
aDict = {}
aDict["a"] = 364936
aDict["b"] = 12.4
aDict[7] = "hi"
print(aDict)
aDict["a"]
aDict["b"]
aDict[7]
#%%
## exercise 4 ##
# Mary’s favorite candy is chocolate, Rodrigo’s favorite is bubble gum, and
# Larry’s is gummy bears. Write a dictionary that stores, for each person,
# their favorite candy. Then, pick a person among the three, and, using the
# dictionary keys you defined, print to the screen a statement something to
# the effect of “Mary’s candy of choice is chocolate.” Make sure that your
# print() statement is a concatenation of some text and the result of querying
# your dictionary for that person’s favorite candy.
# Hint: aDict = {"Mary": "Chocolate"}
# print("Mary's candy of chocie is " + aDict["Mary"])
#%%
# Keywords: reserved words in python.
# Cannot be used as a variable name.
import keyword
print(keyword.kwlist)
#%%
# ---PYTHON FUNCTIONS---
# As you already know, Python gives you many built-in
# functions e.g. print(mydata), dir(), type()
# When you use a function, you "call" its name.
#
# print() is the default function
# so this function call: print(q1)
print("hello world")
# ---USER-DEFINED FUNCTIONS---
#
# A function statement starts with the def keyword, followed by
# the function name, parameters and keywords and end with a colon":".
#
# Parameters/keywords in a function are called "arguments"
# Arguments are enclosed within parentheses
# and separated by commas
#
# In python, user-defined functions can take four
# different types of arguments. The argument types
# and their meanings, however, are pre-defined and
# can’t be changed.
# A function use indentation to define the content of the function.
# The content indents four spaces.
# Use Tab key as the shortcut
# The colon is used to declare the start of an indented block.
# When we need to use indentation:
# if/else statement
# for/while statement
# def statement
# class statement
#
# example:
def my_function():
print("Hello from a function")
# Calling a function
# To call a function, use the function name followed by parenthesis:
my_function()
# example:
def my_function_with_args(username, greeting):
print("Hello "+ username + " From My Function!, I wish you " + greeting + "!")
#prints - "Hello, Julia, From My Function!, I wish you a great year!"
my_function_with_args("Mary", "a great year")
#%%
#---FUNCTION OUTPUT---
#
# Returning a value from a function, Not only can
# you pass a parameter value into a function, a function
# can also produce a value, i.e., Output.
# For example,
len(aDict)
#
# That value is a single object that may contain
# much information (e.g. data frame, list)
#
# Example
def square(x):
y = x * x
return y
result = square(10)
print(result)
# Note: Cannot use print to return a value
#%%
## exercies 5 ##
# write a function that will return a person's BMI, where height and weight are
# two variable names passed to the function as the argument.
# Then call your function to compute
# a person's BMI with heigh of 1.6m and weight of 75kg.
# Hint: def BMI(weight, height):
# aBMI = weight / (height * height)
# Formula: weight (kg) / [height (cm)]^2
# Formula: weight (lb) / [height (in)]^2 x 703
#%%
#---CONDITIONAL STATEMENTS---
#
# In the real world, we commonly must evaluate information
# around us and then choose one course of action or another
# based on what we observe: For example,
#
# If the weather is nice, then I’ll mow the lawn.
# Otherwise, I won’t mow.
#
# if/else-statement
# if/elif/else-statement
#
# Blocks of code under if statements are executed as long
# as the stated condition is true.
# Here is an if/else-statement example:
weather = str(input('How is the weather today, nice or not? '))
if weather == "nice":
print('I will mow the Lawn')
else:
print("I won't mow the Lawn")
#note: double equal sign is used here.
# Can have elif (which is a contraction of "else if") and/or
# else statements associated, when the condition is not true.
# If/elif/else statement example,
i = 1
j = 2
if i + j == 3:
print("three")
elif i + j == 2:
print("two")
else:
print("neither!")
# Create a function
def checkNumber(i, j):
if i + j == 3:
print("three")
elif i + j == 2:
print("two")
else:
print("neither!")
checkNumber(1, 1)
checkNumber(10, 1)
#%%
# ---TABLE OF LOGICAL COMPARISONS---
#
# Equals ==
# Less than <
# Greater than >
# Less or equal <=
# Greater or equal >=
# Not equal !=
# And &
# Or |
# 0<=x<=1 (x >= 0) & (x <=1)
## exercise 6 ##
# Import the random module, and use the random function in it that gives you
# a value in the range [0.0, 1.0), multiply it by 10,000, and round it to zero
# decimal places using round() print to the screen a message saying the
# number is odd or even. Part of the code are shown below,
from random import randint
# generate a random number ranging from 0 to 1000
n = randint(0,1000)
m = n % 2 # Modulo (%) calculates the remainder after division.
print(n)
# Plese write the if else statement below,
if :
print("odd")
else:
print("even")
#%%
# --- ITERATION---
#
# Iteration is typically done by means of a loop,
# being a piece of code that is executed repeatedly.
# We can control how often a loop repeats, or whether it repeats at all,
# with control flow statements, which evaluates conditions.
# Control flow statements can control more than just loops.
# For more control flow statements, see
# https://docs.python.org/2.7/tutorial/controlflow.html
# --FOR STATEMENT---
#
# Blocks of code under for statements repeat themselves for each
# elements of some iterable object. They make a for loop.
# Iterable objects are those that have a defined sequence of zero or more objects.
# e.g. lists, strings, tuples, etc.
namelist = ["Bob", "Josh", "Cary","Michael","Rochelle", "Sun"]
for name in namelist:
print ("Hello " + name + ", Merry Christmas!")
aText = "Hello world!"
for i in aText:
print(i)
#---RANGE FUNCTION---
#
# Often we want to repeat an action some specified number of
# times, rather than over a collection of objects.
# The range() function returns an iterable object of numbers, of size
# (and optionally, starting value and increment) you ask for. In python,
# we iterate on that.
# Ask for a range of itegers, starting at zero and ending before 7.
aRange = range(7)
for i in aRange:
print(i)
for i in range(3, 7): # start at 3 end before 7
print(i)
for i in range(2, 12, 3): #start at 2, end before 12, increment by 3
print(i)
#%%
## exercise 7 ##
# Use the range() function to do exercise 6 five times.
from random import randint
# use for statement to run the statement five times
for i in :
n = randint(0, 1000)
m = n % 2 # Modulo (%) calculates the remainder after division.
# Plese write the if else statement below,
if m==1:
print(str(n) + " is an odd number.")
else:
print(str(n) + " is an even number.")
## extra credit assignment ##
## exercise 8 ##
# use a for statement to calucate the sum of consecutive numbers 1 to 100
# print the result to the screen
#%%
# ---WHILE STATEMENT ---
#
# Sometimes we use a conditional statment to control the number of times
# a loop repeats. As long as the condition is true, the program
# will repeatedly execute. So we need to use while statement.
# Blocks of code under while statements repeat themselves until a
# specified condition is detected as false - they make a while loop.
# Before the indented block (re)run, the condition is evaluated. It
# runs only if the condition is true.
i = 0
while i < 10:
print(str(i) + " is less than 10")
i = i + 1
print(i)
# If i had left out the increment, i could always be <10,
# and we'd get an infinite loop.
# Use Ctrl+C to terminate a loop.
#%%
## exercise 9 ##
# To make things concrete and numerical, suppose the following:
# The tea starts at 115 degrees Fahrenheit. You want it at 112 degrees.
# A chip of ice turns out to lower the temperature one degree each time.
# You test the temperature each time, and also print out the temperature
# before reducing the temperature. In Python you could write and run the code
# below, saved in example program cool.py:
temperature = 118
while temperature : # first while loop code
print(str(temperature))
temperature = temperature - 1
print('The tea is cool enough.')
#%%
#---QUESTIONS?---
# ---FINDING FILES---
#
# To tell Python the folder to read from or
# write to, set your "working directory" (wd)
#
# This sets it from your Documents folder:
import os
print(os.getcwd()) # Prints the working directory
# Set the working directory:
# python path use "/" or "\\" instead of "\"
# put a r in front of the path string without using / or \\.
import os
os.chdir(r"C:\Users\xzhu8\Downloads\Intro2Python-master") # Provide the path here
# if your run spyder on Apps.utk.edu, use the code below
## os.chdir(r"\\client\C$\Users\XZHU8\Documents\Intro2python")
# Note put "r" before the path by using "copy path" in windows
# or use of forward slash or double backward slashes ("/" or "\\")
## os.chdir(r"I:\Classes\OIT_Training\Intro to Python\netid")
# Show the work directory again:
print(os.getcwd())
# Read file from the current work directory
import pandas as pd
mydata100 = pd.read_csv("mydata100.csv")
# show the first five lines of mydata100
mydata100.head()
# see 10 rows of mydata100
mydata100.head(10)
# --- BASIC DESCRIPTIVE ANALYSIS---
#
# get the mean, sum and summary of mydata100
mydata100.mean()
mydata100.sum()
# use describe function
basic = mydata100.describe()
print(basic)
# return the means grouped by gender using groupby methods
mydata100.groupby('gender').mean()
# return means/median/std group by gender using groupby
out = mydata100.groupby('gender').agg(['mean', 'median', 'std'])
print(out)
#%%
#---BASE GRAPHICS USING SEABORN---
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
# Barplot
# Barplot stacked
sns.set(color_codes=True) #Change how matplotlib color shorthands are interpreted.
sns.catplot(x="workshop", kind="count", color="b", data=mydata100)
plt.show()
# Boxplot
# Draw a single horizontal boxplot:
sns.boxplot(x=mydata100["posttest"])
plt.show()
#Draw a vertical boxplot grouped by a categorical variable:
sns.boxplot(x="workshop", y="posttest", data=mydata100)
plt.show()
#Draw a boxplot with nested grouping by two categorical variables:
sns.boxplot(x="workshop", y="posttest", hue="gender",
data=mydata100)
plt.show()
# Scatterplot
sns.set_style("whitegrid")
sns.scatterplot(x="pretest", y="posttest", data=mydata100)
# Draw a scatterplot of two variables, x and y,
# and then fit the regression model y ~ x
# and plot the resulting regression line
# and a 95% confidence interval for that regression:
sns.regplot(x="pretest", y="posttest", data=mydata100)
#plt.show()
# Histogram
sns.distplot(mydata100['posttest'])
#plt.show()
from scipy.stats import norm
# Get rid of kernel fit
hist2 = sns.distplot(mydata100['posttest'], fit=norm, kde=False)
#plt.show()
#%%
# For many more examples,
# see: https://seaborn.pydata.org/tutorial.html
# ---LISTING OBJECTS IN YOUR WORKSPACE---
#
# %who: Print all interactive variables, with some minimal formatting.
# %whos: like %who, but gives some extra information about each variable.
%who
%whos
# ---DELETING OBJECTS---
# The del() function deletes (ReMoves) objects
del(mydata)
mydata
# You can remove a list using:
# del list
del id
id
# ---SAVING YOUR WORK---
#
# Save your progs & results with File: Save as...
#
# Export a dataframe in your workspace as csv: dataframe.to_csv('test.csv')
mydata100.to_csv( r'C:\Users\XZHU8\Documents\test.csv')
# Save a datafram as excel: dataframe.to_excel('test.xls', index=False)
mydata100.to_excel('test.xls', index=False)
# --- QUESTIONS? ---
#%%
# ---GOOD SOURCES OF PYTHON HELP---
#
# UT people get 15 hours per semester of
# free help in 540 Greve Hall:
#
# HelpDesk: 974-9900
# Walk-in Schedule:
# http://oit.utk.edu/research/schedule
#
# Python & R cheat sheets: https://www.datacamp.com/community/data-science-cheatsheets?page=3
# R & SAS/SPSS/Stata: http://www.r4stats.com
# Linkedin learning: https://oit.utk.edu/training/online-training/lil/
# Stackoverflow: https://stackoverflow.com/questions
# ---In a New Browser Tab---
#
# https://workshop.utk.edu/feedback.php
|
186aacf4b7dd4a00680643f04a7a86692fda9d87 | mpettersson/PythonReview | /questions/data_structure/hash_map_list.py | 717 | 3.65625 | 4 | class HashMapList:
def __init__(self):
self.map = {}
def put_item(self, key, item):
if not key in self.map:
self.map[key] = []
self.map[key].append(item)
def put_list(self, key, list):
self.map[key] = list
def get(self, key):
if key in self.map.keys():
return self.map[key]
else:
return None
def contains_key(self, key):
return key in self.map
def contains_key_value(self, key, value):
l = self.get(key)
if l is None:
return False
return value in l
def key_set(self):
return self.map.keys()
def __repr__(self):
return str(self.map)
|
d98cd7cf15f48c3f619ab85e9b69898f719f1004 | mjrish96/AirHockey | /gameObjects.py | 2,422 | 3.75 | 4 | import pygame
import math
class Paddle():
def __init__(self, x, y, radius, velocity):
self.x = x
self.y = y
self.radius = radius
self.velocity = velocity
def checkTopBottomBounds(self, height):
# top
if self.y - self.radius <= 0:
self.y = self.radius
# bottom
elif self.y + self.radius > height:
self.y = height - self.radius
def checkLeftBoundary(self, width):
if self.x - self.radius <= 0:
self.x = self.radius
elif self.x + self.radius > int(width / 2):
self.x = int(width / 2) - self.radius
def checkRightBoundary(self, width):
if self.x + self.radius > width:
self.x = width - self.radius
elif self.x - self.radius < int(width / 2):
self.x = int(width / 2) + self.radius
def draw(self, screen, color):
position = (self.x, self.y)
pygame.draw.circle(screen, color, position, self.radius, 0)
pygame.draw.circle(screen, (0, 0, 0), position, self.radius, 2)
pygame.draw.circle(screen, (0, 0, 0), position, self.radius - 5, 2)
pygame.draw.circle(screen, (0, 0, 0), position, self.radius - 10, 2)
class Puck():
def __init__(self, x, y, radius, velocity):
self.x = x
self.y = y
self.init_x = x
self.init_y = y
self.radius = radius
self.velocity = velocity
self.serveDirection = 1
def collidesTopBottom(self, height):
return self.y - self.radius < 0 or self.y + self.radius > height
def collidesWithPaddle(self, paddle):
"""
Checks collision between circles using the distance formula:
dist = sqrt((x2 - x1)**2 + (y2 - y1)**2)
returns true if the distance is less than or equal to sum of
radius of the puck and the paddle
"""
centerDistance = (paddle.x - self.x)**2 + (paddle.y - self.y)**2
centerDistance = math.ceil(math.sqrt(centerDistance))
if centerDistance <= self.radius + paddle.radius:
return True
return False
def reset(self):
self.velocity[0] = 10 * self.serveDirection
self.velocity[1] = 4 * self.serveDirection
self.x = self.init_x
self.y = self.init_y
def draw(self, screen):
pygame.draw.circle(screen, (255, 255, 255), (self.x, self.y), self.radius)
|
cbae4e8b17710d5622045f97fc244fb856b43ef2 | colbychang/othelloAI | /othelloRunner copy.py | 823 | 3.78125 | 4 | ## Othello Runner
from graphics import *
def initPieces(win):
loc1 = [3,3]
loc2 = [4,4]
loc3 = [3,4]
loc4 = [4,3]
whitePiece1 = Piece("white", loc1, win)
whitePiece2 = Piece("white", loc2, win)
blackPiece1 = Piece("black", loc3, win)
blackPiece2 = Piece("black", loc4, win)
blackPieceList = [blackPiece1, blackPiece2]
whitePieceList = [whitePiece1, whitePiece2]
pieceList = [whitePiece1, whitePiece2, blackPiece1, blackPiece2]
def currentPositions(pieceList):
"""This method returns the current positions of all the pieces sent in through a list as a parameter."""
# Appending all the locations of the objects in the list to an empty list.
occupiedSpaces = []
for piece in pieceList:
occupiedSpaces.append(piece.getLocation())
return occupiedSpaces
|
2ea6ce183752747b81b435b117235a9297f76c3e | Infosharmasahil/python-programming | /unit-3/function_args.py | 122 | 3.609375 | 4 | def add(*args):
total = 0
for item in args:
total += item
return total
print(add(1, 2, 3, 4, 5))
|
545d67b901880ad93402fe3376f2b1ac38087606 | Sjaiswal1911/PS1 | /python/Phonebook/proto1.py | 2,059 | 3.59375 | 4 | import pymysql
class Phonebook(object):
# Open database connection
db = pymysql.connect("localhost","root","J@imatadi19","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
contact_count = 0
def __init(self):
# Create table as per requirement
sql = """CREATE TABLE PHONEBOOK (
F_NAME VARCHAR(20) NOT NULL,
L_NAME VARCHAR(20),
CONTACT_NO VARCHAR(10),
EMAIL_ID VARCHAR(30),
DESIGNATION VARCHAR(30),
PRIMARY KEY(CONTACT_NO))"""
Phonebook.cursor.execute(sql)
Phonebook.db.close()
def add_contact(self):
number = input("Please enter the number:")
if (Phonebook.contact_count != 0):
cmd = "SELECT CONTACT_NO from Phonebook"
Phonebook.cursor.execute(cmd)
result = Phonebook.cursor.fetchall()
if number in result:
return("The number already exists.")
else:
f_name = input("Enter First name:")
l_name = input("Enter last name:")
email_id = input("Enter email_id, press '-' if not present and press enter")
designation = input("Enter designation, press '-' if not present and press enter")
#try:
temp = """INSERT INTO PHONEBOOK
(F_NAME,L_NAME,CONTACT_NO,EMAIL_ID, DESIGNATION) VALUES
('%s', '%s', '%s', '%s', '%s' ) """ % (f_name,l_name,number,email_id,designation)
Phonebook.cursor.execute(temp)
Phonebook.contact_count += 1
return("Number Added succesfully")
#except:
# return("Operation unsuccessful")
def print_contacts(self):
if(Phonebook.contact_count != 0):
cmd = "SELECT F_NAME from PHONEBOOK"
Phonebook.cursor.execute(cmd)
result = Phonebook.cursor.fetchall()
print(result)
else:
return(None)
pb = Phonebook()
#print(pb.add_contact())
#print(pb.print_contacts())
|
1e484dc3632384dfbe06cb27ff5e68aa4e76c981 | nauman-sakharkar/Python-3.x | /Data Structure & Artificial Intelligence/Linear_Sets.py | 952 | 3.875 | 4 | print("---------------------------------\nName : Nauman\nRoll No. : 648\n---------------------------------")
class Linear_Sets:
def __init__(self):
self.l=[]
def insert(self,e):
if e not in self.l:
self.l.append(e)
def union(self,b):
u=self.l[:]
for i in b.l:
if i not in u:
u.append(i)
print(u)
def intersection(self,b):
i=[]
for j in self.l:
if j in b.l:
i.append(j)
print(i)
def difference(self,b):
d=self.l[:]
for i in b.l:
if i in d:
d.remove(i)
print(d)
def issubset(self,b):
for i in self.l:
if i not in b.l:
print(False)
return
print(True)
s=Linear_Sets()
s.insert(1)
s.insert(151)
s.insert(11)
s.insert(1)
t=Linear_Sets()
t.insert(1)
s.difference(t)
s.issubset(t)
|
57b5b737ab89eb7cac97613ee2d99c0b5cdbe6be | VictrixHominum/primary_school_arithmetic_arranger | /arithmetic_arranger.py | 3,411 | 3.578125 | 4 |
def arithmetic_arranger(problems, answer=False):
arranged_problems = ""
tab = " "
if len(problems) > 5:
return "Error: Too many problems."
for i in range(len(problems)):
dashes = ""
problems[i] = problems[i].split()
try:
problems[i][0] = int(problems[i][0])
problems[i][2] = int(problems[i][2])
except:
return 'Error: Numbers must only contain digits.'
if problems[i][1] != '+' and problems[i][1] != '-':
return "Error: Operator must be '+' or '-'."
elif problems[i][0] > 9999 or problems[i][2] > 9999:
return "Error: Numbers cannot be more than four digits."
elif problems[i][1] == "+":
problems[i].append(problems[i][0]+problems[i][2])
else:
problems[i].append(problems[i][0]-problems[i][2])
problems[i][0] = str(problems[i][0])
problems[i][2] = str(problems[i][2])
problems[i][3] = str(problems[i][3])
if len(problems[i][0]) >= len(problems[i][2]) and len(problems[i][0]) >= len(str(abs(int(problems[i][3])))):
for j in range(len(problems[i][0])+2):
if j > 5:
continue
else:
dashes = dashes + "-"
problems[i].insert(3, dashes)
elif len(problems[i][2]) >= len(problems[i][0]) and len(problems[i][2]) >= len(str(abs(int(problems[i][3])))):
for j in range(len(problems[i][2])+2):
if j > 5:
continue
else:
dashes = dashes+"-"
problems[i].insert(3, dashes)
else:
for j in range(len(str(abs(int(problems[i][3]))+2))):
if j > 5:
continue
else:
dashes = dashes + "-"
problems[i].insert(3, dashes)
for item in range(len(problems)):
for element in range(len(problems[item])):
for space in range((len(problems[item][3])-len(problems[item][element]))):
if element != 1 and element != 2:
problems[item][element] = " " + problems[item][element]
elif element == 2:
spaces = len(problems[item][3]) - (len(problems[item][2])+1)
for count in range(spaces):
problems[item][2] = " " + problems[item][2]
problems[item][2] = problems[item][1] + problems[item][2]
problems[item].pop(1)
if answer is True:
for count in range(4):
for item in range(len(problems)):
if item < len(problems)-1:
arranged_problems = arranged_problems + problems[item][count] + tab
else:
arranged_problems = arranged_problems + problems[item][count]
if count < 3:
arranged_problems = arranged_problems + "\n"
else:
for count in range(3):
for item in range(len(problems)):
if item < len(problems) - 1:
arranged_problems = arranged_problems + problems[item][count] + tab
else:
arranged_problems = arranged_problems + problems[item][count]
if count < 2:
arranged_problems = arranged_problems + "\n"
return arranged_problems
|
808eef113b3285ea36a971647f6510f766406102 | 369geofreeman/MITx_6.00.1x | /algos/search/BFS.py | 1,392 | 4.3125 | 4 | # BFS (Breadth First Search)
# Breadth First Search Implementation in Python,
# Finding shortest distance and path of any node from source node in a Graph.
# (B)--(A) (E)---(G)
# | | / | |
# | | / | |
# (C) (D)/--(F)---(H)
from queue import Queue
adj_lst = {
"A": ["B","D"],
"B": ["A","C"],
"C": ["B"],
"D": ["A","E","F"],
"E": ["D","F","G"],
"F": ["D","E","H"],
"G": ["E","H"],
"H": ["G","F"]
}
# BFS code
visited= {}
level = {} # distance dictonary
parent = {}
bfs_traversal_output = []
queue = Queue()
# Set all the entries for the graph
for node in adj_lst.keys():
visited[node] = False
parent[node] = None
level[node] = -1 # infinity
# Set the source node/vertex
s = "A"
visited[s] = True
level[s] = 0
queue.put(s)
# Start the search
while not queue.empty():
u = queue.get()
bfs_traversal_output.append(u)
for v in adj_lst[u]:
if not visited[v]:
visited[v] = True
parent[v] = u
level[v] = level[u]+1
queue.put(v)
# Output of the BFS
print(bfs_traversal_output)
# Shortest distance of all nodes from source node
print(level)
# Distance of single element from source
print(level["E"])
# Shortest node of any path from source nbode
v = "G"
path = []
while v != None:
path.append(v)
v = parent[v]
path.reverse()
print(path)
|
9aa42cc24649b875d611a054530f52b09bc88176 | JohnlLiu/Sudoku_solver | /main.py | 1,432 | 3.671875 | 4 |
#Sudoku board
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def solve(board):
#check if index is empty
indx = is_empty(board)
#board is filled out and program exits
if not indx:
return True
row = indx[0]
col = indx[1]
#check for valid values to fill in for the position (index)
for i in range (1,10):
if is_valid(board, i, indx):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
def is_valid(board, num, idx):
row = idx[0]
col = idx[1]
#check row
if num in board[row]:
return False
#check column
for i in range(len(board)):
if num == board[i][col]:
return False
#check box
box_x = row//3
box_y = col//3
for i in range(box_x*3, box_x*3 + 3):
for j in range(box_y*3, box_y*3 + 3):
if num == board[i][j]:
return False
return True
def is_empty(board):
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
return [i, j]
return None
solve(board)
for i in board:
print(i) |
1549de1e28cac2201feb48b20e471789eaa881dc | Irondev25/plab | /9a.py | 919 | 4.21875 | 4 | import sqlite3
import os
if(os.path.exists("test.db")):
os.system("rm test.db")
connection = sqlite3.connect("test.db")
cursor = connection.cursor()
def createStudentDatabase():
statement = """
create table student(
usn varchar(10) primary key,
name varchar(50),
age integer,
address varchar(100))"""
cursor.execute(statement)
connection.commit()
def insertStudentValues():
students = (
('1BM17IS063','Rahul Bhaskar',20,'Ashoknagar'),
('1BM17ISxxx','xxxxx',20,'xxxx')
)
for student in students:
cursor.execute("insert into student(usn,name,age,address) values(?,?,?,?)",student)
connection.commit()
def printAllStudent():
statement = "select * from student"
cursor.execute(statement)
students = cursor.fetchall()
for student in students:
print(student)
createStudentDatabase()
insertStudentValues()
printAllStudent() |
b960ac54c57ae7299cd3a103da2e235cf457bf4c | sebastian-holguin/hw4 | /markov_chain.py | 663 | 3.625 | 4 | import numpy as np
# creating base numbers
def markov_chains(n1, N1):
n = n1
N = N1
# Creating the first array that'll hold numbers n x n
P = np.random.rand(n, n)
# Creating the second array that'll hold the initial state.
p = np.random.rand(n)
# .sum makes sure that the sum of the entries is equal to one, from the start to
# the number of entries (newaxis). This is the same method I used for the previous
# file.
P = P/P.sum(axis=1)[:, np.newaxis]
# Looping for N steps
for i in range(N):
p = P.T.dot(p)
# Computing the eigenvector.
eigenvector = np.linalg.eig(P.T)
print(eigenvector)
|
f6043a4761c5b9f4a0e0198c324fa5a1df52122b | ITZALMALTZURA/sum_primes.py | /sum_primes.py | 2,883 | 3.90625 | 4 | #! / usr / bin / python
# Archivo: sum_primes.py
# Autor: VItalii Vanovschi
# Desc: Este programa demuestra cálculos paralelos con el módulo pp
# Calcula la suma de números primos debajo de un entero dado en paralelo
# Software Python paralelo: http : //www.parallelpython.com
import math, sys, time
import pp
def isprime (n):
"" "Devuelve True si n es primo y False en caso contrario" ""
si no es isinstance (n, int):
raise TypeError ( " el argumento pasado a is_prime no es de tipo 'int' " )
si n < 2 :
devuelve False
si n ==2 :
return True
max = int (math.ceil (math.sqrt (n)))
i = 2
while i <= max:
if n% i == 0 :
return False
i = 1
return True
def sum_primes (n):
"" "Calcula la suma de todos los números primos siguientes dado el entero n" ""
devuelve la suma ([x para x en xrange ( 2 , n) if isprime (x)])
print "" "Uso: python sum_primes.py [ncpus]
[ ncpus]: el número de trabajadores que se ejecutarán en paralelo,
si se omite, se establecerá en el número de procesadores en el sistema
"" "
# tupla de todos los servidores Python paralelos para conectarse con
ppservers = ()
#ppservers = (" 10.0.0.1 ",)
if len (sys.argv)> 1 :
ncpus = int (sys.argv [ 1 ])
# Crea jobserver con ncpus trabajadores
job_server = pp.Server (ncpus, ppservers = ppservers)
else :
# Crea jobserver con número de trabajadores detectado automáticamente
job_server = pp.Server (ppservers = ppservers)
print "Comenzando pp con" , job_server.get_ncpus (), "workers"
# Envíe un trabajo de cálculo de sum_primes (100) para su ejecución.
# sum_primes - la función
# (100,) - tupla con argumentos para sum_primes
# (isprime,) - tupla con funciones de las que depende la función sum_primes
# ("matemáticas",) - tupla con nombres de módulo que deben importarse antes de la ejecución de sum_primes
# La ejecución comienza tan pronto como uno de los trabajadores esté disponible
job1 = job_server.submit (sum_primes, ( 100 ,), (isprime,), ( "math" ,))
# Recupera el resultado calculado por job1
# El valor de job1 ( ) es lo mismo que sum_primes (100)
# Si el trabajo aún no se ha terminado, la ejecución esperará aquí hasta que el resultado esté disponible
result = job1 ()
print "La suma de los primos por debajo de 100 es" , resultado
start_time = time.time ()
# Lo siguiente envía 8 trabajos y luego recupera los resultados
input = ( 100000 , 100100 , 100200 , 100300 , 100400 , 100500 , 100600 , 100700 )
jobs = [(input, job_server.submit (sum_primes, ( input,), (isprime,), ( "math" ,))) para entrada en entradas]
para entrada, trabajo en trabajos:
imprimir "Suma de primos debajo" , entrada, "es" , trabajo ()
imprimir "Tiempo transcurrido : ", time.time () - start_time, "s"
job_server.print_stats ()
# Parallel Python Software: http://www.parallelpython.com
|
11f3d7d6e3d6be343f1f01cb2025b887e949ed46 | ryankc/python | /yes_no.py | 295 | 4.28125 | 4 | print"Yes Means No And No Means Yes"
name = raw_input("What is your name?")
h = raw_input("1.Do you like your house? a.yes b.no ")
if name == "ryan" or "louie" or "aaron":
n = h
else:
n="b"
if n=="a":
print "You ",n,"like your house"
else:
print "You don't like your house"
|
b93f3259f45dbd9ee4ab762f32afd1496a63a75f | claimskg/claimskg-extractor | /claim_extractor/__init__.py | 9,492 | 3.640625 | 4 | from typing import Dict
class Claim:
def __init__(self):
"""
Default constructor, see other constructor to build object from dictionary
"""
self.source = ""
"""The name of the fack checking site, should match the name of the extractor"""
self.claim = str("")
"""The text of the claim (almost always different from the title of the page!)"""
self.body = str("")
"""Text of the claim review extracted from the fact checkin site"""
self.referred_links = ""
"""Links that appear in the body of the claim review in support of various statements."""
self.title = str("")
"""Titre of the claim review page, often different from the claim, e.g. a reformulation with more context."""
self.date = ""
"""Date on which the claim review was written"""
self.url = ""
"""URL of the claim review. Mandatory."""
self.tags = ""
"""List of tags/keywords extracted from the fact checking site when available, strings separated by commas"""
self.author = ""
"""Name of the author of the claim (the claimer)."""
self.author_url = ""
"""Webpage URL associated with the author of the claim review."""
self.date_published = ""
"""Date on which the claim was made. Not always available in fact checking sites. Often extracted from
free text. Optional, but please include it if the information is available in the fact checking site."""
self.same_as = ""
"""URL of claim reviews that are marked as identical. Only for fact checkin sites that have a list of
associated claim reviews. Optional."""
self.rating_value = ""
"""Numerical value for the truth rating, only for fact checking sites that include this information in the
meta tags following the schema.org specification. Optional."""
self.worst_rating = ""
"""Numerical value for worst rating on the scale, only for fact checking sites that include this information in the
meta tags following the schema.org specification. Optional."""
self.best_rating = ""
"""Numerical value for best rating on the scale, only for fact checking sites that include this information in the
meta tags following the schema.org specification. Optional."""
self.rating = ""
"""Truth rating (text) for the claim extracted from the fact checking site. Mandatory."""
self.claim_entities = ""
"""Named entities extracted from the text of the claim encoded in JSON, optional and deprecated,
this will be done in the claimskg generator"""
self.body_entities = ""
"""Named entities extracted from the body of the claim review encoded in JSON, optional and deprecated,
this will be done in the claimskg generator"""
self.keyword_entities = ""
"""Named entities extracted from the keywords associated with the claim review encoded in JSON, optional and deprecated,
this will be done in the claimskg generator"""
self.author_entities = ""
"""Named entities extracted from the name of the claimer (author of the claim) encoded in JSON, optional and deprecated,
this will be done in the claimskg generator"""
self.review_author = ""
"""Author of the review of the claim on the fact checking site (not the claimer!)"""
self.related_links = []
def generate_dictionary(self):
if isinstance(self.referred_links, list):
self.referred_links = ",".join(self.referred_links)
dictionary = {'rating_ratingValue': self.rating_value, 'rating_worstRating': self.worst_rating,
'rating_bestRating': self.best_rating, 'rating_alternateName': self.rating,
'creativeWork_author_name': self.author, 'creativeWork_datePublished': self.date_published,
'creativeWork_author_sameAs': self.same_as, 'claimReview_author_name': self.source,
'claimReview_author_url': self.author_url, 'claimReview_url': self.url,
'claimReview_claimReviewed': self.claim, 'claimReview_datePublished': self.date,
'claimReview_source': self.source, 'claimReview_author': self.review_author,
'extra_body': self.body.replace("\n", ""), 'extra_refered_links': self.referred_links,
'extra_title': self.title, 'extra_tags': self.tags,
'extra_entities_claimReview_claimReviewed': self.claim_entities,
'extra_entities_body': self.body_entities, 'extra_entities_keywords': self.keyword_entities,
'extra_entities_author': self.author_entities, 'related_links': ",".join(self.related_links)}
return dictionary
@classmethod
def from_dictionary(cls, dictionary: Dict[str, str]) -> 'Claim':
"""
Build claim instance from dictionary generated by the generate_dictionary method, mainly used for round tripping
from cache.
:param dictionary: The dictionary generated by generate_dictionary
"""
claim = Claim()
if 'claimReview_author_name' in dictionary.keys():
claim.source = dictionary['claimReview_author_name']
else:
claim.source = ""
claim.claim = dictionary["claimReview_claimReviewed"]
claim.body = dictionary['extra_body']
claim.referred_links = dictionary['extra_refered_links']
claim.title = dictionary['extra_title']
claim.date = dictionary['claimReview_datePublished']
claim.url = dictionary['claimReview_url']
claim.tags = dictionary['extra_tags']
claim.author = dictionary['creativeWork_author_name']
claim.date_published = dictionary['creativeWork_datePublished']
claim.same_as = dictionary['creativeWork_author_sameAs']
claim.author_url = dictionary['claimReview_author_url']
claim.rating_value = dictionary['rating_ratingValue']
claim.worst_rating = dictionary['rating_worstRating']
claim.best_rating = dictionary['rating_bestRating']
claim.rating = dictionary['rating_alternateName']
claim.related_links = dictionary['related_links']
return claim
def set_rating_value(self, string_value):
if string_value:
string_value = str(string_value).replace('"', "")
self.rating_value = string_value
return self
def set_worst_rating(self, str_):
if str_:
str_ = str(str_).replace('"', "")
self.worst_rating = str_
return self
def set_best_rating(self, str_):
if str_:
str_ = str(str_).replace('"', "")
self.best_rating = str_
return self
def set_rating(self, alternate_name):
self.rating = str(alternate_name).replace('"', "").strip()
# split sentence
if "." in self.rating:
split_name = self.rating.split(".")
if len(split_name) > 0:
self.rating = split_name[0]
return self
def set_source(self, str_):
self.source = str_
return self
def set_author(self, str_):
self.author = str_
return self
def set_same_as(self, str_):
if str_ is not None:
self.same_as = str_
return self
def set_date_published(self, str_):
self.date_published = str_
return self
def set_claim(self, str_):
self.claim = str(str_).strip()
return self
def set_body(self, str_):
self.body = str(str_).strip()
return self
def set_refered_links(self, str_):
self.referred_links = str_
return self
def set_title(self, str_):
self.title = str(str_).strip()
return self
def set_date(self, str_):
self.date = str_
return self
def set_url(self, str_):
self.url = str(str_)
return self
def set_tags(self, str_):
self.tags = str_
def add_related_link(self, link):
self.related_links.append(link)
def add_related_links(self, links):
self.related_links.extend(links)
class Configuration:
def __init__(self):
self.maxClaims = 0
self.within = "15mi"
self.output = "output.csv"
self.website = ""
self.until = None
self.since = None
self.html = False
self.entity = False
self.input = None
self.rdf = None
self.avoid_urls = []
self.update_db = False
self.entity_link = False
self.normalize_credibility = True
self.parser_engine = "lxml"
self.annotator_uri = "http://localhost:8090/service/"
def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setMaxClaims(self, maxClaims):
self.maxTweets = maxClaims
return self
def setOutput(self, output):
self.output = output
return self
def setOutputDev(self, output):
self.output_dev = output
return self
def setOutputSample(self, output):
self.output_sample = output
return self
def set_website(self, website):
self.website = website
return self
|
645ce730275d873537f99034a652c649ab6498d3 | anapauregdom/Banco-ExamenProgramacion- | /Bank.py | 1,002 | 3.875 | 4 | #AnaPaulaGemaRegaladoDominguez
class Bank:
#Se define la clase Banco
def __init__(self,name,location):
self.name=name
self.location=location
self.client_dictionary={}
self.number_clients=0
#Se crea un metodo para agregar un cliente
def add_client(self, client):
if self.already_exists(client):
print("Ese cliente ya existe")
return
else:
client_dictionary[numbre_client] = client
number_clients+=1
#Se crea un metodo para obtener a un cliente
def already_exists(self,client):
for x in range(number_clients):
if client_dictionary[x] == client:
return True
return False
#Se crea un metodo para eliminar a un cliente
def erase_client(self, index):
if index not in client_dictionary:
print("Ese cliente no existe")
return
else:
del client_dictionary[index]
def __str__(self):
cadena="Bank: " +str(self.__name)
cadena+="\n Location: "+str(self.__location)
return cadena
|
e840fb0f215b1a46e6ae345d61e77190376be636 | WilliamMarti/CCI | /Arrays and Strings/palidrome.py | 837 | 3.875 | 4 | # test if given strings permutation can be a palidrome
# return list of permutations of a given string
def returnpermutations(s, start):
slist = list(s)
swap = start + 1
print (start)
if start == len(s):
return
'''
temp = slist[start]
slist[start] = slist[swap]
slist[swap] = temp
'''
newstring = ''.join(slist)
for x in range(0, len(s)-1):
swap = x + 1
temp = slist[x]
slist[x] = slist[swap]
slist[swap] = temp
newstring = ''.join(slist)
print (newstring)
'''
if newstring == s:
return
'''
returnpermutations(newstring, start+1)
def returnpalidrome(s):
pass
def main(test):
returnpermutations(test, 0)
if __name__ == '__main__':
test = "abc"
main(test) |
49d149011f2be8856ccb7f53ac0b341b20918d74 | theeric80/LeetCode | /easy/lowest_common_ancestor_of_BST.py | 1,138 | 3.796875 | 4 |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
n, v, w = root.val, p.val, q.val
if v < n and w < n:
return self.lowestCommonAncestor(root.left, p, q)
elif v > n and w > n:
return self.lowestCommonAncestor(root.right, p, q)
return root
def main():
n0 = TreeNode(0)
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
n6 = TreeNode(6)
n7 = TreeNode(7)
n8 = TreeNode(8)
n9 = TreeNode(9)
n6.left = n2
n6.right = n8
n2.left = n0
n2.right = n4
n4.left = n3
n4.right = n5
n8.left = n7
n8.right = n9
for p, q in [(n2, n8), (n2, n4)]:
result = Solution().lowestCommonAncestor(n6, p, q)
print result.val
if __name__ == '__main__':
main()
|
28f20f90ca59777807ba7d8512073d1b3069c6fd | structuredcreations/Formal_Learning | /python_basics/C1_w6_test1_function.py | 319 | 3.859375 | 4 |
def Computerpay(hr_work,base_rate):
if int(hr_work)<=40:
pay_amount=int(hr_work)*float(base_rate)
else:
pay_amount=(40*float(base_rate))+((int(hr_work)-40)*float(base_rate)*1.5)
return pay_amount
hr_work=input("type number of hours")
base_rate=input("type base rate")
x=Computerpay(hr_work,base_rate)
print(x)
|
22ca6647f7e52fbca18fffeb2d1e351d881d71cb | dmaahs2017/covid-benford-analysis | /src/graphs.py | 2,496 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import os
import math
import utils
def display_freq(freq_tables, filter=""):
for (table_name, table) in freq_tables:
print("===============================================================")
if filter == "":
print(f"Table Name: {table_name}, Total Count: {table['count'].sum()}")
else:
print(f"Table Name: {table_name}, {filter}, Total Count: {table['count'].sum()}")
print("===============================================================")
print(table)
print("===============================================================")
print("")
def autolabel(rects, ax):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
round(height, 2),
ha='center', va='bottom')
def graph_freq(freq_tables, title="Frequency of Digit Plots", show=False, export=True, export_path=".", export_to="digit"):
rows = int(math.sqrt(len(freq_tables)))
cols = math.ceil(len(freq_tables) / rows)
fig, axs = plt.subplots(rows, cols)
fig.suptitle(title)
try:
for ((table_name, table), ax) in zip(freq_tables, utils.flatten(axs)):
bar = ax.bar(table.digit, table.freq)
ax.set_title(table_name)
ax.set_xlabel("digits")
ax.set_ylabel("freq")
ax.label_outer()
ax.set_xticks(np.arange(1, 10, step=1))
ax.set_ylim([0,1])
autolabel(bar, ax)
except TypeError: # axs is just one plot
for (table_name, table) in freq_tables:
bar = axs.bar(table.digit, table.freq)
axs.set_title(table_name)
axs.set_xlabel("digits")
axs.set_ylabel("freq")
axs.label_outer()
axs.set_xticks(np.arange(1, 10, step=1))
axs.set_ylim([0,1])
autolabel(bar, axs)
if export:
try:
fig.savefig(f"../plots/{export_path}/{export_to}_freq.png")
fig.savefig(f"../plots/{export_path}/{export_to}_freq.pdf")
except FileNotFoundError:
os.mkdir(f"../plots/{export_path}")
fig.savefig(f"../plots/{export_path}/{export_to}_freq.png")
fig.savefig(f"../plots/{export_path}/{export_to}_freq.pdf")
if show:
plt.show()
plt.close(fig)
|
b7930fcbb32b4c4ba5c02bff0e09cd97a06967a7 | joeslee94/PythonProjects | /Python101/Translator_Project.py | 333 | 4.21875 | 4 | vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
def translate(phrase):
translation = ""
for letter in phrase:
if letter in vowel:
translation += "g"
else:
translation += letter
return translation
phrase = input("Enter in a word: ")
print(translate(phrase)) |
ee240acd422ee9d7e41c8ead7434fd216a796724 | Matt-McConway/Python-Crash-Course-Working | /Chapter 8 - Functions/ex8-3_pp141_t-Shirt.py | 229 | 3.625 | 4 | """
"""
def make_shirt(size, message):
print("Your shirt is a " + size + " size.")
print("Your shirt has '" + message + "' written on it.")
make_shirt("medium", "HELLO WORLD")
make_shirt(message="1337", size="large")
|
e274fa306ecfde5e52dafa3a4049c6780f1bc41c | SameerShiekh77/Python-Problems-Solution | /problem27.py | 147 | 4.4375 | 4 | # 27. Write a Python program to calculate the length of a string
text = input("Enter any text to find what is length of text: ")
print(len(text)) |
b251fd6068ed99f9bfec0242013aa5819441b8bf | Maxwell-Banks/search-engine | /search_engine.py | 8,170 | 3.6875 | 4 | """Maxwell Banks
Search Engine
CPE202
"""
import sys
import os
from linear_hash import *
import math
class SearchEngine:
"""A search engine class that builds and maintains an inverted
index of documents stored in a specified directory and
provides a functionality to search documents with query terms
Attribues:
directory(str): a directory name
stopwords(HashMap):a hash table containing stopwords
doc_length(HashMap): a hash table containing the total
number of words in each document
doc_freqs(HashMap): a hash table containing the number of
documents containing the term for each term
term_freqs(HashMap): a hash table of hash tables for each
term. Each hash table contains the frequency of the
term in documents (document names are the keys and
the frequencies are the values)
"""
def __init__(self, directory, stopwords):
self.doc_length = HashTableLinear()
self.doc_freqs = HashTableLinear() #this will not be used in this assignment
self.term_freqs = HashTableLinear()
self.stopwords = stopwords
self.index_files(directory)
def read_file(self, file_name):
"""A helper function to read a file
Args:
infile(str): the path to a file
Returns:
list: a list of str read from a file
"""
#print('reading' + file_name)
file = open(file_name, 'r')
contents = file.read()
file.close()
return contents
def parse_words(self, lines):
"""split strings into words
Converts words to lower cases and remove new line chars.
Excludes stopwords.
Args:
lines(list): a list of strings
Returns:
list: a list of words
"""
#print('\nparsing...' + str(lines))
word_string = lines.split()
no_stops_word_list = []
for word in word_string:
if word not in self.stopwords and word != '\n':
no_stops_word_list.append(repr(word.lower()))
return no_stops_word_list
def count_words(self, filename, words):
"""counts words in a file and stores the frequency of each
word in the term_freqs hash table.
words should do not contain stopwords.
Also stores the total count of words contained in the file
in the doc_length hash table.
Args:
filename(str): the file name
words(list): a list of words
Returns:
None
"""
#print('counting...' + filename)
count = 0
for word in words:
#print(word)
count += 1
if self.term_freqs.contains(word):
hash_word = self.term_freqs.get(word)[1]
hash_word.put(filename, 1)
else:
self.term_freqs.put(word, HashTableLinear())
hash_word = self.term_freqs.get(word)[1]
hash_word.put(filename, 1)
self.doc_length.put(filename, count)
#self.doc_length.put(filename, file_hash)
def index_files(self, directory):
"""index all text files in a given directory
Args:
directory (str) : the path of a directory
"""
#print('indexing...' + directory)
all_list = os.listdir(directory)
#print(all_list)
file_list = []
#checking if a file is a file
for file in all_list:
#print(file)
text = os.path.splitext(file)[1] == '.txt'
#print(os.path.splitext(file))
file_path = (os.path.join(directory, file))
if os.path.isfile(file_path) and text:
file_list.append(file_path)
#print(file_path)
#print('====================')
#print(file_list)
#print('====================')
for file in file_list:
#print(os.path.split(file))
contents = self.read_file(file)
word_list = self.parse_words(contents)
self.count_words(file, word_list)
def get_wf(self, tf):
"""comptes the weighted frequency
Args:
tf(float): term frequency
Returns:
float: the weighted frequency
"""
#print('getting wf...' + str(tf))
if tf > 0:
wf = 1 + math.log(tf)
else:
wf = 0
return wf
def biggest_tuple(self, tuples):
"""Takes a list of tuples and returns the largest value and the list
with out that value in it
Args:
list(list): A list of tuples with values (ANY,int)
returns:
tuple: The tuple with the largest [1]
list: The remaining list
"""
mx = tuples[0]
del tuples[0]
for i in range(len(tuples)):
if tuples[i][1] > mx[1]:
temp = tuples[i]
tuples[i] = mx
mx = temp
return mx, tuples
def get_scores(self, terms):
"""creates a list of scores for each file in corpus
"The Score" is the weighted frequency/the total word count in the file
our program computes this score for each term in a query and sum all the scores
Args:
terms (list) : a list of str
Returns:
list : a list of tuples, each containing the filename and its relevancy score
"""
#scores = HashMap()
#print('getting scores...' + str(terms))
scores = HashTableLinear()
#For each query term terms
for query in terms:
try:
files_table = self.term_freqs.get(query)[1]
for file_score in files_table.table:
if file_score is not None:
scores.put(file_score[0], self.get_wf(file_score[1]))
except:
pass
score_list = []
for val in scores.table:
if val is not None and val[1] > 0:
score_list.append((val[0], val[1]))
ordered_score_list = []
big = None
while len(score_list) > 1:
big, score_list = self.biggest_tuple(score_list)
ordered_score_list.append(big)
ordered_score_list.append(score_list[0])
return ordered_score_list
#Fetch a hash table of t from self.term_freqs
#For each file in the hash table, add wf to scores[file]
#For each file in scores, do scores[file] /= self.doc_length[file]
#Return scores
def main():
"""The main beef of the function. Requests a user input from the
terminal screen and uses the search engine class the find all
relevent documents
Args:
None
Returns:
None
"""
file = open('stop_words.txt', 'r')
stop_words_str = file.read()
file.close()
stop_words = stop_words_str.split()
path = sys.argv[-1]
engine = SearchEngine(path, stop_words)
user_in = None
while True:
#input('Press any key to print the term frequencies')
#print(engine.term_freqs)
user_in = input('input: ')
if user_in == 'q':
break
elif user_in == 'f':
for word in engine.term_freqs.table:
if word:
for freq in word[1].table:
if freq:
print((word[0])+ "\t:\t" + str(freq[0])\
+ "\t" + str(freq[1]))
elif len(user_in) < 2:
print('Please use the "s:" followed by a path to search\
, "f" to display the frequencies of \nthe words or the \
"q" function to quit')
else:
parsed_input = engine.parse_words(user_in[2:])
scores = engine.get_scores(parsed_input)
for file in scores:
split_file = file[0].split('/')
print((split_file[-1], file[1]))
if __name__ == '__main__':
main() |
73066ac81266ec0e02a76eba37fbfe6f0abb4f6b | avelikev/Exercises | /data_structures/binary_trees/3_delete a node/Solution/solution.py | 1,670 | 3.96875 | 4 | # Definition: Binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def delete_Node(root, key):
# if root doesn't exist, just return it
if not root:
return root
# Find the node in the left subtree if key value is less than root value
if root.val > key:
root.left = delete_Node(root.left, key)
# Find the node in right subtree if key value is greater than root value,
elif root.val < key:
root.right= delete_Node(root.right, key)
# Delete the node if root.value == key
else:
# If there is no right children delete the node and new root would be root.left
if not root.right:
return root.left
# If there is no left children delete the node and new root would be root.right
if not root.left:
return root.right
# If both left and right children exist in the node replace its value with
# the minmimum value in the right subtree. Now delete that minimum node
# in the right subtree
temp_val = root.right
while temp_val.left:
temp_val = temp_val.left
# Replace value
root.val = mini
# Delete the minimum node in right subtree
root.right = deleteNode(root.right,root.val)
return root
def preOrder(node):
if not node:
return
return node.val
preOrder(node.left)
preOrder(node.right)
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(6)
root.left.left = TreeNode(2)
root.left.right = TreeNode(4)
root.left.right.left = TreeNode(7)
res1 = preOrder(root)
# print(res1) # Original
result = delete_Node(root, 4)
res2 = preOrder(result)
print(res1,res2) # After Deletion |
c841fc009bfacfcd1d91ef2e1e245a659e7f7561 | dhruvanshmoyal01/Data-Structures | /primitive_calculator.py | 992 | 3.578125 | 4 | def calc(num):
minOP = [None for i in range(num+1)]
minOP[0], minOP[1] = 0, 0
# operations x*2 // x*3 // x+1
# calculating the min number of operations
for i in range(2, num+1):
op1, op2, op3 = num, num, num
op1 = minOP[i-1] +1
if i%2 == 0 :
op2 = minOP[i//2] + 1
if i%3 == 0 :
op3 = minOP[i//3] + 1
minOP[i] = min(op1, op2, op3)
# storing the progression
nums = [num]
while num!=1:
if num%3 ==0 and minOP[num]-1 == minOP[num//3]:
nums += [num//3]
num = num//3
elif num%2 ==0 and minOP[num]-1 == minOP[num//2]:
nums += [num//2]
num = num//2
else:
nums += [num-1]
num = num - 1
progress = ' '.join([str(i) for i in nums][::-1])
return minOP[number], progress
if __name__ == "__main__":
number = int(input())
res, seq = calc(number)
print(res)
print(seq)
|
16aee9dffa412f244e0a9722e4cd2b0fd6a21769 | DaDaGoRo/Python | /Prueba_ComparacionStrings.py | 581 | 3.890625 | 4 | print("Hola Mundo")
var = ["Hola Mundo", "X", "Y"]
exit = "Finalizar"
temp = ""
while temp != exit:
temp = str(input("Escribe algo: "))
if temp in var:
print("Lo que escribiste: {} está en la lista".format(temp))
posicion = var.index(temp)
print("Adicionalmente, está en la posición: {}".format(posicion))
else:
print("Escribiste un dato que NO está en nuestra base de datos")
else:
print("Has escrito Finalizar, por lo tanto hemos terminado por ahora")
print("Fin del programa")
print(var)
clase = type(var)
print(clase) |
37ccb90ae036514907e4ecd0e5b82b63a84e3af3 | M-Jawad-Malik/Python | /Python_Fundamentals/29.Operations_on_sets.py | 544 | 4.21875 | 4 | # all operations of set theory : Union,intersection,difference and symmetric difference can be applied#
A={1,2,3,4,5}
B = {3,4,5,6,7,89,32,45,9}
# Difference of two sets A-B#
print('Difference of A and B is : ', A-B)
# Union of two Set AUB#
print('Union of A and B is : ', A | B)
# Intersection of two sets A&B#
print('Intersection of A and B is : ', A & B)
# symmetric difference of A and B#
print('Symmetric difference of A and B is : ', A ^ B)
# In Symmetric difference has all elements of A and B but exclude common elements#
|
4cc50141c483126a03e43509fba7181ab9ad4f76 | pacomgh/universidad-python | /017-sobrecarga-operadores/persona_sobrecarga.py | 647 | 3.96875 | 4 | class Persona:
def __init__(self, nombre):
self.__nombre = nombre
#metodo sobreescrito de la clase padre object
def __add__(self, otro):
#accedemos al nombre del objeto y lo concatenamos con el nombre del otro
#objeto
return self.__nombre + " " + otro.__nombre
def __sub__(self, otro):
return "Operacion no soportada"
p1 = Persona("juan")
p2 = Persona("Karla")
#la llamada al metodo add se hace automaticamente, solo se concatenan objetos
#cuando sobreescribimos el metodo add
#sobrecarga agrega una nueva forma de trabajar al operador +
print(p1+p2)
print(p1-p2) |
9e850bca7503ff02b906b8b8d35361104b76156f | zealpatel1990/3gpp_tagger | /utils/file_utils.py | 426 | 3.546875 | 4 | import json
def get_text_from_file(input_file):
with open(input_file, 'r') as f:
text_content = f.read()
f.close()
return text_content
def write_text_to_file(text, file_name):
with open(file_name, 'w') as f:
f.write(text)
f.close()
def write_json_to_file(dict_value, file_name):
with open(file_name, 'w') as f:
json.dump(dict_value, f, indent=6)
f.close()
|
6a7229cbaf4a1113ad6af876621b2e78b8b3db0c | isarvesh/phonebook-demo | /main.py | 2,408 | 4.21875 | 4 | import contacts
from os import system
main_message = """WELCOME TO PHONEBOOK
----------------------------------
**********************************
Please choose:
1 - to add a new contact
2 - to find a contact
3 - to update a contact
4 - to delete a contact
**********************************
----------------------------------
"""
def prompt_add_contact():
name = input("Please enter the contact's name: ")
number = input("Please enter the contact's phone number: ")
print(f"Adding {name} with {number}")
contacts.add_contact(name, number)
def prompt_get_contact():
name = input("Please enter the name to find: ")
number = contacts.get_contact(name)
if number:
print(f"{name}'s number is {number}")
else:
matches = contacts.search_contacts(name)
if matches:
for k in matches:
print(f"{k}'s number is {matches[k]}")
else:
print(f"It looks like {name} does not exist")
def prompt_update_contact():
old_name = input("Please enter the name of the contact to update: ")
old_number = contacts.get_contact(old_name)
if old_number:
new_name = input(f"Please enter the new name for this contact (leave blank to keep {old_name}): ").strip()
new_number = input(f"Please enter the new number for this contact (leave blank to keep {old_number}): ").strip()
if not new_number:
new_number = old_number
if not new_name:
contacts.update_number(old_name, new_number)
else:
contacts.update_contact(old_name, new_name, new_number)
else:
print(f"It looks like {old_name} does not exist")
def prompt_delete_contact():
name = input("Please enter the name to delete: ")
contact = contacts.get_contact(name)
if contact:
print(f"Deleting {name}")
contacts.delete_contact(name)
else:
print(f"It looks like {name} does not exist")
def main():
print(main_message)
choice = input("Please make your choice: ").strip()
if choice == "1":
prompt_add_contact()
elif choice == "2":
prompt_get_contact()
elif choice == "3":
prompt_update_contact()
elif choice == "4":
prompt_delete_contact()
else:
print("Invalid input. Please try again.")
while True:
system("clear")
main()
input("Press enter to continue: ")
|
67f5f040dc84978dbc4ceadb79f00074ff0718af | S-ghanbary98/python_API_Package | /api_request_practice.py | 1,241 | 3.75 | 4 |
# import requests
#
# check_response_postcode = requests.get("https://api.postcodes.io/postcodes/")
#
# if check_response_postcode.status_code == 200:
# print("postcode is valid")
# print("Status code: {}" .format(check_response_postcode.status_code))
#
# else:
# print("OOps something went wrong")
#
#
# import requests
#
# check_response_postcode = requests.get("https://api.postcodes.io/postcodes/nw24pn")
# if check_response_postcode: # Functionality is abstracted
# print("Success")
# else:
# print("unavailable")
#
#
import requests
check_response_postcode = requests.get("https://api.postcodes.io/postcodes/nw24pn")
# print(type(check_response_postcode.headers))
response_dict = check_response_postcode.json()["result"]
for key in response_dict.keys():
print(f"The name if the key is {key} and the value inside the key is {response_dict[key]}")
postcode = input("Enter a postcode?")
url ="https://api.postcodes.io/postcodes/" + postcode
response = requests.get(url)
if response:
print("success")
while True:
postcode = input("Enter a postcode?")
url = "https://api.postcodes.io/postcodes/" + postcode
if response:
print("success")
else:
|
e44069b96bff145fbd809e1101c1983365368bd8 | nayan-mehta/pydemo2 | /Class-9 Exception Handling.py | 2,023 | 4.28125 | 4 | #Basic Example
# while True:
# try:
# x=int(input("Enter an integer:"))
# break
# except ValueError:
# print("That was not a valid int! Try again")
#Try except else
# import sys
#
# print(sys.argv)
# try:
# f=open(sys.argv[1],'r')
# except OSError:
# print("Cannot open",sys.argv[1])
# else:
# print(sys.argv[1],'has',len(f.readline()),'lines')
# f.close()
#Try except finally
# try:
# fh=open("testfile","w")
# try:
# fh.write("This is my test file for exception handling")
# finally:
# print("Going to close the file")
# fh.close()
# except IOError:
# print("Can\'t find file or read data")
#raise
# import sys
# def read_c():
# try:
# c=float(sys.argv[1])
# except IndexError:
# raise IndexError('Celsius degrees must be applied to command line')
# except ValueError:
# raise ValueError('Celsius degree must be a pure number,'\
# 'not "%s"'%sys.argv[1])
# #Read correctly but wrong value i.e. out of range
# if c<-273.15:
# raise ValueError('Not a physical value of Celsius')
#
# return c
#
# c=read_c()
# #User defined exception class
# class Error(Exception):
# '''Base class for other exceptions'''
# pass
# class ValueTooSmallError(Error):
# '''Raised when the input is too small'''
# pass
# class ValueTooBigError(Error):
# '''Raised when the input is too large'''
# pass
#
# #User guesses a number until they guess the right one
# number=10
# while True:
# try:
# i_num=int(input("Enter a number"))
# if i_num < number:
# raise ValueTooSmallError
# elif i_num > number:
# raise ValueTooBigError
# break
# except ValueTooSmallError:
# print("The value is too small, try again")
# except ValueTooBigError:
# print("The value is too big, try again")
# print("Congratulations! You guessed is correct")
# l=[1,2,3]
# print(l[3])
|
ab51bb6a72dfa449d8807e1a9008f69029a32f0d | hugoleonardodev/learning | /python/desafio-015-python.py | 269 | 3.703125 | 4 | #Desafio 015 Python Prof Guanabara
#Car rent: input how many days? how much km? return you pay: R$1,55 p km
#Consider 1 day = 12*7=84 each day, price=(84*d)+(1.55xk)
d=int(input('How many days?'))
k=float(input('How much kilometers?'))
p=float((k*1.55)+(d*7))
print(p)
|
b5b9f851715f3e257a547e69c7e6d976455f335d | billgoo/LeetCode_Solution | /Related Topics/Two Pointers/1721. Swapping Nodes in a Linked List.py | 658 | 3.921875 | 4 | # 1721. Swapping Nodes in a Linked List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
head_k = ListNode(-1, head)
tail_k = head
tail_helper = head
for _ in range(k):
head_k = head_k.next
tail_helper = tail_helper.next
while tail_helper:
tail_k = tail_k.next
tail_helper = tail_helper.next
head_k.val, tail_k.val = tail_k.val, head_k.val
return head
|
615b97fff6245e253cdbe96e8000af47c2c7c7dc | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/08-Text-Processing/01_Lab/05-Digits-Letters-and-Other.py | 864 | 3.96875 | 4 | # 5. Digits, Letters and Other
# Write a program that receives a single string and on the first line prints all the digits,
# on the second – all the letters, and on the third – all the other characters.
# There will always be at least one digit, one letter and one other characters.
# string = input()
#
# digits = ""
# letters = ""
# other = ""
#
# for character in string:
# if character.isdigit():
# digits += character
# elif character.isalpha():
# letters += character
# else:
# other += character
#
# print(digits)
# print(letters)
# print(other)
string = input()
separator = "\n"
print(separator.join([''.join(filter(lambda x: x.isdigit(), string)),
''.join(filter(lambda x: x.isalpha(), string)),
''.join(filter(lambda x: not x.isalpha() and not x.isdigit(), string))]))
|
ac87c58420db7acd5dff47e0b50b3e5ba4ecf4b0 | tlambrou/Tweet-Generator | /analyze_word_frequency.py | 883 | 3.734375 | 4 | from collections import Counter
import sys
import string
import re
def histogram(source): #9
dictionary = {}
with open(source) as f:
wordList = f.read().split()
for word in wordList:
word = re.sub('[.,:]', '', word)
if word not in dictionary:
dictionary[word] = 1
else:
dictionary[word] += 1
return dictionary
def unique_words(histogram): #1
return len(histogram)
def frequency(word, histogram): #1
# if word in histogram:
# return histogram[word]
# else:
# return 0
# return histogram[word] if word in histogram else 0
return histogram.get(word, 0)
if __name__ == '__main__': #5
source = "bible.txt"
histogram = histogram(source)
print(histogram)
print(unique_words(histogram))
print(frequency("death", histogram))
|
2a4cbd00c1f6a5657b6dedd74ad909cd60ac7e0e | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4140/codes/1674_1105.py | 453 | 3.765625 | 4 | a=input()
print("Entrada: ",a)
a=a.lower()
if(a=="lobo"):
print("Casa: Stark");
elif(a=="leao"):
print("Casa: Lannister");
elif(a=="veado"):
print("Casa: Baratheon")
elif(a=="dragao"):
print("Casa: Targaryen")
elif(a=="rosa"):
print("Casa: Tyrell")
elif (a=="sol"):
print("Casa: Martell")
elif (a=="lula"):
print("Casa: Greyjoy")
elif(a=="esfolado"):
print("Casa: Bolton")
elif (a=="turta"):
print("Casa: Tully")
else:
print("Brasao invalido") |
5f2c70c6debb449ed53e6be019435dcdc46cf3f2 | vmurali100/prudvi | /sets.py | 455 | 3.59375 | 4 | # cities ={"Bangalore","Hyd","Ram","Ravi"}
# cities.add("Amaravathi")
# cities.update(["Tirupathi"])
# cities.remove("Bangalore")
# cities.discard("Ram")
# cities
# print(len(cities))
# print(cities)
# for a in cities:
# print(a)
newCities = { "Bangalore","Hyd","Ram","Ravi"}
newCities.add("Kochin")
newCities.update(["Mumbai"])
newCities.remove("Bangalore")
newCities.discard("Hyd")
for a in newCities:
print(a)
# print("Bangalore" in cities) |
348708c6db2b4c792eb592a49ba3ada75fcee29d | shubhamwaghe/Work-System-Design | /p_chart.py | 3,577 | 3.5625 | 4 | # Author: Shubham Waghe
# Roll No: 13MF3IM17
# Description: WSD-II Assignment-1
import numpy as np
import matplotlib.pyplot as plt
from random import gauss
import Tkinter as tk
import math
# Given data
READINGS_EACH_DAY = 400
desired_limit = 0.05
p = 0.2
RANGE_VALUE = 3
PLOT_RANGE = 2*p
#Stopping criteria
NO_OF_DAYS = 100
GLOBAL_OBSERVATIONS = []
# Function to calculate sigma
def get_sigma(p):
sigma = math.sqrt( (p*(1-p)/READINGS_EACH_DAY ))
return sigma
def get_number_of_days(p):
n = get_n(p)
return roundup(n)/READINGS_EACH_DAY
def roundup(x):
return int(math.ceil(x / READINGS_EACH_DAY*1.0)) * READINGS_EACH_DAY
def get_l(p):
l = p*desired_limit
return l
def get_n(p):
l = get_l(p)
n = (3.84*p*(1-p))/(l**2)
return n
def get_accuracy(p, n):
x = (3.84*p*(1-p))/(n)
return math.sqrt(x)
days_plotted = 0
plotting_done = False
#Final plot
plt.title("P - Chart :: Shubham Waghe")
plt.xlabel("Mean (p)")
plt.ylabel("Days")
while days_plotted <= NO_OF_DAYS:
sigma, num_days = get_sigma(p), get_number_of_days(p)
print "***********************************************************************"
print "p = ",p, " n = ", get_n(p), " sigma = ", sigma, " Number of days: ", num_days
# directly taking x<bar> mu and variance/n
random_numbers = []
for i in xrange(num_days):
observations = [gauss(0.2, 0.02) for i in range(NO_OF_DAYS)]
random_numbers.append(np.mean(observations))
# print random_numbers
N = len(GLOBAL_OBSERVATIONS)
t_observations = N + len(random_numbers)
axes = plt.axis([0, t_observations + 1, 0, PLOT_RANGE])
ucl, lcl = p + RANGE_VALUE*sigma, p - RANGE_VALUE*sigma
print "UCL: ", ucl, " LCL: ", lcl
print "***********************************************************************"
m_line = plt.axhline(y = p, color='b', linestyle = None)
ucl_line = plt.axhline(y = ucl, color='r', linestyle = '--')
lcl_line = plt.axhline(y = lcl, color='r', linestyle = '--')
offset_length = days_plotted
for i in range(len(random_numbers)):
c_pt = plt.scatter(offset_length+i+1, random_numbers[i])
GLOBAL_OBSERVATIONS.append(random_numbers[i])
days_plotted += 1
if random_numbers[i] > ucl or random_numbers[i] < lcl:
plt.pause(0.05)
print
print "###################################################"
print "Obeservation - Out of Control: ", random_numbers[i]
print "###################################################"
p = np.mean(GLOBAL_OBSERVATIONS)
break
if days_plotted == NO_OF_DAYS:
plotting_done = True
break
plt.pause(0.05)
if plotting_done: break
else:
axes = plt.axis([0, t_observations + 1, 0, PLOT_RANGE])
m_line.remove()
ucl_line.remove()
lcl_line.remove()
print
root = tk.Tk()
root.geometry("300x200+100+100")
root.title("Final Results")
revised_p = np.mean(GLOBAL_OBSERVATIONS)
accuracy = get_accuracy(revised_p, get_n(revised_p))
p_accuracy = "{:.2f}".format(accuracy*100)
heading_label = tk.Label(root, text="Results", height=2, width=100, font=("Helvetica", 14)).pack()
p_label = tk.Label(root, text="Revised p : {:.6f}".format(revised_p), height=0, width=100).pack()
accuracy_label = tk.Label(root, text="Accuracy : {0}".format(p_accuracy + " %"), height=0, width=100).pack()
b = tk.Button(root, text="Close", command=exit).pack(padx = 10, pady = 20)
root.mainloop()
while True:
plt.pause(0.05) |
76a069f02d6411654cbd484425df97db4b6ce9dd | isthegoal/SwordForOffer | /数学计算/题目34.丑数.py | 1,885 | 3.90625 | 4 | # coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目: 把只包含因子2、3和5的数称作丑数(Ugly Number)。求第1500个丑数
例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
分析: 很明显还是从数字规律来 考虑,而不可能是直接遍历,该怎么利用这一规律呢?
因为都是只包含2、3、5因子,所以这里的规律就是:因为丑数的因子只有 2 3 或者 5,所以丑数必定是 某个丑数 k 的 2倍、3倍、或者 5倍。
思路: 所有丑数都是由前面丑数乘上2,或3,或5得到的。因此丑数按从小到大顺序排列,初始化一个丑数数组a[0...n-1],以及三个临时索引i,j,k.
计算a[n] = min{2*a[i], 3*a[j], 5*a[k]}.,并min{2*a[i], 3*a[j], 5*a[k]} > 2*a[i]或min{2*a[i], 3*a[j], 5*a[k]} > 3*a[j]或 min{2*a[i], 3*a[j], 5*a[k]} > 5*a[k]情况下,更新i,j,k。
'''
def fun(n):
#定义丑数 容器ugly,我们需要有1500个丑数
ugly=[1]
#定义三个临时索引
t2=t3=t5=0
#这个循环非常有意思
while len(ugly)<n:
#对于每次 找丑数都是在已有的丑数序列中,利用三个索引从前往后搜【不是从头,是从现有的前开始】, 三个索引对应三种情况,只需要找到大于之前丑数的 对应最小的即可。方法稳稳的
#2 3 5这三个可以对应不同的各自的索引 找序列
while ugly[t2]*2<ugly[-1]:
t2+=1
while ugly[t3]*3<ugly[-1]:
t3+=1
while ugly[t5]*5<ugly[-1]:
t5+=1
ugly.append(min(ugly[t2]*2,ugly[t3]*3,ugly[t5]*5))
return ugly[-1]
|
5509c5cf210e9ce337260488cfc33afa9e683a6b | dev-iwin/book8-hanbit-python-data-structure-algorithm | /11-01.py | 646 | 3.625 | 4 | def findMinIdx(ary):
minIdx = 0 # 첫번째 값을 가리킴
for i in range(1, len(ary)): # 두번째 값부터 끝까지 비교하기
if ary[minIdx] > ary[i]:
minIdx = i
return minIdx
testAry = [55, 88, 33, 77]
minPos = findMinIdx(testAry)
print('최솟값 -->', testAry[minPos])
def findMaxIdx(ary):
maxIdx = 0 # 첫번째 값을 가리킴
for i in range(1, len(ary)): # 두번째 값부터 끝까지 비교하기
if ary[maxIdx] < ary[i]:
maxIdx = i
return maxIdx
testAry2 = [55, 88, 33, 77]
maxPos = findMaxIdx(testAry2)
print('최댓값 -->', testAry2[maxPos]) |
f8ca6ce2ddae8bca3d5c2ab923ef20ebb99fcfa0 | THACT3001/PhamTienDung-c4t3 | /hahaha/prime_number.py___jb_tmp___ | 364 | 3.8125 | 4 | n = int(input("Please enter a number: "))
count = 0
if n == 1:
print("n khong la so nguyen to")
elif n == 2:
print("n la so nguyen to")
else:
for i in range(2, n):
if n%i == 0:
count = 1
break
else:
count = 0
if count == 1:
print("n khong la so nguyen to")
else:
print("n la so nguyen to")
|
3e79816afb5a04c4655bbc2b6222539b94482f3b | borko81/basic_python_solvess | /while/report_system.py | 829 | 3.875 | 4 | expected_sum = int(input())
sold_cash = 0
sold_card = 0
total_cash = 0
total_card = 0
product_count = 0
while True:
if total_cash + total_card >= expected_sum:
print(f'Average CS: {total_cash / sold_cash:.2f}')
print(f'Average CC: {total_card / sold_card:.2f}')
break
command = input()
if command == 'End':
print('Failed to collect required money for charity.')
break
price = int(command)
product_count += 1
is_cash_payment = product_count % 2 == 1
if price <= 100 and is_cash_payment:
total_cash += price
sold_cash += 1
elif price >= 10 and not is_cash_payment:
total_card += price
sold_card += 1
else:
print('Error in transaction!')
continue
print('Product sold!')
|
68479696e3e85d90a53c4aa14a7121a3d1f55a85 | laubosslink/lab | /python/python-basic-test/MyFirstClass.py | 1,235 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 21:02:30 2012
@author: laubosslink
"""
class MyFirstClass:
_hello="default value"
def __init__(self):
self._hello = "default value from init"
@property
def hello(self):
return "from property : " + self._hello
@hello.setter
def hello(self, value):
self._hello = " (used setter) " + value
@hello.getter
def hello(self):
return "Getter " + self._hello
usefs = MyFirstClass()
usefs2 = usefs
usefs3 = MyFirstClass()
#print(MyFirstClass())
#print(usefs)
#print(usefs2)
usefs3.hello="hello modify"
#print(usefs3)
print(usefs3.hello)
print(usefs.hello)
#Sans instancier, python appel tout de même __init__
print(MyFirstClass().hello)
class MySecondClass:
number=10
def setNumber(self, number):
self.number = number
def getNumber(self):
return self.number
number2 = property(getNumber, setNumber)
myNumber = MySecondClass()
myNumber.setNumber(6)
print(myNumber.number)
myNumber.number = 2
print(myNumber.getNumber())
print(myNumber.number)
#print(MySecondClass().number)
class Trying:
number=5
print(Trying().number) |
deba2a8df135cdad1259b1a8a7441a85e103be51 | RAVarikoti/DeepLearning-NNs | /ANN.py | 2,634 | 3.59375 | 4 | #! /usr/bin/python3.6
import os
import pandas as pd
import seaborn as sns
import numpy as np
from sklearn import metrics
import tensorflow as tf
#print(tf.__version__)
#print(np.__version__)
df = pd.read_csv("Churn_Modelling.csv")
x = df.iloc[:, 3:-1].values # removing the columns that are not important (row #, customer ID and surname)
y = df.iloc[:, -1].values
#print(x)
#print(y)
# encoding categorical data --- changing the words/labels to numerical
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
x[:, 2] = le.fit_transform(x[:, 2]) # encoding gender column -- male = 1 and female =0 since we have only two variables
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [1])], remainder='passthrough')
x = np.array(ct.fit_transform(x))
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x , y, test_size=0.2, random_state=0)
# feature scaling is important for the ANN, we will apply it for all variables
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)
###################################################### ANN #########################################################
# initializing ANN
ann = tf.keras.models.Sequential()
# adding an input layer 1st hidden layer
ann.add(tf.keras.layers.Dense(units=6, activation='relu')) # first layer
ann.add(tf.keras.layers.Dense(units=6, activation='relu')) # second layer
ann.add(tf.keras.layers.Dense(units=1, activation='sigmoid')) # output layer --- since its binary units = 1 if you have >2 use OneHotEncoder and activation = softmax
# compiling the ANN
ann.compile(optimizer = 'adam', loss = 'binary_crossentropy' , metrics= ['accuracy'])
# optimizer updates the weights through Stochastic gradi optimizer, loss --> categorical
# binary_crossentropy: Computes the cross-entropy loss between true labels and predicted labels.
# training the ANN on training set
ann.fit(x_train, y_train, batch_size = 32, epochs = 50)
print(ann.predict(sc.transform([[1, 0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]])) > 0.5) #[[]] --> i/p of predict method should be a 2d array
#predicting test results
y_pred = ann.predict(x_test)
y_pred = (y_pred > 0.5)
print(np.concatenate((y_pred.reshape(len(y_pred), 1), y_test.reshape(len(y_test), 1)), 1))
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
print(cm)
ac = accuracy_score(y_test, y_pred)
print(ac)
|
4254b9e39c64d0e40c3193903654e1eb49c86382 | Dinakar726/New_Challenge | /creating_new_list.py | 511 | 4.5625 | 5 | '''
Two lists are given below. Write a program to create a third list by picking an odd-index element from the first list and even index elements from second.
# Sample Input
list1 = [3, 6, 9, 12, 15, 18, 21]
list2 = [4, 8, 12, 16, 20, 24, 28]
# Expected Output
list3 = [6, 12, 18, 4, 12, 20, 28]
'''
list1 = [3, 6, 9, 12, 15, 18, 21]
list2 = [4, 8, 12, 16, 20, 24, 28]
list3=[]
odd=list1[1::2]
even=list2[0::2]
for i in odd:
list3.append(i)
for j in even:
list3.append(j)
print(list3)
|
1c79e94148e06197e8bffca4d04a12505949d350 | medeiroscwb/py_sqlite_test | /9_sqlite_orderresults.py | 374 | 3.875 | 4 | import sqlite3
conn = sqlite3.connect("customers.db")
c = conn.cursor()
#c.execute("SELECT rowid, * FROM customers ORDER BY rowid DESC") ##orders by rowid descending
c.execute("SELECT rowid, * FROM customers ORDER BY first_name") ##orders alphabeticaly by first name
tab_all = c.fetchall()
for line in tab_all:
print(line)
print("Table Ordered.")
conn.commit() |
49006d177d51fec9bbf1dd0cd31c4c2af2841e04 | taylorcreekbaum/lpthw | /ex11/ex11-3.py | 278 | 3.90625 | 4 | print("What is your favorite color?", end=' ')
color = input()
print("What is your favoriate food?", end=' ')
food = input()
print("What is your favorite hobby?", end=' ')
hobby = input()
print(f"So would you enjoy eating {food} and looking at {color} pictures while {hobby}?") |
7d53a1380aea4c2a56206b05d47ae74e03fbdf7c | damien75/Training-Algos | /HackerRank/dynamic_programming/longest_increasing_subsequence.py | 2,083 | 4 | 4 | from typing import Any, List
class LongestIncreasingSubsequence(object):
"""
Source Hackerrank / Algorithms / Dynamic Programming / The Longest Increasing Subsequence
Input: sequence of integers of size n
Goal: find the length of the longest subsequence of increasing integers in this array
Idea: solution in O(n log n) time complexity
go through the array in normal path, from left to right
when we see a new element a[i]:
a[i] is smaller than all other last elements of the list we have so far => create new list of size 1 with a[i] as
last element and remove other list of size 1
a[i] is bigger than all others => add it to the list of longest length so far
a[i] is between smallest and biggest => add it to the list where its end element is smallest and it's bigger than
a[i] and remove all lists of same length
"""
@staticmethod
def find_position(ar: List[Any], el: Any) -> int:
left = -1
right = len(ar) - 1
while right > left + 1:
m = (left + right) // 2
if ar[m] >= el:
right = m
else:
left = m
return right
def length_of_longest_subsequence(self, ar: List[Any]) -> int:
if len(ar) == 0:
return 0
else:
last_element = [ar[0]]
best_length = 1
for i in range(1, len(ar)):
if ar[i] < last_element[0]:
last_element[0] = ar[i]
elif ar[i] > last_element[best_length - 1]:
best_length += 1
last_element.append(ar[i])
else:
last_element[self.find_position(last_element, ar[i])] = ar[i]
return best_length
def read_and_print_from_hackerrank(self):
"""
Utility function to read from hackerrank stdin and return to stdout
"""
n = int(input())
a = [0] * n
for i in range(n):
a[i] = int(input())
print(self.length_of_longest_subsequence(a))
|
e30661a859b9ae3d3fa234812d406033a816009d | sudhanshu-jha/python | /python3/Python-algorithm/Lists/kthToLast/kthToLast_test.py | 714 | 3.546875 | 4 | from LinkedList import LinkedList
from kthToLast import kthToLast
import pytest
def test_kthToLast():
lst = LinkedList()
lst.insert("Batman")
lst.insert("Superman")
lst.insert("Flash")
lst.insert("Green Lantern")
lst.insert("Wonder Woman")
lst.insert("Hawkgirl")
# Hawkgirl -> Wonder Woman -> ... -> Batman -> None
_2nd_last = kthToLast(lst, 2)
_6th_last = kthToLast(lst, 6)
_1st_last = kthToLast(lst, 1)
_overflow = kthToLast(lst, 10)
_underflow = kthToLast(lst, -1)
assert _2nd_last.get_key() == "Superman"
assert _6th_last.get_key() == "Hawkgirl"
assert _1st_last.get_key() == "Batman"
assert _overflow is None
assert _underflow is None
|
86b5f550a96e952373bdb6b93bb83d37e113431d | OvaLorenzo/Paubot | /Paubot.py | 4,796 | 3.765625 | 4 | # validacion de la matricula, acepta 8 digitos y solo numeros
print('Whats your id?')
while True:
id = input()
if id.isnumeric() == False or len(id) != 8:
print('invalid id')
else:
login = True
# el login = True es para utilizarlo como booleano en el codigo del bot, si es que se necesita.
print('La matricula %s ha sido registrada' % (id))
# el with open escribe la matricula introducida 1 sola ves, digase, si corremos el programa de nuevo y
# introducimos otra matricula, solo aparecera la ultima matricula introducida
with open('iddata.py', 'w') as file:
file.write(id)
break
while True:
print('''
eliga un comando
a)Codewars
b)Summary
c)exit''')
command = input()
if command == 'codewars' or command == 'a':
# aqui abajo el codigo de todo el bot
from datetime import datetime
path = 'path.py'
path2 = 'path2.py'
path3 = 'path3.py'
excersices = []
returnable = []
with open(path, 'r') as file:
lista = file.readlines()
for i in range(1, len(lista)):
lista_split = lista[i].split(",")
paste = {'slug': lista_split[3].replace("https://www.codewars.com/kata/", ""),
'due_date': lista_split[1], 'batch': lista_split[0]}
excersices.append(paste)
with open(path2, 'r') as file2:
lista2 = file2.readlines()
control = False
for j in range(len(excersices)):
control = False
returnable = []
for i in range(1, len(lista2)):
lista2_split = lista2[i].split(",")
# print(excersices[j]['due_date'])
# time2 = datetime.strptime(excersices[j]['due_date'], '%Y/%d/%m')
if lista2_split[2] == excersices[j]['slug']:
control = True
returnable.append(excersices[j]['batch'])
returnable.append(excersices[j]['slug'])
returnable.append(True)
returnable.append(lista2_split[4].replace("Z\n", "").replace("T", " "))
time1 = datetime.strptime(lista2_split[4].replace("Z\n", "").replace("T", " "),
'%Y-%m-%d %H:%M:%S')
time2 = datetime.strptime(excersices[j]['due_date'] + " 00:00:00", '%Y/%m/%d %H:%M:%S')
if (time1 <= time2):
returnable.append(False)
else:
returnable.append(True)
with open(path3, 'a') as file3:
file3.write(str(returnable) + "\n")
print(returnable)
# print(lista2_split[4].replace("Z\n", "").replace("T", " "))
# print(time2)
if control == False:
returnable.append(excersices[j]['batch'])
returnable.append(excersices[j]['slug'])
returnable.append(False)
returnable.append(None)
returnable.append(False)
with open(path3, 'a') as file3:
file3.write(str(returnable) + "\n")
print(returnable)
print("\n")
"# tareagrupal"
elif command == 'summary' or command == 'b':
import csv
reader1 = csv.reader(open("path.py"), delimiter=',') # ejercicios resueltos
reader = csv.reader(open("path2.py"), delimiter=',') # ejercicios totales
data = []
data1 = []
sum = 0
sum1 = 0
total_late=0
# split_exercise =
for row in reader:
data.append(row)
sum += 1
for row in reader1:
data1.append(row)
sum1 += 1
# for i in
# total_late += 1
print("Total exercises:", sum - 1)
print("Total completed:", sum1 - 1)
print("Total late:", total_late)
print("Total missing:", (sum - 1) - (sum1 - 1))
elif command == 'exit' or command == 'c':
print('Goodbye')
break
else:
print('invalid command')
# En Summary hay un peque;o error que es el Completed Late
# si prueba completed late en el archivo 'summary' vera que esta funcionando bien
# pero tuvimos un problema al unir los codigos |
39cf5adbb84ddd53c972d2ec73626f8be7dbb344 | ag3000/connect4game | /hello.py | 4,190 | 3.671875 | 4 | #setup
import random
import numpy as np
a = "player 1"
b= "player 2"
firstgo = random.choice([a,b])
print("It is %s's turn" % (firstgo))
activeplayer = firstgo
counterdict = {a : 1, b: 2}
currentboard = np.zeros([6,7],dtype=int)
counterdict[activeplayer]
previousboard = [currentboard]
#function returns true if the column is already full
def columnfull(testspace):
if currentboard[0,testspace] != 0:
return True
else:
return False
#function to check if board is full
def boardfull(currentboard):
if np.count_nonzero(currentboard) == 42:
return True
else:
return False
#function where user picks a valid column, returns the column index the player has chosen
def pickcolumn():
while True:
selectspace = input("Choose which column to drop your token")
try:
testspace = int(selectspace) - 1
except ValueError:
print("Not a valid column, please enter a number between 1 and 7")
if columnfull(testspace):
print ("Column full, pick another column")
else:
break
return testspace
#function switches the active player, returns the new activeplayer
def switchplayer(activeplayer):
if activeplayer == a:
activeplayer = b
else:
activeplayer = a
print("It is now %s's turn"% (activeplayer))
return activeplayer
#function to place counter at next available spot, returns the new board
def placecounter(currentboard,testspace,counterdict,activeplayer):
for i in reversed(range(6)):
if currentboard[i,testspace] == 0:
currentboard[i,testspace] = counterdict[activeplayer]
break
return currentboard
#check for 4 consecutive numbers in a list, returns true if there are 4 consecutive numbers and the indices of those numbers
def conseclist(list1):
m = 1
list2 = []
for i in range(len(list1)-1):
if list1[i+1] == list1[i] +1:
m += 1
list2.append(i)
if m ==4:
list2.append(i+1)
return( [True, list2] )
else:
m = 1
list2 = []
m=1
list2 = []
for i in range(len(list1)-1):
if list1[i+1] == list1[i] -1:
m += 1
list2.append(i)
if m ==4:
list2.append(i+1)
return([True,list2])
else:
m = 1
list2 = []
return(False,"No 4 consecutive numbers")
#function checks if there is a winner
def winner(currentboard,counterdict,activeplayer):
#result outputs two arrays, the first is of the row indices, the second is the column indices
result = np.where(currentboard == counterdict[activeplayer])
#check for horizontal win
for m in result[0]:
if (result[0] == m).sum() >= 4:
list1 = []
for i in list(np.where(result[0] == m)[0]):
list1.append(result[1][i])
if conseclist(list1)[0] == True:
return(True)
#check for vertical win
for m in result[1]:
if (result[1] == m).sum() >= 4:
list1 = []
for i in list(np.where(result[1] == m)[0]):
list1.append(result[0][i])
if conseclist(list1)[0] == True:
return(True)
#check for diagonal left win
coord = list(zip(result[0],result[1]))
for i,j in coord:
match1 = [(i+1,j+1),(i+2,j+2),(i+3,j+3)]
match2 = [(i+1,j-1),(i+2,j-2),(i+3,j-3)]
if set(match1).issubset(set(coord)) == True or set(match2).issubset(set(coord)) == True:
return(True)
return(False)
#undo function
#def undo():
# currentboard = previousboard[-1]
# print(currentboard)
while True:
print(currentboard)
testspace = pickcolumn()
currentboard = placecounter(currentboard,testspace,counterdict,activeplayer)
previousboard.append(currentboard)
if winner(currentboard,counterdict,activeplayer) == True:
print("%s is the winner!"%(activeplayer))
break
if boardfull(currentboard) == True:
print("Tie")
break
activeplayer = switchplayer(activeplayer)
|
2e745eda9fb86585213b2b5c20dacb8dc7ae8624 | hvaltchev/UCSC | /python3/code/Lab20_Developer_Modules/file4.py | 1,010 | 3.859375 | 4 | #!/usr/bin/env python3
"""The finally can be attached to the try/except since
Python 2.5. But, the finally always happens last, and
doesn't re-raise.
"""
def PrintFile(file_name, fail_on_read=False):
try:
file_obj = open(file_name)
for line in file_obj:
print(line, end=' ')
if fail_on_read:
raise IOError("Failed while reading.")
except IOError as info:
print(info)
finally:
print("Finally")
try:
file_obj.close()
except UnboundLocalError:
pass
def main(file_name="ram_tzu.txt"):
"""Same main as file3.py
"""
print(f"""\nCalling PrintFile("{file_name}")""")
PrintFile(file_name)
print(f"""\nCalling PrintFile("{file_name}", fail_on_read=True)""")
PrintFile(file_name, fail_on_read=True)
print("""\nCalling PrintFile("absent_file")""")
PrintFile("absent_file")
if __name__ == "__main__":
main()
|
f19a2126d0ef9c449d85c1e1084bedae72af14ca | i-me/Python2014 | /exemple_mouvement.py | 1,429 | 3.75 | 4 | from tkinter import *
#définition des gestionnaires
#D'évènement:
def move():
"Déplacement de la balle"
global x1,y1, dx, dy, flag
x1,y1=x1+dx,y1+dy
if x1>210:
x1, dx, dy= 210, 0,15
if y1>210:
y1, dx, dy=210, -15, 0
if x1<10:
x1, dx, dy=10,0,-15
if y1<10:
y1, dx, dy=10,15,0
can1.coords(oval1, x1,y1,x1+30, y1+30)
if flag>0:
fen1.after(50,move) #boucler après 50 milisecondes tant que flag démarré
def stop_it():
"arrêt de l'Animation"
global flag
flag=0
def start_it():
"Démarrage de l'animation"
global flag
#if flag==0:#Pour ne lancer qu'une seule boucle
flag=1
move()
#=== Programme principal=====
#Les variables suivantes seront utilisées de manière globales
x1,y1=10, 10 #coordonnées initiales
dx,dy= 15, 0 #'pas' du déplacement
flag=0 #commutateur
#Création du widget principal("Parent"):
fen1=Tk()
fen1.title("Exercice d'animation avec tkinter")
#création des widgets "enfants":
can1=Canvas(fen1, bg='dark grey', height=250, width=250)
can1.pack(side=LEFT, padx=5, pady=5)
oval1=can1.create_oval(x1,y1, x1+30, y1+30, width=2, fill='red')
bou1=Button(fen1, text='Quitter',width=8,command=fen1.quit)
bou1.pack(side=BOTTOM)
bou2=Button(fen1, text='Démarrer',width=8,command=start_it)
bou2.pack()
bou3=Button(fen1, text='Arrêter', width=8, command=stop_it)
bou3.pack()
fen1.mainloop()
|
ba1fe197028562c12db08559b539a3b45ccb1b98 | Koneko264/Chapter-9 | /Chapter 9/9.11.py | 1,713 | 3.75 | 4 | class Item(object):
def __init__(self,item_name,item_price,item_quantity):
self.__item_name = item_name
self.__item_price = item_price
self.__item_quantity = item_quantity
def GetItemName(self):
return self.__item_name
def GetItemPrice(self):
return self.__item_price
def GetItemQuantity(self):
return self.__item_quantity
def ChangeItemPrice(self,newprice):
self.__item_price
class Cart:
{item_name:[price,number]}
def ShowCart(self):
return self
class User(object):
def __init__(self, name):
self.name = name
self.__cartlist = {}
self.__cartlist[0] = Cart()
def AddCart(self):
self.__cartlist[len(self.__cartlist)] = Cart()
def GetCart(self,cartindex = 0):
return self.__cartlist[cartindex]
def BuyItem(self, item, itemnum, cartindex = 0):
try:
self.__cartlist[cartindex][item.getItemName()][1] += itemnum
except:
self.__cartlist[cartindex].update({item.GetItemName():[item.getItemPrice(),itemnum]})
def BuyCancle(self,item_name,itemnum,cartindex = 0):
pass
if __name__ == '__main__':
item1 = Item('apple', 7.8, 10)
item2 = Item('pear', 5, 1)
user1 = User('John')
user1.BuyItem(item1, 5)
print("user1 cart0 have: %s" % user1.GetCart(0).ShowCart())
user1.BuyItem(item2, 6)
print("user1 cart0 have: %s" % user1.GetCart(0).ShowCart())
user1.AddCart()
user1.BuyItem(item1, 5, 1)
print("user1 cart1 have: %s" % user1.GetCart(1).ShowCart())
|
ced9a84c6b742ddc8bb88a75cba07b79ef87222d | girlingoggles/training-scripts | /projects/speak_number/speak_number.py | 2,927 | 3.53125 | 4 | #!/usr/bin/env python3
#girlingoggles made this
# phase 4: fix for commented inputs
# 0
# 20000000
# negitives
# decimals
# non number input #parsing input
import sys
import math
def speak_number_ones(one):
if one == 1:
print("one", end = ' ')
elif one == 2:
print("two", end = ' ')
elif one == 3:
print("three", end = ' ')
elif one == 4:
print("four", end = ' ')
elif one == 5:
print("five", end = ' ')
elif one == 6:
print("six", end = ' ')
elif one == 7:
print("seven", end = ' ')
elif one == 8:
print("eight", end = ' ')
elif one == 9:
print("nine", end = ' ')
def speak_number_teens(teen):
if teen == 10:
print("ten", end = ' ')
elif teen == 11:
print("eleven", end = ' ')
elif teen == 12:
print("twelve", end = ' ')
elif teen == 13:
print("thirteen", end = ' ')
elif teen == 14:
print("fourteen", end = ' ')
elif teen == 15:
print("fifteen", end = ' ')
elif teen == 16:
print("sixteen", end = ' ')
elif teen == 17:
print("seventeen", end = ' ')
elif teen == 18:
print("eighteen", end = ' ')
elif teen == 19:
print("nineteen", end = ' ')
def speak_number_tens(number):
ten = int(number / 10)
if ten == 1:
speak_number_teens(number)
return
elif ten == 2:
print("twenty", end = ' ')
elif ten == 3:
print("thirty", end = ' ')
elif ten == 4:
print("fourty", end = ' ')
elif ten == 5:
print("fifty", end = ' ')
elif ten == 6:
print("sixty", end = ' ')
elif ten == 7:
prinmt("seventy", end = ' ')
elif ten == 8:
print("eighty", end = ' ')
elif ten == 9:
print("ninety", end = ' ')
speak_number_ones(int(number % 10))
def speak_number_hundreds(number):
hundred=int(number / 100)
if number > 99:
speak_number_ones(hundred)
print("hundred", end= ' ')
speak_number_tens(number % 100)
def get_digit_set(digit):
dig = int((digit - 1) // 3)
if dig == 1:
print("thousand", end=' ')
elif dig == 2:
print("million", end=' ')
elif dig == 3:
print("billion", end=' ')
def main_menu():
# 0
# 20000000
# negitives
# decimals
# non number input #parsing input
try:
sys.argv[1]
except IndexError:
number = int(input('Enter your number: '))
else:
number = int(sys.argv[1])
digit = len(str(number))
while (digit > 0):
sl = (digit % 3)
if (sl == 0):
sl = 3
set_place = (10 ** (digit - sl))
speak_number_hundreds(number // set_place)
get_digit_set(digit)
number %= set_place
digit -= sl
print("")
if (__name__ == "__main__"):
main_menu()
|
247ad0e2e9a3375646987b574f3c2a47b44468ee | Rvk1605/Python | /Programs/Functionreturn.py | 347 | 3.671875 | 4 | def disp():
def show():
return("Rajveer")
print("My name Is")
return show
ret=disp()
print(ret())
print("---------------------------------------------------------------------------")
#Defining functions Seperately
def disp():
return("My Name Is "+show())
def show():
return "Rajveer"
res=disp()
print(res) |
83c9d348e172b8693112a25060ad5af46eb0e7f7 | nischalshrestha/automatic_wat_discovery | /Notebooks/py/njmei42/kaggle-titanic-with-tensorflow/kaggle-titanic-with-tensorflow.py | 26,360 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Disclaimer:
# For the Titanic dataset, the best performance will likely be achieved by a non-ANN model. But as a student interested in applying artificial neural networks, I thought it'd be a fun/educational challenge! I'm still very very new to machine learning and neural networks so feedback is much appreciated!
# # 0) Libraries
# In[1]:
from collections import Counter
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Scikit-learn
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# Tensorflow
import tensorflow as tf
from tensorflow.python.data import Dataset
# # 1) Loading in and checking data
# In[2]:
# Okay, let's load in our datasets!
raw_train_df = pd.read_csv("/kaggle/input/train.csv")
raw_test_df = pd.read_csv("/kaggle/input/test.csv")
example_submission_df = pd.read_csv("/kaggle/input/gender_submission.csv")
train_df = raw_train_df.copy(deep=True)
test_df = raw_test_df.copy(deep=True)
train_test_lst = [train_df, test_df]
# ### First, Let's take a look at the train and test data to make sure everything was loaded okay
# In[3]:
# Taking a look at the first few values in the dataframe
display(train_df.head())
# Taking a look at the summary statistics for each feature
display(train_df.describe())
# The minimum fare of 0.00 stuck out to me as a little odd so I decided to take a little deeper look.
# Seems like maybe crew members or staff working on the Titanic? That said, there is a Jonkheer in the list too so there might have been some free tickets involved for special personages...
# In[4]:
train_df[train_df['Fare'] == 0]
# In[5]:
display(test_df.head())
display(test_df.describe())
# # 2) Data preprocessing
# ### Both train and test datasets appear to have NaN values this could cause problems for our model, so let's look at what is missing and how much
# In[6]:
display(train_df.isnull().sum())
print("Total individuals in train set is: {}".format(len(train_df)))
# In[7]:
display(test_df.isnull().sum())
print("Total individuals in test set is: {}".format(len(test_df)))
# ### The huge amount of missing Cabin data is worrying, but let's see if it has any predictive power before figuring out what to do
# In[8]:
# Let's only consider data that has non-NaN Cabin values (Age or Embarked can still be NaN!)
cabin_df = train_df[train_df['Cabin'].notnull()]
# Let's create a new feature 'deck_level' that groups passengers by deck levels
cabin_df = cabin_df.assign(deck_level=pd.Series([entry[:1] for entry in cabin_df['Cabin']]).values)
display(cabin_df.head())
print("Survival chances based on deck level:")
cabin_df.groupby(['deck_level'])['Survived'].mean()
# So it looks like deck level may be a useful feature to learn. The NaNs are troubling though, we can get around them (hopefully) by adding a new option for the deck_level to be 'U' (for unknown).
#
# Later, we'll use one hot encoding on deck_level before sending it to our neural network.
# In[9]:
def process_deck_level(train_test_lst):
new = []
for dataset in train_test_lst:
dataset = dataset.copy(deep=True)
# Take the first letter of the Cabin entry if it's not nan. Otherwise, it should be labelled as 'U'.
dataset = dataset.assign(deck_level=pd.Series([entry[:1] if not pd.isnull(entry) else 'U' for entry in dataset['Cabin']]))
# Okay, now let's drop the Cabin column from our dataset
dataset = dataset.drop(['Cabin'], axis = 1)
new.append(dataset)
return (new)
train_df, test_df = process_deck_level(train_test_lst)
# Let's check that we did the right thing...
display(train_df.head())
display(test_df.head())
# Let's also recheck what's still missing
display(train_df.isnull().sum())
display(test_df.isnull().sum())
# Okay looking better already!
# ### Now let's try to address the missing embarked data! First off what are the possible values of embarked?
# In[10]:
display(set(train_df['Embarked']))
print("Survival chances based on embarcation:")
train_df.groupby(['Embarked'])['Survived'].mean()
# It looks like people who embarked from Q had a low survival rate and S had an especially low survival rate...
#
# For this feature, we'll also fill NaN values with 'N' for 'Not known' since filling with C/Q/S looks like it would make a big difference.
# In[11]:
# Replace NaN values in the 'Embarked' column with 'N'
train_df[['Embarked']] = train_df[['Embarked']].fillna('N')
# Let's check that we filled things correctly!
display(set(train_df['Embarked']))
display(train_df.isnull().sum())
# ### Let's take a quick look at the test data and see what to do about the one fare datapoint that is missing
# In[12]:
test_df[test_df['Fare'].isnull()]
# ### Let's use Pclass to fill our missing value!
# In[13]:
Pclass_Fare_grouping = test_df.groupby(["Pclass"])['Fare']
Pclass_Fare_grouping.plot(kind='hist', bins=15, legend=True, title='Fare histogram grouped by Pclass')
plt.xlabel('Fare')
print("Mean Fare for each Pclass:")
display(Pclass_Fare_grouping.mean())
print("Median Fare for each Pclass:")
display(Pclass_Fare_grouping.median())
# The tail for the Fare for Pclass 3 is a bit long so it's probably safer to fill with the median value for that Pclass.
#
# All this work for one missing fare is overkill, but it's a good exercise in thinking about how to impute data!
# In[14]:
test_df[['Fare']] = test_df[['Fare']].fillna(Pclass_Fare_grouping.median()[3])
# Let's check that our one fill worked!
display(test_df[test_df['PassengerId'] == 1044])
display(test_df.isnull().sum())
# ### Now to figure out what to do about missing age data. Let's do a quick analysis of age before imputing any values!
# ### Let's first just take a look at the age distribution in our training set.
# In[15]:
ax = train_df[['Age']].plot(kind='hist', bins=20)
plt.xlabel("Age")
_ = plt.title("Age histogram")
# ### Next, let's look at the relationship between Age and survival
# In[16]:
train_df.groupby(['Survived', pd.cut(train_df['Age'], np.arange(0, 100, 5))]).size().unstack(0).plot.bar(stacked=True, alpha=0.75)
_ = plt.title("Age histogram grouped by survival")
# * So an initial analysis shows that younger passengers ( < 6) were much more likely to survive than not.
#
# * Agewise, the worst outcomes were for folks in their late teens and early 20's.
#
# * Bad outcomes also for people between age ~24 and ~32 as well.
# ### What about the effect of gender and age on survival?
# In[17]:
train_df.groupby(['Survived', 'Sex', pd.cut(train_df['Age'], np.arange(0, 100, 5))]).size().unstack(0).plot.bar(stacked=True, alpha=0.75)
_ = plt.title("Age histogram grouped by survival and gender")
# * This plot is a bit messy, but the left side shows pretty clearly that females had a high survival rate.
#
# * Looking at right side paints the opposite picture (with the exception if you were a male under 6, then youre survival chances were pretty good).
#
# ### This quick set of observations seem to suggest that getting age right for young children and those between 20 and 30 is important for predicting survival.
# ### One promising strategy to impute age that seems to work well in other kernels is to use the name title
# In[18]:
# All name formats seem to be something like:
# "last_name, title. first_name "nickname" (full_name)"
# To get title, we split the string by comma and select the second half. Then we split that second half by '.' and take the first half
# i.e.
# 1) ["last_name", "title. first_name "nickname" (full_name)"] (select element 1!)
# 2) ["title", "first_name "nickname" (full_name)"] (select element 0!)
train_titles = [name.split(',')[1].lstrip(' ').split('.')[0] for name in train_df['Name']]
# Let's see if the above strategy works
print("Train set titles (and counts):")
print(Counter(train_titles))
print("\nTest set titles (and counts):")
test_titles = [name.split(',')[1].lstrip(' ').split('.')[0] for name in test_df['Name']]
print(Counter(test_titles))
print("\n===============================")
age_missing_train_titles = [name.split(',')[1].lstrip(' ').split('.')[0] for name in train_df[train_df['Age'].isnull()]['Name']]
print("\nTrain set titles (and counts) with missing ages:")
print(Counter(age_missing_train_titles))
age_missing_test_titles = [name.split(',')[1].lstrip(' ').split('.')[0] for name in test_df[test_df['Age'].isnull()]['Name']]
print("\nTest set titles (and counts) with missing ages:")
print(Counter(age_missing_test_titles))
# ### Looks like we have a nice list of titles, let's add them to our dataframe for now
# In[19]:
# Let's add the titles as a new feature for our dataset
def naive_process_title(train_test_lst):
new = []
for dataset in train_test_lst:
dataset = dataset.copy(deep=True)
titles = [name.split(',')[1].lstrip(' ').split('.')[0] for name in dataset['Name']]
dataset = dataset.assign(title=pd.Series(titles).values)
new.append(dataset)
return (new)
train_df, test_df = naive_process_title([train_df, test_df])
# Taking a look at our dataframes to make sure we did the right thing...
display(train_df.head())
display(test_df.head())
# ### I'm not super well versed with titles from "back in the day" so let's see if we can discover how age (the thing we want to impute) relates to title
# In[20]:
def plot_title_age_hist(title, train_df, bins=20):
title_ages = train_df[train_df['title'] == title]['Age']
title_ages.plot(kind='hist', bins=bins, legend=True)
title_ages.describe()
plt.xlabel("Age")
plt.title("Age histogram for '{}' title".format(title))
# In[21]:
title_groups = train_df.groupby(['title'])
display(title_groups['Age'].describe())
plot_title_age_hist("Master", train_df, bins=10)
# * It looks like 'Master' is a reliable signal for young boy.
# In[22]:
plot_title_age_hist('Miss', train_df)
# * Miss looks like the corresponding title, but it can take on a much much larger variation of values...
# ### Let's see if we can get more specific ages to impute for the "miss" title by using the 'Parch' feature
# In[23]:
def title_feature_age_analysis(title, feature, train_df, bins):
# Let's loop through all values of our feature of interest (in this case "Parch")
for i in range(max(train_df[train_df['title'] == title][feature]) + 1):
# Create an age histogram for a given feature level that also has our title of interest
train_df[(train_df['title'] == title) & (train_df[feature] == i)]['Age'].plot(kind="hist", bins=bins, legend = True, label="{} {}".format(feature, i), alpha = 0.5)
# Print common descriptive stats for our title and the given level of our feature
print("Statistics for '{}' title with {} of: {}".format(title, feature, i))
display(train_df[(train_df['title'] == title) & (train_df[feature] == i)]['Age'].describe())
print("Median\t{}\n".format(train_df[(train_df['title'] == title) & (train_df[feature] == i)]['Age'].median()))
print("=========================\n")
plt.xlabel("Age")
_ = plt.title("Age histogram for '{}' title grouped by {}".format(title, feature))
title_feature_age_analysis('Miss', 'Parch', train_df, bins=20)
# ### Cool! A parch of 1 or 2 together with the 'Miss' title seems to be quite indicative of younger age! Does our finding in the train dataset hold up in the test dataset?
# In[24]:
title_feature_age_analysis('Miss', 'Parch', test_df, bins=20)
# ### Besides 'Miss' and 'Master' we'll also have to fill many more missing ages with 'Mr' and 'Mrs'. Let's see if we can use Parch to help us out again!
# In[25]:
title_feature_age_analysis('Mrs', "Parch", train_df, bins=20)
# In[26]:
title_feature_age_analysis('Mr', "Parch", train_df, bins=20)
# So it looks like "Parch" is not super helpful for narrowing the age of 'Mr' and 'Mrs' titles. Let's try using the median to fill these titles then...
# ### We've taken a bit of a look at titles and their relation to age, time to fill in our missings age values with the above information
# In[27]:
def age_imputer(train_test_lst):
new = []
for dataset in train_test_lst:
dataset = dataset.copy(deep=True)
# This is the list of unique titles for individuals with a NaN age
missing_age_titles = list(set([name.split(',')[1].lstrip(' ').split('.')[0] for name in dataset[dataset['Age'].isnull()]['Name']]))
print("Titles for individuals with missing age are: {}".format(missing_age_titles))
for title in missing_age_titles:
# Fill in missing ages for 'Mr'/'Mrs'/'Master'/'Ms'/'Dr' titles
if (title in ['Mr', 'Mrs', 'Master', 'Ms', 'Dr']):
median = dataset[(dataset['title'] == title)]['Age'].median()
# Treat 'Ms' as 'Mrs'
if (title == 'Ms'):
median = dataset[(dataset['title'] == 'Mrs')]['Age'].median()
dataset[(dataset['title'] == title) & (dataset['Age'].isnull())] = dataset[(dataset['title'] == title) & (dataset['Age'].isnull())].fillna(median)
# Fill in missing ages for "Miss" titles
elif (title == 'Miss'):
for level in range(max(dataset[dataset['title'] == title]['Parch']) + 1):
df = dataset[(dataset['title'] == 'Miss') & (dataset['Age'].isnull()) & (dataset['Parch'] == level)]
if (not df.empty):
median = dataset[(dataset['title'] == title) & (dataset['Parch'] == level)]['Age'].median()
dataset[(dataset['title'] == 'Miss') & (dataset['Age'].isnull()) & (dataset['Parch'] == level)] = dataset[(dataset['title'] == 'Miss') & (dataset['Age'].isnull()) & (dataset['Parch'] == level)].fillna(median)
new.append(dataset)
return (new)
train_df, test_df = age_imputer([train_df, test_df])
# In[28]:
display(train_df.isnull().sum())
display(test_df.isnull().sum())
# ### Looks like all the NaNs got filled in. But we should do some sanity checks to verify that things got filled in **correctly**.
# In[29]:
display(raw_train_df[raw_train_df['Age'].isnull()])
# In[30]:
# Select passengers that have NaN ages in our raw_train_df
train_df.loc[train_df['PassengerId'].isin(raw_train_df[raw_train_df['Age'].isnull()]['PassengerId'])]
# ### How does our new distribution look?
# In[31]:
fig, (ax1, ax2) = plt.subplots(1, 2)
# First column plot
train_df[['Age']].plot(kind='hist', bins=20, ax=ax1, legend=False)
ax1.set_xlabel("Age")
ax1.set_title("NaN filled")
ymin, ymax = ax1.get_ylim()
# Second column plot
raw_train_df[['Age']].plot(kind='hist', bins=20, ax=ax2, sharey=True, legend=False)
ax2.set_ylim(ymin, ymax)
ax2.set_xlabel("Age")
_ = ax2.set_title("Original distribution")
# Looks like things got filled in properly. We now have a massive peak at 30 and 35 years of age due to the large number of fills we made (for 'Mr' and 'Mrs' titles) but the rest of the distribution looks to be preserved...
# # 3) Some feature engineering
# While going through the data, I happened to stumble on the unfortunate 'Sage' family which had a 0 survival rate despite having women and children (which normally have a high survival rate).
# In[32]:
raw_train_df[raw_train_df['Name'].str.startswith('Sage,')]
# Maybe, family size and/or the Pclass also played a big role in survivorship. Let's engineer some features and explore!
# In[33]:
# Let's add family_size which is just the sum of 'SibSp' and 'Parch'
train_df['family_size'] = train_df['SibSp'] + train_df['Parch']
test_df['family_size'] = test_df['SibSp'] + test_df['Parch']
# Check that things were added properly
display(train_df.head())
# Plot family size grouped by survival
train_df.groupby(['Survived'])['family_size'].plot(kind='hist', legend=True, alpha=0.5)
plt.xlabel("Family Size")
_ = plt.title("Histogram of family size grouped by survival")
# So yeah... large family is definitely not good for survival...
# In[34]:
_ =train_df.groupby(['Survived', pd.cut(train_df['Pclass'], np.arange(0, 4))]).size().unstack(0).plot.bar(stacked=True)
# Being in Pclass gives much higher chance of survival but let's drill in more and look at gender too
# In[35]:
_ = train_df.groupby(['Survived', 'Sex', pd.cut(train_df['Pclass'], np.arange(0, 4))]).size().unstack(0).plot.bar(stacked=True)
# Looks like if you were a female in class 1 or 2 your chances were pretty great. Pclass 3 females had more of a 50/50 chance.
#
# As a male things look much more grim. But Pclass 1 and 2 males still fare better than those in 3.
#
# Since I'm using tensorflow, we can create the 'Pclass' and 'Sex' feature cross in the data pipeline (below).
# # 4) Assembling pipeline for tensorflow
# In[36]:
# To get things to work nicely with tensorflow we'll need to subtract one from 'Pclass' so our classes start at 0
train_df['Pclass'] = train_df['Pclass'] - 1
test_df['Pclass'] = test_df['Pclass'] - 1
# In[37]:
train_df
# In[38]:
# Let's remind ourselves of the data columns we have
train_df.columns
# In[49]:
def build_feature_columns():
"""
Build our tensorflow feature columns!
For a great overview of the different feature columns in tensorflow and when to use them, see:
https://www.tensorflow.org/versions/master/get_started/feature_columns
"""
Pclass = tf.feature_column.categorical_column_with_identity("Pclass", num_buckets = 3)
Sex = tf.feature_column.categorical_column_with_vocabulary_list("Sex", ["female", "male"])
Age = tf.feature_column.numeric_column("Age")
SibSp = tf.feature_column.numeric_column("SibSp")
Parch = tf.feature_column.numeric_column("Parch")
Fare = tf.feature_column.numeric_column("Fare")
# I end up not using the 'Embarked' feature but you can try it if you'd like!
#Embarked = tf.feature_column.categorical_column_with_vocabulary_list("Embarked", ["C", "N", "Q", "S"])
# I end up not using the deck_level feature but you can try it if you'd like!
#deck_level = tf.feature_column.categorical_column_with_vocabulary_list("deck_level", ["A", "B", "C", "D", "E", "F", "G", "T", "U"])
family_size = tf.feature_column.numeric_column("family_size")
Pclass_x_Sex = tf.feature_column.crossed_column(keys = [Pclass, Sex], hash_bucket_size = 10)
# Let's bucket age into 5 year boundaries
age_buckets = tf.feature_column.bucketized_column(Age, boundaries=list(range(5, 100, 10)))
fare_buckets = tf.feature_column.bucketized_column(Fare, boundaries=list(range(1, 600, 10)))
# Wrapping categorical columns in indicator columns
#Embarked = tf.feature_column.indicator_column(Embarked)
#deck_level = tf.feature_column.indicator_column(deck_level)
Pclass = tf.feature_column.indicator_column(Pclass)
Sex = tf.feature_column.indicator_column(Sex)
Pclass_x_Sex = tf.feature_column.indicator_column(Pclass_x_Sex)
# Time to put together all the feature we'll use!
#feature_columns = set([Pclass, Sex, Age, SibSp, Parch, Fare, Embarked, age_buckets, fare_buckets, family_size, Pclass_x_Sex])
#feature_columns = set([Pclass, Sex, Age, SibSp, Parch, Fare, age_buckets, fare_buckets, family_size, Pclass_x_Sex])
#feature_columns = set([Pclass, Sex, Age, SibSp, Parch, Fare, age_buckets, family_size, Pclass_x_Sex])
#feature_columns = set([Pclass, Sex, Age, SibSp, Parch, fare_buckets, age_buckets, family_size, Pclass_x_Sex])
feature_columns = set([Pclass, Sex, fare_buckets, age_buckets, family_size, Pclass_x_Sex])
return(feature_columns)
# In[50]:
def input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
"""
This is our input function that will pass data into the tensorflow DNN class we'll create.
It takes in a pandas dataframe.
It outputs a tensorflow dataset one_shot_iterator
"""
# Convert pandas df to dict of numpy arrays
features = {key:np.array(value) for key, value in dict(features).items()}
# Put together the tensorflow dataset. Configures batching/repeating.
dataset = Dataset.from_tensor_slices((features, targets))
dataset = dataset.batch(batch_size).repeat(num_epochs)
# Shuffle data
if (shuffle):
dataset = dataset.shuffle(buffer_size = 20000)
features, labels = dataset.make_one_shot_iterator().get_next()
return (features, labels)
# We'll take our train data and do a 70/30 split so that we can get a sense for the validation performance before trying it on the test set.
# In[51]:
train_ex_df = train_df.sample(frac=0.70)
train_targ_series = train_ex_df['Survived']
#train_ex_df = train_ex_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", "family_size", "deck_level"]]
#train_ex_df = train_ex_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "family_size", "deck_level"]]
train_ex_df = train_ex_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "family_size"]]
xval_ex_df = train_df.drop(train_ex_df.index)
xval_targ_series = xval_ex_df['Survived']
#xval_ex_df = xval_ex_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", "family_size", "deck_level"]]
#xval_ex_df = xval_ex_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "family_size", "deck_level"]]
xval_ex_df = xval_ex_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "family_size"]]
# # 5) Building our (deep neural network) DNN classifier model with tensorflow
# In[52]:
def plot_acc(train_accs, val_accs):
fig, ax = plt.subplots(1, 1)
ax.set_ylabel("Accuracy")
ax.set_xlabel("Period")
ax.set_title("DNN model accuracy vs. Period")
ax.plot(train_accs, label = "train")
ax.plot(val_accs, label = "validation")
ax.legend()
fig.tight_layout()
print("Final accuracy (train):\t\t{:.3f}".format(train_accs[-1]))
print("Final accuracy (validation):\t{}".format(val_accs[-1]))
def train_dnn_classifier(periods, learning_rate, steps, batch_size, hidden_units, train_ex, train_targ, val_ex, val_targ):
#steps per period (spp)
spp = steps / periods
# Make our tensorflow DNN classifier (we'll use the ProximalAdagradOptimizer with L1 regularization to punish overly complex models)
optim = tf.train.ProximalAdagradOptimizer(learning_rate = learning_rate,
l1_regularization_strength=0.1)
# We'll use the stock DNNClassifier
# We'll also add dropout at a 20% rate to make our network more robust (hopefully)
# Finally, we'll make our activation function a leaky_relu
dnn_classifier = tf.estimator.DNNClassifier(feature_columns = build_feature_columns(),
hidden_units = hidden_units,
optimizer = optim,
dropout = 0.25,
activation_fn = tf.nn.leaky_relu)
# Input functions
train_input_fn = lambda: input_fn(train_ex,
train_targ,
batch_size = batch_size)
pred_train_input_fn = lambda: input_fn(train_ex,
train_targ,
num_epochs = 1,
shuffle = False)
pred_val_input_fn = lambda: input_fn(val_ex,
val_targ,
num_epochs = 1,
shuffle = False)
#train and validation accuracy per period
train_app = []
val_app = []
for period in range(periods):
# Train our classifier
dnn_classifier.train(input_fn = train_input_fn, steps = spp)
# Check how our classifier does on training set after one period
train_pred = dnn_classifier.predict(input_fn = pred_train_input_fn)
train_pred = np.array([int(pred['classes'][0]) for pred in train_pred])
# Check how our classifier does on the validation set after one period
val_pred = dnn_classifier.predict(input_fn = pred_val_input_fn)
val_pred = np.array([int(pred['classes'][0]) for pred in val_pred])
# Calculate accuracy metrics
train_acc = accuracy_score(train_targ, train_pred)
val_acc = accuracy_score(val_targ, val_pred)
print("period {} train acc: {:.3f}".format(period, train_acc))
# Add our accuracies to running list
train_app.append(train_acc)
val_app.append(val_acc)
print("Training done!")
plot_acc(train_app, val_app)
return (dnn_classifier)
# # 6) Training our model
# In[53]:
tf.logging.set_verbosity(tf.logging.ERROR)
classifier = train_dnn_classifier(periods = 25,
learning_rate = 0.05,
steps = 4000,
batch_size = 75,
hidden_units = [100, 100, 42],
train_ex = train_ex_df,
train_targ = train_targ_series,
val_ex = xval_ex_df,
val_targ = xval_targ_series)
# # 7) Making predictions for test dataset
# In[54]:
#test_ex_df = test_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "family_size", "deck_level"]]
#test_ex_df = test_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", "family_size", "deck_level"]]
test_ex_df = test_df[["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "family_size"]]
# Create a dummy series that will be compatible with our input_fn
test_targ_series = pd.Series(np.zeros(len(test_df), dtype=int))
pred_test_input_fn = lambda: input_fn(test_ex_df,
test_targ_series,
num_epochs = 1,
shuffle = False)
test_pred = classifier.predict(input_fn = pred_test_input_fn)
test_pred = np.array([int(pred['classes'][0]) for pred in test_pred])
# In[ ]:
submission_df = test_df[["PassengerId"]]
submission_df = submission_df.assign(Survived=pd.Series(test_pred).values)
display(submission_df)
submission_df.to_csv('2018-03-31_submission_5.csv', index = False)
# In[ ]:
|
6f3b7acf404f5b26f5e0b249f6ac80856bc1d2be | zhangzongyan/python20180319 | /day08/e1.py | 378 | 3.640625 | 4 |
import datetime
import e1_module as mye
import turtle
def mytime(mytimestr):
for i in mytimestr:
mye.drawDigit(int(i))
if __name__ == "__main__":
turtle.setup(800, 600, 200, 200)
turtle.penup()
turtle.backward(300)
turtle.pendown()
# 获取当前的年月日
s = datetime.date.strftime(datetime.datetime.now(), "%Y%m%d")
print(s)
mytime(s)
turtle.done()
|
76beec2e93dbf6127d97194935c770ea3024b72f | fergussmyth/Hangman | /main.py | 1,354 | 3.796875 | 4 | import os, random, time, assets
f = open('word.txt', 'r')
word = random.choice(f.readlines()).strip().upper()
reveal = list(len(word)*'_')
lives = 7
game_won = False
print('Welcome to HANGMAN!')
time.sleep(1)
print('Game is starting..')
time.sleep(2)
def letter_check(letter, word):
"""
Function to check if single letter is in word, if so replaces blank with letter.
:param letter:
:param word:
:return:
"""
global reveal
global game_won
global lives
for i in range(0, len(word)):
letter = word[i]
if guess == letter:
reveal[i] = guess
if '_' not in reveal:
game_won = True
else:
game_won = False
def status():
"""
Current status of lives remaining, changes assets picture.
:return:
"""
os.system('cls')
print(assets.pictures[7-lives])
print(' '.join([str(e) for e in reveal]))
print('You have', lives, 'lives remaining!')
while game_won == False and lives > 0:
status()
guess = input('Guess a letter or word: ')
guess = guess.upper()
if guess == word:
game_won = True
if len(guess) == 1 and guess in word:
letter_check(guess, word)
else:
lives -= 1
if game_won:
print('Well done you won! The final word was', word)
else:
print('You failed! The word was', word)
|
9482d34e26d44cf942b9fe48e5d2c2dbdcd696d1 | saveriogzz/CS_Curriculum | /ALGS200x_Algorithmic_Design_and_Techniques/5.Dynamic_Programming/PC5-2_primitive_calculator.py | 747 | 3.625 | 4 | def greedy_calc(n):
numOperations = 0
history = [n]
while n > 1:
numOperations += 1
if n % 3 == 0:
n /= 3
elif n % 2 == 0:
n /= 2
else:
n -= 1
history.append(int(n))
return numOperations, history[::-1]
def min_ops(n):
result = [0 for x in range(n + 1)]
for i in range(2, n+1):
min1 = result[i-1]
min2 = float('inf')
min3 = float('inf')
if i % 2 == 0:
min2 = result[i // 2]
if i % 3 == 0:
min3 = result[i // 3]
minOp = min(min1, min2, min3)
result[i] = minOp + 1
return result[-1]
if __name__ == '__main__':
n = int(input())
print(min_ops(n))
|
1d38a7481b12b73bb712a9c14245b38cfe9240d9 | vividsky/CSES | /trailing_zero.py | 123 | 3.5625 | 4 | from math import factorial
# n = int(input())
n = 100000000
count = 0
while n != 0:
n = (n//5)
count+=n
print(count)
|
4793ea5c44741359cf475c1fc1cfff9feeabd4b3 | rafaelperazzo/programacao-web | /moodledata/vpl_data/79/usersdata/162/43338/submittedfiles/serie1.py | 189 | 3.625 | 4 | # -*- coding: utf-8 -*-
import math
n=int(input('n:'))
soma=0
for i in range(1,n+1,1):
if i%2==0:
soma=soma-(i/(i**2))
else:
soma=soma+(i/(i**2))
print('%.5f'%soma)
|
a9e21f6f19138eb38a9beabbe64fead2973a2eb3 | thominj/reinforcement-learning | /reinforcement_learning/trainers.py | 1,792 | 3.609375 | 4 | import random
import reinforcement_learning.agents as agents
import reinforcement_learning.base as base
class MonteCarloTrainer(base.Trainer):
"""Uses a RandomAgent to select Actions. Stores reward and state between
actions, and reverts to the previous state if the reward for a new action is
lower than the previous reward, with a small chance for keeping a worse state.
"""
def __init__(
self,
environment_generator: 'base.EnvironmentGenerator',
agent: 'agents.RandomAgent',
output: 'base.Output',
num_scenarios: int = 1,
max_trials: int = 100,
keep_prob: float = 0.1,
):
self._environment_generator = environment_generator
self._num_scenarios = num_scenarios
self._max_trials = max_trials
self._keep_prob = keep_prob
self._agent = agent
self._output = output
super().__init__()
def train(self):
self._scenario_count = 0
while self._scenario_count < self._num_scenarios:
self._scenario_count += 1
self._environment = self._environment_generator.new_environment()
self._trial = 0
while self._trial < self._max_trials:
self._trial += 1
state = self._environment.state
reward = self._environment.reward
action = self._agent.choose_action()
self._environment.update(action)
new_reward = self._environment.reward
if new_reward.value < reward.value:
if random.random() < self._keep_prob:
self._environment.state = state
self._output.send(self._environment.state, self._environment.reward, self)
|
1f805a4dc6a35ca3ddaf964c4c9c7e981cb6fb92 | TianrunCheng/LeetcodeSubmissions | /open-the-lock/Time Limit Exceeded/6-28-2021, 3:22:37 PM/Solution.py | 1,789 | 3.90625 | 4 | // https://leetcode.com/problems/open-the-lock
from collections import deque
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
# each step we could turn one wheel one slot
# 4 wheels * 2 directions = 8 possible next steps
# bredth first search?
# reaching target: return steps;
# reaching deadend: don't use it to add to queue of (step+1)'s starting point
# complexity of this method?
for pos in deadends:
if pos == target:
return -1
def turnLock(curr: str) -> list:
curr = list(curr)
res = []
for i in range(4):
num = int(curr[i])
turnForward = (num + 1) % 10
curr[i] = str(turnForward)
res.append("".join(curr))
turnBackward = (num - 1) % 10
curr[i] = str(turnBackward)
res.append("".join(curr))
curr[i] = str(num)
# print(res)
return res
queue = deque()
queue.append("0000")
step = 0
# queue includes the possible lock state at step
count = 0
while(len(queue) > 0):
size = len(queue)
for _ in range(size):
curr = queue.popleft()
count += 1
# print(curr)
# print(count)
if curr == target:
return step
if curr not in deadends:
res = turnLock(curr)
for turn in res:
if turn not in queue:
queue.append(turn)
step += 1
return -1 |
9085ca2129140c610e2b0876f0afb7cd109f4448 | sunday1103/Notebook | /language/python/library/gui/first.py | 3,141 | 3.5 | 4 | from tkinter import Tk, Label, Button, filedialog, Text, Entry
import tkinter
class MyFirstGUI:
def __init__(self, master):
self.master = master
master.title("A simple Telnet Client")
self.file = 0
self.ip = '192.168.172.90'
self.port = 40001
self.timeout = 1
help = '''
使用说明:
1. 打开待发送文本,
在右侧查看脚本是否正确
2. 更改脚本或者直接发送
注意:
脚本需要使用utf-8编码
'''
self.ipLabel = Label(master, text="串口服务器IP:")
self.ipLabel.config(justify=tkinter.LEFT)
self.portLabel = Label(master, text="需要发送板子Port:")
self.timeoutlable = Label(master, text="发送间隔(s):")
self.ipEntry = Entry(master)
self.ipEntry.insert(0, "192.168.172.90")
self.portEntry = Entry(master)
self.portEntry.insert(0, "40001")
self.timeoutEntry = Entry(master)
self.timeoutEntry.insert(0, "1")
self.ipLabel.grid(row=0, column=0)
self.ipEntry.grid(row=1, column=0)
self.portLabel.grid(row=2, column=0)
self.portEntry.grid(row=3, column=0)
self.timeoutlable.grid(row=4, column=0)
self.timeoutEntry.grid(row=5, column=0)
self.label = Label(master, text=help)
self.label.config(justify=tkinter.LEFT)
self.label.grid(row=6, column=0)
self.open_button = Button(master, text="Open", command=self.openFile)
self.open_button.grid(row=0, column=1)
self.send_button = Button(master, text="Send", command=self.Send)
self.send_button.grid(row=0, column=2)
self.save_button = Button(master, text="Save", command=self.Save)
self.save_button.grid(row=0, column=3)
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.grid(row=0, column=4)
self.text = Text(master)
self.text.grid(row=1, column=1,columnspan=5, rowspan=10)
def openFile(self):
self.master.filename = filedialog.askopenfilename(initialdir="/", title="Select file",
filetypes=(("txt files", "*.txt"), ("all files", "*.*")))
print(self.master.filename)
self.text.delete(1.0, tkinter.END)
self.file = open(self.master.filename, encoding= 'utf-8')
for s in self.file.readlines():
self.text.insert(tkinter.INSERT, s)
def Save(self):
content = self.text.get(1.0, tkinter.END)
fileWrite = open(self.master.filename, 'w', encoding= 'utf-8')
fileWrite.write(content)
fileWrite.close()
def Send(self):
self.ip = self.ipEntry.get()
self.port = int(self.portEntry.get())
self.timeout = int(self.timeoutEntry.get())
print(self.ip, self.port, self.timeout)
content = self.text.get(1.0, tkinter.END)
content = str(content)
lines = content.splitlines()
print(content)
root = Tk()
my_gui = MyFirstGUI(root)
root.geometry("600x400") # 设置窗口大小 注意:是x 不是*
root.mainloop() |
4282b9070d25009eba5a1450b4ea9bd82d99279c | BeholdenArt/Python-plays-Flappy-Bird | /Score.py | 1,002 | 3.5 | 4 | import pygame
pygame.init()
# Main class
class Score:
def __init__(self):
self.count = 0
self.font = pygame.font.SysFont("Consolas", 32)
self.score_x, self.score_y = 10, 40
self.gen_x, self.gen_y = 150, 10
self.pop_x, self.pop_y = 250, 40
def display_score(self, win):
class_score = self.font.render("SCORE : " + str(self.count), True, (255, 0, 0))
win.blit(class_score, (self.score_x, self.score_y))
def update_score(self):
self.count += 1
def display_pop_size(self, window, birds_len):
pop_size = self.font.render("Population : " + str(birds_len), True, (255, 0, 0))
window.blit(pop_size, (self.pop_x, self.pop_y))
pass
# Show generation number/counter
def show_generation(self, generation, win):
generation_counter = self.font.render("GEN : " + str(generation), True, (255, 0, 0))
win.blit(generation_counter, (self.gen_x, self.gen_y))
|
b5fc823983ef67f3e0e5cba0da9b7e82ff616bfd | irkartem/forfun | /homeWork/loopDetect.py | 923 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# DESCRIPTION:
# AUTHOR: [email protected] ()
# ===============================================================================
from LinkedList import LinkedList
def loop_detection(ll):
slow, fast = ll.head, ll.head
if fast and fast.next:
fast = fast.next.next
while fast and fast.next and slow is not fast:
slow, fast = slow.next, fast.next.next
if fast is None or fast.next is None:
return None
slow = ll.head
fast = fast.next.next
while fast is not slow:
fast = fast.next
slow = slow.next
return fast
ll = LinkedList([1, 2, 3, 4, 5, 6, 7, 8])
cur = sv = ll.head
while cur.next:
if cur.value == 5:
sv = cur
cur = cur.next
cur.next = sv
print(loop_detection(ll))
while cur.next:
print(cur.value)
cur = cur.next
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.