blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2ab2af6ab1a063d85753251cd3a7e7575f4a40c2 | k-j-m/KenGen | /kengen/model.py | 4,931 | 3.734375 | 4 | class Model(object):
def __init__(self, classes, package):
self.classes = classes
self.package = package
class ClassElement(object):
"""
ClassElement class contains a description of a class in our data
model.
Please note that I've made sure to keep this class completely unaware
of the format of the model. Please don't let the xml (or replacement format)
slip in here.
Note:
We don't currently support user classes with generics/type-parameters.
"""
def __init__(self, name, attrs, extends, class_parameters, isabstract):
"""
All values are set in the constructor and must be read by the parser.
"""
self.name = name
self.attrs = attrs
self.extends = extends
self.class_parameters = class_parameters
self.isabstract = isabstract
def get_precedents(self):
"""
Returns a list of all types that are referenced by this class.
This is especially important when generating the python code
since the python classes need to be written in an order such that
all classes are read by the interpreter before they are referenced.
"""
precedents=[]
if not self.extends is None:
precedents.append(self.extends)
for type_ref in self.attrs.values():
precedents.extend(type_ref.get_precedents())
return precedents
class TypeRef(object):
"""
This class is the nuts-and-bolts of our type-system.
It contains the type name and a {name:type_ref} dict
of all nested type parameters. An example of this is a
list where all of the items must be of a certain type.
In Java-speak: List<Integer> or Map<String,Double>
"""
def __init__(self, type_, type_params=[]):
"""
Value constructor.
All of the info needs to be parsed from the data model by code
in another module. That is not the job here!
"""
self.type_ = type_
self.type_params = type_params
def get_precedents(self):
"""
Returns a list of all types that need to be available
to be able to use this type (including the top level
type itself and the types of any nested attributes).
"""
precedents = [self.type_]
for tp in self.type_params:
print tp[1]
precedents.extend(tp[1].get_precedents())
return precedents
def __repr__(self):
return 'TypeRef(%s, %s)'%(self.type_, repr(self.type_params))
def order_classes(classes):
"""
Function orders classes such that they can be written with
no classes being referenced before they are read by the interpreter.
Note that this will raise an error in the following 2 cases:
+ Circular dependencies
+ Mistakenly underfined types
"""
unsorted_classes = classes[:]
sorted_classes = []
custom_types=[]
for _ in range(len(classes)):
nxt_class,unsorted_classes = find_resolved_class(unsorted_classes,custom_types)
sorted_classes.append(nxt_class)
custom_types.append(nxt_class.name)
return sorted_classes
def find_resolved_class(classes, custom_types):
"""
Takes a list of classes and a list of already-defined custom_types
and returns a class with no unresolved dependencies and a list
of the remaining classes.
"""
assert len(classes) > 0, 'Trying to find a class in an empty list...'
ok_classes = [c for c in classes
if class_is_resolved(c, custom_types)]
if len(ok_classes) == 0:
raise Exception("Can't find any resolved classes. Check for circular dependencies or undefined types.")
classes2=classes[:]
classes2.remove(ok_classes[0])
return ok_classes[0],classes2
def class_is_resolved(cls_elem, custom_types):
"""
Returns true of the given class element doesn't require
any data types that are not in the builtins or the list
of custom_types passed in as the 2nd argument.
"""
precedents = cls_elem.get_precedents()
def check_type(type_name):
return type_is_resolved(type_name, custom_types)
return all(map(check_type, precedents))
# This is NASTY! This is meant to be language neutral in here
# I guess I need to add some language specific (but not library
# specific) utility modules.
# A list of what builtin data types we support.
python_primitives = ['float','int','string','boolean']
python_structures = ['List', 'Map']
def type_is_resolved(type_name, custom_types):
"""
Returns true of the given type_name is found either in
the builtins or the list of custom_types passed in
as the 2nd argument.
"""
return any([type_name in python_primitives,
type_name in python_structures,
type_name in custom_types])
|
5b21093884fa7272edafaabf4dfab40581f8e29e | njdevengine/nltk-exploration | /nltk-chapter-3.py | 2,568 | 3.671875 | 4 | from urllib import request
url = "http://www.gutenberg.org/files/2554/2554-0.txt"
response = request.urlopen(url)
raw = response.read().decode('utf-8')
type(raw)
len(raw)
raw[:100]
#tokenize the text, splitting all words and punctuation
import nltk, re, pprint
from nltk import word_tokenize
tokens = word_tokenize(raw)
type(tokens)
len(tokens)
tokens[:10]
#convert to nltk Text object
text = nltk.Text(tokens)
#top bigrams in the text
text.collocations()
# Method##########Functionality####################################################
# s.find(t) index of first instance of string t inside s (-1 if not found)
# s.rfind(t) index of last instance of string t inside s (-1 if not found)
# s.index(t) like s.find(t) except it raises ValueError if not found
# s.rindex(t) like s.rfind(t) except it raises ValueError if not found
# s.join(text) combine the words of the text into a string using s as the glue
# s.split(t) split s into a list wherever a t is found (whitespace by default)
# s.splitlines() split s into a list of strings, one per line
# s.lower() a lowercased version of the string s
# s.upper() an uppercased version of the string s
# s.title() a titlecased version of the string s
# s.strip() a copy of s without leading or trailing whitespace
# s.replace(t, u) replace instances of t with u inside s
#dealing with different encodings
path = nltk.data.find('corpora/unicode_samples/polish-lat2.txt')
f = open(path, encoding='latin2')
for line in f:
line = line.strip()
print(line)
# Pruska Biblioteka Państwowa. Jej dawne zbiory znane pod nazwą
# "Berlinka" to skarb kultury i sztuki niemieckiej. Przewiezione przez
# Niemców pod koniec II wojny światowej na Dolny Śląsk, zostały
# odnalezione po 1945 r. na terytorium Polski. Trafiły do Biblioteki
# Jagiellońskiej w Krakowie, obejmują ponad 500 tys. zabytkowych
# archiwaliów, m.in. manuskrypty Goethego, Mozarta, Beethovena, Bacha.
f = open(path, encoding='latin2')
for line in f:
line = line.strip()
print(line.encode('unicode_escape'))
#b'Pruska Biblioteka Pa\\u0144stwowa. Jej dawne zbiory znane pod nazw\\u0105'
#b'"Berlinka" to skarb kultury i sztuki niemieckiej. Przewiezione przez'
#b'Niemc\\xf3w pod koniec II wojny \\u015bwiatowej na Dolny \\u015al\\u0105sk, zosta\\u0142y'
#b'odnalezione po 1945 r. na terytorium Polski. Trafi\\u0142y do Biblioteki'
#b'Jagiello\\u0144skiej w Krakowie, obejmuj\\u0105 ponad 500 tys. zabytkowych'
#b'archiwali\\xf3w, m.in. manuskrypty Goethego, Mozarta, Beethovena, Bacha.'
|
fd284f5ceefa02965d794923ecac5e367e461184 | FireHo57/mud_wizard | /mudWizard/game/game_object_base.py | 277 | 3.609375 | 4 | from abc import ABCMeta
class game_object_base:
"""
This class is abstract! it makes sure that every (visible) object has
a looks like method on it.
"""
def looks_like(self):
raise NotImplementedError( "You haven't implemented looks_like()!" )
|
26f3a1474e7b23a69abcc233bac02684266a1c67 | Tomek189/day2 | /Zmiennap.py | 179 | 3.796875 | 4 | a=3
b=4
x=b/(2.0+a)
print("zmienna a:{} zmienna b:{}".format(a,b))
print("{:.17}".format(x))
print(True)
print(False)
print (True==True)
print(True!=False)
print(True!=False)
|
f7d79acd5833d909c9fb4f81268da7f5b5f58994 | Rahix/frequency-bands | /gen_data.py | 1,113 | 4 | 4 | # Simple python script to add new entries
def gen_entry():
ob = input("Operating Band: ")
ul = input("Uplink(UL) lower: ")
uu = input("Uplink(UL) upper: ")
dl = input("Downlink(DL) lower: ")
du = input("Downlink(DL) upper: ")
dm = input("Duplex Mode: ")
ne = input("Note(Leave empty for no note): ")
if ne == "":
ne = "-"
return ",".join([ob, ul, uu, dl, du, dm, ne])
print("""Add frequency band to list:
Information:
- Uplink lower = F UL_low
- Uplink upper = F UL_high
- Downlink lower = F DL_low
- Downlink upper = F DL_high
- If only one band is used set the values for Uplink to the same as Downlink
""")
while True:
entry = gen_entry()
r = input("Is the above data correct(Y/N)?")
if r == "Y" or r == "y" or r == "":
f = open("data/fb.csv", "a")
f.write(entry + "\n")
f.close()
print("Entry written.")
else:
print("Please enter again!")
continue
r = input("Do you want to enter another frequency band(Y/N)?")
if r == "Y" or r == "y" or r == "":
continue
else:
exit()
|
f02d5df44baa691d9b8b8beb4609785764e80a46 | kaylalee44/Computing-Kids | /info_extract.py | 5,960 | 3.828125 | 4 | import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv
def jobsUpdated(file_name):
"""
Goes through a data set file and looks through all the job listings for the date it was posted. If the days posted
was 1, 7, 14, or 21 days ago, then the counter goes up. Prints out the number of jobs that were posted within the
number range.
:param file_name: name of data set file passed in
:return: number of jobs that were updated
"""
df = pd.read_csv(file_name)
url_column = df["IndeedJobListingURL"] # gets url column from .csv file
urls = url_column.tolist()
num_last_updated = 0
base_url = 'https://www.indeed.com/'
job_num = 1
for url in urls:
if (job_num == 1):
print("Checking first 10 jobs...")
elif ((job_num % 10) == 0):
print("Checking next 10 jobs...")
html = urlopen(base_url + url) # connects to url
soup = BeautifulSoup(html.read(), features="lxml") # gets html
last_updated_days = soup.find('div', attrs={'class': 'jobsearch-JobMetadataFooter'}).text # text
for s in last_updated_days.split(): # extracting number
if s.isdigit():
days = int(s)
# print(days)
if (days == 1 or days == 7 or days == 14 or days == 21):
num_last_updated += 1
job_num += 1
return (str(num_last_updated) + " jobs were updated 1, 7, 14, or 21 days ago" + "\n")
# test = jobsUpdated("indeedJobs_WA_computerprogrammer_entrylevel.csv")
# print(test)
def companyCount(file_name):
"""
Goes through the data set passed in and creates a data frame of all the companies and a count of each company.
:param file_name: name of data set file passed in
:return: data frame of all the companies and the counts for them
"""
df = pd.read_csv(file_name)
company_column = df["Company"] # gets company column from .csv file
companies = company_column.tolist()
count = {}
for company in companies:
if company not in count:
count[company] = 1
else:
count[company] = count.get(company, 0) + 1
df = pd.DataFrame.from_dict(count, orient='index', columns=['Count'])
df.index.name = 'Company'
df = df.sort_values(by=['Count'], ascending=False)
return df
test1 = companyCount("indeedJobs_WA_computerprogrammer_entrylevel.csv")
print(test1)
# test1.to_csv("test.csv")
def locationCount(file_name):
"""
Goes through the data set passed in and creates a data frame of all the location cities and states and a count for
each location.
:param file_name: name of data set file passed in
:return: data frame of all the locations and the counts for them
"""
df = pd.read_csv(file_name)
locationstate_column = df["LocationState"] # gets location state column from .csv file
locationstate = locationstate_column.tolist()
locationcity_column = df["LocationCity"]
locationcity = locationcity_column.tolist()
count = {}
for i in range(0, len(locationcity)):
location = str(locationcity[i]) + ", " + str(locationstate[i])
if location not in count:
count[location] = 1
else:
count[location] = count.get(location, 0) + 1
df = pd.DataFrame.from_dict(count, orient='index', columns=['Count'])
df.index.name = 'Location'
df = df.sort_values(by=['Count'], ascending=False)
return df
test2 = locationCount("indeedJobs_WA_computerprogrammer_entrylevel.csv")
print(test2)
# test2.to_csv("test.csv")
def countJobType(file_name):
"""
Goes through the data set and creates a data frame of all the job types and a count for each job type.
:param file_name: name of data set file passed in
:return: data frame of all the job types and the counts for them
"""
df = pd.read_csv(file_name)
jobtype_column = df["JobType"]
jobtype = jobtype_column.tolist()
count = {}
for type in jobtype:
if type not in count:
count[type] = 1
else:
count[type] = count.get(type, 0) + 1
df = pd.DataFrame.from_dict(count, orient='index', columns=['Count'])
df.index.name = 'JobType'
df = df.sort_values(by=['Count'], ascending=False)
return df
test2 = countJobType("indeedJobs_WA_software_internship_entrylevel.csv")
print(test2)
# test2.to_csv("test.csv")
def countSalary(file_name):
"""
Goes through the data set and identifies how many jobs have salaries attached and how many don't. Also, identifies
all possible options of the salary units and converts all salaries to the same unit (hourly).
:param file_name: name of data set file passed in
:return: a string with details on how many jobs have salaries and how many don't.
"""
df = pd.read_csv(file_name)
minsalary_column = df["MinimumSalary"]
min = minsalary_column.tolist()
min_null = minsalary_column.isnull()
maxsalary_column = df["MaximumSalary"]
max = maxsalary_column.tolist()
max_null = maxsalary_column.isnull()
salaryunits_column = df["SalaryTimeUnits"]
salaryunits = salaryunits_column.tolist()
units = []
for unit in salaryunits:
if unit not in units:
units.append(unit)
print(units)
withSalary = 0
withoutSalary = 0
print(min)
for i in range(0, len(min)):
if min_null[i] and max_null[i]:
withoutSalary += 1
else:
withSalary += 1
# if salaryunits[i] != "Hourly":
# min[i] = int(min[i]) / 2080
# max[i] = int(max[i]) / 2080
# print(min)
return "There are " + str(withSalary) + " jobs with salaries attached and " + str(withoutSalary) + \
" without salaries attached."
test3 = countSalary("indeedJobs_WA_computerprogrammer_entrylevel.csv")
print(test3)
# test3.to_csv("test.csv")
|
c68ca2b8fbd9f772b509bda0cb4a226e94bac90d | kaylalee44/Computing-Kids | /test.py | 757 | 3.515625 | 4 | import requests
from urllib.request import urlopen
import re
from bs4 import BeautifulSoup
url = "https://www.indeed.com/jobs?q=data+scientist&l=WA&explvl=entry_level&start={}"
# page_response = requests.get(url, timeout=3)
# soup = BeautifulSoup(page_response.content, 'html.parser')
html = urlopen(url) #connects to url
soup = BeautifulSoup(html.read(), features="lxml") #gets html
num_jobs_area = soup.find(id = 'searchCount').string
job_numbers = re.findall('\d+', num_jobs_area) # Extract the total jobs found from the search result
if len(job_numbers) >= 3: # Have a total number of jobs greater than 1000
total_num_jobs = (int(job_numbers[1]) * 1000) + int(job_numbers[2])
else:
total_num_jobs = int(job_numbers[1])
print(total_num_jobs) |
3b563267fbc6c016985e4b8c7e5c657b7cd0f2e3 | OctopusHugz/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/1-last_digit.py | 282 | 3.8125 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
ld = abs(number) % 10
if number < 0:
ld = -ld
print("Last digit of {:d} is {:d} and is ".format(number, ld), end='')
print("greater than 5" if ld > 5 else "0"
if ld == 0 else "less than 6 and not 0")
|
3d57998b7d52f7ff65567e000ca0eb6aefec57b3 | OctopusHugz/holbertonschool-higher_level_programming | /0x06-python-classes/100-singly_linked_list.py | 2,867 | 4.03125 | 4 | #!/usr/bin/python3
"""This module implements a class Node that defines a node of a singly
linked list."""
class Node:
"""This class Node assigns data and next_node."""
def __init__(self, data, next_node=None):
"""This function initializes an instance of the Node class and assigns
the public attribute size to the instance if size is the correct int type. It
then assigns the public attribute position once it's validated."""
self.data = data
self.next_node = next_node
@property
def data(self):
"""This getter function gets the data attribute of the instance
and returns it"""
return self.__data
@data.setter
def data(self, value):
"""This setter function validates the data argument given at instantiation.
If valid, it sets the private data attribute for the instance."""
if isinstance(value, int):
self.__data = value
else:
raise TypeError("data must be an integer")
@property
def next_node(self):
"""This getter function gets the next_node attribute of the instance
and returns it"""
return self.__next_node
@next_node.setter
def next_node(self, value):
"""This setter function sets the next_node attribute to None, the value
passed to the function, or raises a TypeError if those fail"""
if value is None:
self.__next_node = None
elif isinstance(value, Node):
self.__next_node = value
else:
raise TypeError("next_node must be a Node object")
class SinglyLinkedList:
"""This class SinglyLinkedList assigns head to None and adds
Node instances through sorted_insert()."""
def __init__(self):
"""This function initializes an instance of the SinglyLinkedList class and
assigns the private attribute head to None."""
self.__head = None
def __str__(self):
"""This function prints the string representation of the SLL"""
string = ""
tail = self.__head
while tail:
string += str(tail.data)
if tail.next_node:
string += "\n"
tail = tail.next_node
return string
def sorted_insert(self, value):
"""This function determines the correct positioning of the new Node
instance and creates it at that position"""
if self.__head is None:
self.__head = Node(value)
return
else:
tail = self.__head
if value < tail.data:
self.__head = Node(value, tail)
return
while tail and tail.next_node:
temp = tail
tail = tail.next_node
if value < tail.data:
temp.next_node = Node(value, tail)
return
tail.next_node = Node(value)
|
7d5484155698ffad5a8413aed26d70e69a627db6 | OctopusHugz/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 3,748 | 3.796875 | 4 | #!/usr/bin/python3
"""This module implements the Base class"""
import json
import os
import csv
class Base:
"""This is the Base class's instantiation"""
__nb_objects = 0
def __init__(self, id=None):
"""This function creates the Base instance"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
@staticmethod
def to_json_string(list_dictionaries):
"""This function returns the JSON string representation of
list_dictionaries"""
if list_dictionaries is None:
return "[]"
return json.dumps(list_dictionaries)
@classmethod
def save_to_file(cls, list_objs):
"""This function writes the JSON string representation of list_objs
to a file"""
filename = cls.__name__ + ".json"
new_list = []
with open(filename, "w") as fp:
if list_objs is None:
fp.write("[]")
else:
for objs in list_objs:
new_list.append(cls.to_dictionary(objs))
fp.write(cls.to_json_string(new_list))
@staticmethod
def from_json_string(json_string):
"""This function returns the list of the JSON string representation"""
new_list = []
if json_string is None:
return new_list
else:
return json.loads(json_string)
@classmethod
def create(cls, **dictionary):
"""This function returns an instance with all attributes already set"""
new_inst = cls.__new__(cls)
if cls.__name__ == "Rectangle":
new_inst.__init__(42, 98)
elif cls.__name__ == "Square":
new_inst.__init__(42)
new_inst.update(**dictionary)
return new_inst
@classmethod
def load_from_file(cls):
"""This function returns a list of instances"""
filename = cls.__name__ + ".json"
new_list = []
if not os.path.isfile(filename):
return new_list
with open(filename) as fp:
json_string = fp.read()
cls_list = cls.from_json_string(json_string)
for items in cls_list:
new_inst = cls.create(**items)
new_list.append(new_inst)
return new_list
@classmethod
def save_to_file_csv(cls, list_objs):
"""This functions saves a list of objects to a CSV file"""
r_fields = ['id', 'width', 'height', 'x', 'y']
s_fields = ['id', 'size', 'x', 'y']
filename = cls.__name__ + ".csv"
new_list = []
with open(filename, "w") as fp:
if cls.__name__ == "Rectangle":
dict_writer = csv.DictWriter(fp, fieldnames=r_fields)
elif cls.__name__ == "Square":
dict_writer = csv.DictWriter(fp, fieldnames=s_fields)
dict_writer.writeheader()
for objs in list_objs:
dict_writer.writerow(objs.to_dictionary())
@classmethod
def load_from_file_csv(cls):
"""This functions loads a list of objects from a CSV file"""
fields = []
rows = []
new_dict = {}
new_list = []
key = ""
filename = cls.__name__ + ".csv"
with open(filename) as fp:
reader = csv.reader(fp)
fields = next(reader)
for row in reader:
rows.append(row)
for row in rows:
i = 0
new_dict = new_dict.fromkeys(fields)
for attr in fields:
key = fields[i]
value = row[i]
new_dict[key] = value
i += 1
new_list.append(cls.create(**new_dict))
return new_list
|
84c103cbb20b0f72d368d731eef4dcec402d872e | OctopusHugz/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_rectangle.py | 3,023 | 3.6875 | 4 | #!/usr/bin/python3
"""This module implements the TestRectangle class"""
import unittest
# from models.base import Base
from models.rectangle import Rectangle
class TestRectangle(unittest.TestCase):
"""This is an instance of the TestRectangle class"""
def test_rectangle_instantiation(self):
"""This function tests the setting of id attribute"""
r1 = Rectangle(10, 2)
self.assertEqual(r1.width, 10)
self.assertEqual(r1.height, 2)
r2 = Rectangle(10, 2, 0, 0, 12)
self.assertEqual(r2.x, 0)
self.assertEqual(r2.y, 0)
self.assertEqual(r2.id, 12)
r3 = Rectangle(10, 2, 42, 98, 12)
self.assertEqual(r3.x, 42)
self.assertEqual(r3.y, 98)
self.assertEqual(r3.id, 12)
self.assertEqual(r3.__str__(), "[Rectangle] (12) 42/98 - 10/2")
r4 = Rectangle(10, 2, 42, 98, -12)
self.assertEqual(r4.id, -12)
self.assertEqual(r4.area(), 20)
r5 = Rectangle(1, 1, 1, 1, 1)
r5.update(13, 22, 42, 98, 140)
self.assertEqual(r5.id, 13)
self.assertEqual(r5.width, 22)
self.assertEqual(r5.height, 42)
self.assertEqual(r5.x, 98)
self.assertEqual(r5.y, 140)
r6 = Rectangle(1, 1, 1, 1, 1)
r6.update(x=98, height=42, y=140, id=13, width=22)
self.assertEqual(r6.id, 13)
self.assertEqual(r6.width, 22)
self.assertEqual(r6.height, 42)
self.assertEqual(r6.x, 98)
self.assertEqual(r6.y, 140)
r6_dict = r6.to_dictionary()
self.assertEqual(
r6_dict, {'x': 98, 'y': 140, 'id': 13, 'height': 42, 'width': 22})
# json_dict = Base.to_json_string([r6_dict])
# r5 = Rectangle(2, 2)
# self.assertEqual(r5.display(), "#""#""\n""#""#")
# r6 = Rectangle(2, 2, 2, 2)
# self.assertEqual(r6.display(), "\n""\n"" "" ""#""#""\n"" "" ""#""#")
with self.assertRaises(TypeError):
r1 = Rectangle()
with self.assertRaises(TypeError):
r1 = Rectangle(42)
with self.assertRaises(TypeError):
r1 = Rectangle(-42)
with self.assertRaises(TypeError):
r1 = Rectangle(None)
with self.assertRaises(TypeError):
r1 = Rectangle("holbie")
with self.assertRaises(TypeError):
r1 = Rectangle("holbie", 98)
with self.assertRaises(TypeError):
r1 = Rectangle(42, "holbie")
with self.assertRaises(TypeError):
r1 = Rectangle(42, 98, "holbie", 0)
with self.assertRaises(TypeError):
r1 = Rectangle(42, 98, 0, "holbie")
with self.assertRaises(ValueError):
r1 = Rectangle(-42, 98)
with self.assertRaises(ValueError):
r1 = Rectangle(42, -98)
with self.assertRaises(ValueError):
r1 = Rectangle(42, 98, -1, 0)
with self.assertRaises(ValueError):
r1 = Rectangle(42, -98, 0, -1)
if __name__ == "__main__":
unittest.main()
|
c621bf99110cfda89e2b6196bd363155569883eb | OctopusHugz/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 279 | 3.546875 | 4 | #!/usr/bin/python3
"""This module implements the load_from_json_file function"""
import json
def load_from_json_file(filename):
"""This function loads a JSON object from a file filename"""
with open(filename) as fp:
text = fp.read()
return json.loads(text)
|
ab64f97d2ab84c34fe1af4c973abba878038559b | OctopusHugz/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-from_json_string.py | 231 | 3.5 | 4 | #!/usr/bin/python3
"""This module implements the from_json_string function"""
import json
def from_json_string(my_str):
"""This function returns the Python object represented
by a JSON string"""
return json.loads(my_str)
|
379f87707f737e0b2daabbff27120cd6767fbbe7 | dgoffredo/pattern | /pattern.py | 8,376 | 3.765625 | 4 | """simple pattern matching"""
from collections import defaultdict
import collections.abc as abc
def match(pattern, subject):
"""whether `subject` matches `pattern`"""
return Matcher()(pattern, subject)
class Matcher:
def __init__(self, num_variables=0):
self.vars = tuple(Variable() for _ in range(num_variables))
self.matched = False
def __iter__(self):
yield self
yield self.vars
def variables(self):
return self.vars
def values(self):
for var in self.vars:
yield var.value
def __bool__(self):
return self.matched
def __call__(self, pattern, subject):
self.matched = False # for starters
if any(count > 1 for var, count in _count_variables(pattern).items()):
raise Exception('Pattern contains one or more variables that '
'appear more than once. Each variable may appear '
'at most once in a pattern.')
self.matched, bindings = _match(pattern, subject)
if self.matched:
for var, value in bindings.items():
var.value = value
return self.matched
def _is_listy(value):
"""whether `value` is a sequence, but not a `str` or similar."""
return ( isinstance(value, abc.Sequence) and
not isinstance(value, abc.ByteString) and
not isinstance(value, str))
def _count_variables(pattern):
counts = defaultdict(int)
def visit(pattern):
if isinstance(pattern, Variable):
counts[pattern] += 1
visit(pattern.pattern)
elif isinstance(pattern, abc.Set) or _is_listy(pattern):
for subpattern in pattern:
visit(subpattern)
elif isinstance(pattern, abc.Mapping):
for key, value in pattern.items():
visit(key)
visit(value)
visit(pattern)
return counts
def _are_similar(left, right):
"""whether either of `left` and `right` is derived from the other"""
return isinstance(left, type(right)) or isinstance(right, type(left))
def _match(pattern, subject):
if isinstance(pattern, abc.Set):
if not isinstance(subject, abc.Set) or len(subject) < len(pattern):
return False, {}
else:
return _match_set(pattern, subject)
elif isinstance(pattern, abc.Mapping):
if not isinstance(subject, abc.Mapping) or len(subject) < len(pattern):
return False, {}
else:
return _match_mapping(pattern, subject)
elif _is_listy(pattern):
# of similar types (e.g. distinguish between tuple and list, but not
# between tuple and NamedTuple).
if not _are_similar(subject, pattern):
return False, {}
# of the same length
if len(subject) != len(pattern):
return False, {}
else:
return _match_sequence(pattern, subject)
elif isinstance(pattern, type):
if isinstance(subject, pattern):
return True, {}
else:
return False, {}
elif isinstance(pattern, Variable):
matched, bindings = _match(pattern.pattern, subject)
if matched:
bindings[pattern] = subject
return matched, bindings
elif pattern is ANY:
return True, {}
else:
return subject == pattern, {}
def _match_sequence(pattern, subject):
assert _is_listy(pattern)
assert _is_listy(subject)
assert len(pattern) == len(subject)
combined_bindings = {}
for subpattern, subsubject in zip(pattern, subject):
matched, bindings = _match(subpattern, subsubject)
if not matched:
return False, {}
combined_bindings.update(bindings)
return True, combined_bindings
def _match_unordered(pattern, subject):
# This code is common to matching Sets and Mappings (e.g. sets and dicts)
# We assume that the input `pattern` and `subject` are iterables of
# distinct (either by key or by value, depending on the caller) values.
used = set() # set of subject indices currently "taken" by a pattern index
pattern_list = list(pattern) # in some order
# `table` is all combinations of matching between subject elements and
# pattern elements.
table = [[_match(pat, sub) for sub in subject] for pat in pattern_list]
# Before trying all possible combinations of pattern/subject match
# assignments, sort the patterns in order of increasing matchness, so that
# highly constrained patterns are likely to fail early, avoiding
# unnecessary work.
num_matches = [(sum(matched for matched, _ in column), p) for p, column in enumerate(table)]
num_matches.sort()
# `num_matches` now contains the new `pattern_list` order. Now reorder
# `pattern_list` and `table` accordingly.
pattern_list = [pattern_list[p] for _, p in num_matches]
table = [table[p] for _, p in num_matches]
p = 0 # index into `pattern_list`
s = [0 for _ in pattern_list] # index corresponding to a subject in
# `table` for a given `p`
while True:
if p == len(pattern_list):
# All pattern elements have found distinct matching subject
# elements, so we're done.
combined_bindings = {}
for pattern_index in range(len(pattern_list)):
subject_index = s[pattern_index]
matched, bindings = table[pattern_index][subject_index]
assert matched
combined_bindings.update(bindings)
return True, combined_bindings
if s[p] == len(subject):
# We've run out of possible subjects to match the current pattern.
# Backtrack to the previous pattern and see if it will match a
# different pattern, this possibly freeing up a subject for this
# pattern to match.
if p == 0:
# ...unless, of course, there's no subject to go back to. Then
# there is no match overall.
return False, {}
# reset me (since we're going back to the previous pattern)
s[p] = 0
# and go back to the previous pattern
p -= 1
used.remove(s[p])
s[p] += 1
continue
if s[p] in used:
# Even if the current pattern element matches the current subject
# element, the subject element is already "taken" by a previous
# pattern element, so try another subject element.
s[p] += 1
continue
matched, bindings = table[p][s[p]]
if not matched:
# The current pattern element does not match the current subject
# element, so try another subject element.
s[p] += 1
continue
# We have a partial match consistent with previous partial matches.
# Mark the matching subject element "used" and carry on to the next
# pattern element.
used.add(s[p])
p += 1
# Program execution can't reach here.
def _match_set(pattern, subject):
assert isinstance(pattern, abc.Set)
assert isinstance(subject, abc.Set)
assert len(pattern) <= len(subject)
return _match_unordered(pattern, subject)
def _match_mapping(pattern, subject):
assert isinstance(pattern, abc.Mapping)
assert isinstance(subject, abc.Mapping)
assert len(pattern) <= len(subject)
return _match_unordered(pattern.items(), subject.items())
class _Symbol:
"""A `_Symbol` is a distinct value that displays with a specified name."""
def __init__(self, name):
self._name = name
def __repr__(self):
return f'<{self.__module__}.{self._name}>'
ANY = _Symbol('ANY')
UNMATCHED = _Symbol('UNMATCHED')
class Variable:
def __init__(self):
self.pattern = ANY
self.value = UNMATCHED
def __getitem__(self, pattern):
self.pattern = pattern
return self
def __repr__(self):
if self.value is UNMATCHED:
# Use the default __repr__
return object.__repr__(self)
else:
return f'<{self.__module__}.{type(self).__name__} value={repr(self.value)}>'
|
c10ae32a117863a4df1df1d4a2666f0caa8e943e | MetalSeed/python3_demo2 | /base_syntax/base/the_list.py | 499 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-04-26 21:39:07
# @Author : MetalSeed (=.=)
# @Link :
# @Version : $Id$
classmates = ['Michael', 'Bob', 'Tracy']
print('len(classmates) =', len(classmates))
print('classmates[0] =', classmates[0])
print('classmates[2] =', classmates[2])
print('classmates[-1] =', classmates[-1])
classmates[1] = 'Sarah'
classmates.append('Adam')
classmates.pop()
classmates.insert(1, 'Jack')
classmates.pop(1)
print('classmates =', classmates)
|
3ce4f43aeb0732eddd88177beb3a5c55e99c9a86 | darshanmest47/Pythonoops | /oops/methodoverloading.py | 562 | 3.875 | 4 | # In Python a method is said to be overloaded if it can perform multiple tasks
# General method overloading example (not supported in python)
class Methodover:
def one(self,num1):
print(num1)
def one(self,num1,num2):
print(num1,num2)
def one(self,num1,num2,num3):
print(num1,num2,num3)
mo = Methodover()
mo.one(2)
#o/p
# Traceback (most recent call last):
# File "E:/pyoops/oops/methodoverloading.py", line 17, in <module>
# mo.one(2)
# TypeError: one() missing 2 required positional arguments: 'num2' and 'num3'
|
835584228978e6a4f5275ef9c4f4635683348dec | darshanmest47/Pythonoops | /oops/methodoverpython.py | 527 | 3.609375 | 4 | # method overloading python style
class Methodovpython:
def results(self, num1=None, num2=None, num3=None, num4=None):
if num1 != None and num2 != None and num3 != None and num4 != None:
return num1 + num2 + num3 + num4
elif num1 != None and num2 != None and num3 != None:
return num1 + num2 + num3
elif num1 != None and num2 != None:
return num1 + num2
else:
print('requires atleast 2 args')
m = Methodovpython()
print(m.results(1,2,3))
|
2cc4cc80205a7b5350e254bb7ec0137fa33a8041 | darshanmest47/Pythonoops | /oops/sort.py | 314 | 3.65625 | 4 | list1= [1,3,2,5,100,0]
for i in range(len(list1)):
pos1 = list1.index(list1[i])
for j in range(len(list1)):
pos2= list1.index(list1[j])
if list1[i] > list1[j]:
temp = list1[pos1]
list1[pos1] = list1[pos2]
list1[pos2] = temp
else:
pass
print(list1)
# [100, 5, 3, 2, 1, 0]
|
33aa49cd41a89f73924aa29990eaa46fff43f55e | joel-jaimon/Certificate_Maker | /generate_certificates.py | 1,193 | 3.5 | 4 | #check installation of Pillow:
def install_Pillow(package):
import importlib
try:
from PIL import Image
print("PIL already installed \n")
except ImportError:
print("Pillow not installed \n Installing Pillow... (Make sure you have an active internet connection.)")
import pip
pip.main(['install', package])
install_Pillow('Pillow')
#importing required files
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
file = open("candidate_list.txt")
#Adjust you y-coordinate here
y_coordinate = 656
try:
for name in file:
name = name.rstrip()
img = Image.open("Your-Blank-Certificate/certificate.png")
width, height = img.size
draw = ImageDraw.Draw(img)
#Change Font size here, currently its set to 90
font = ImageFont.truetype("Font/j.ttf", 90)
offset = 10
x_coordinate = int(width / 2 - font.getsize(name)[0] / 2) + offset
draw.text((x_coordinate, y_coordinate), name, (255, 0, 0), font=font)
img.save("Your-Certificates/" + str(name) + ".png", "PNG")
print(f"Done For {name}")
except:
print("Woah.... Try Again") |
04a50ca364fbff8ad7367adb31625d00352f69c8 | srikanthpragada/python_14_dec_2020 | /demo/assignments/char_freq.py | 148 | 3.828125 | 4 |
s = "how do you do"
used_chars = []
for ch in s:
if ch not in used_chars:
print(f"{ch} - {s.count(ch)}")
used_chars.append(ch) |
36c15c15ede4798c5dd4fc837bd668e6371f4dc1 | srikanthpragada/python_14_dec_2020 | /demo/basics/for_demo.py | 87 | 3.5 | 4 | for n in range(1, 10):
print(n)
for n in range(10, 0, -1):
print(n, end= ' ')
|
348b24c93c33437d0431ecc6dcefd1b3056bf451 | srikanthpragada/python_14_dec_2020 | /demo/basics/factorial.py | 134 | 4.3125 | 4 | num = int(input("Enter a number :"))
fact = 1
for n in range(2, num + 1):
fact = fact * n
print(f"Factorial of {num} is {fact}") |
e4d5faad45457275d81cfe4be1e0d2fa6c9369ac | srikanthpragada/python_14_dec_2020 | /demo/funs/prime.py | 170 | 3.671875 | 4 |
def isprime(n):
for v in range(2, n//2 + 1):
if n % v == 0:
return False
return True
print(isprime(11), isprime(35), isprime(3939391113))
|
8b931447c65e8fa149b275a1c8c841b9bd534b52 | srikanthpragada/python_14_dec_2020 | /demo/funs/line_with_defaults.py | 225 | 3.578125 | 4 | def print_line(length=10, char='-'):
for n in range(length):
print(char, end='')
print_line()
print("\nSrikanth Technologies")
print_line(char='*') # Keyword arguments
print()
print_line(20, '.') # Positional
|
c3d980ccde2ec6c45f9f74eb20cc137a7e631697 | jakubsolecki/MOwNiT | /lab2/zad_6.py | 2,204 | 3.5 | 4 | import numpy as np
import time
def add_vectors(v1, v2):
if len(v1) == len(v2):
start = time.time()
for i in range(len(v1)):
v1[i] += v2[i]
end = time.time()
return v1, end - start
else:
print("You shouldn't add vectors of different lengths")
def cross_multiply_vectors(v1, v2):
if isinstance(v1, np.ndarray):
v1 = v1.tolist()
if isinstance(v2, np.ndarray):
v2 = v2.tolist()
if len(v1) == len(v2):
start = time.time()
v3 = v1[1:] + v1[:-1]
v4 = v2[1:] + v2[:-1]
v5 = []
for i in range(0, len(v3) - 1):
v5 += [v3[i]*v4[i+1] - v3[i+1]*v4[i]]
end = time.time()
return v5, end - start
else:
return "You shouldn't multiply vectors of different lengths"
def multiply_matrices(m1, m2):
if len(m1[0]) != len(m2):
return "Incorrect dimensions"
start = time.time()
m3 = np.zeros((len(m1), len(m2[0])))
for i in range(len(m1)):
for j in range(len(m2[0])):
for k in range(len(m2)):
m3[i][j] += m1[i][k] * m2[k][j]
end = time.time()
return m3, start - end
def numpy_add_vectors(v1, v2):
start = time.time()
v3 = np.add(v1, v2)
end = time.time()
return v3, end - start
def numpy_cross_multiply_vectors(v1, v2):
start = time.time()
v3 = np.cross(v1, v2)
end = time.time()
return v3, end - start
def numpy_multiply_matrices(m1, m2):
start = time.time()
r = np.dot(m1, m2)
end = time.time()
return r, end - start
a = [[12, 7, 3],
[4, 5, 6]]
b = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
c = [1, 2, 3]
d = [3, 2, 1]
print("Numpy add two vectors:", numpy_add_vectors(c, d))
print("My add two vectors:", add_vectors(c, d), "\n")
print("Numpy cross multiply two vectors:", numpy_cross_multiply_vectors(c, d), "\n")
print("My cross multiply two vectors:", cross_multiply_vectors(c, d), "\n")
print("Numpy multiply matrices: \n", numpy_multiply_matrices(a, b)[0],
"\n", numpy_multiply_matrices(a, b)[1])
print("My multiply matrices: \n", multiply_matrices(a, b)[0],
"\n", multiply_matrices(a, b)[1])
|
97a9e78a34d68244e5f4c14b3b35130d4cd82870 | jakubsolecki/MOwNiT | /lab3/zad_2.py | 965 | 3.5 | 4 | import sympy as sp
import math
from lab3.zad_1 import to_table
def lagrange_polynomial(x_values, y_values):
if len(x_values) != len(y_values):
exit("There must be exact same number of x and y values")
return -1
x = sp.symbols('x')
y = 0
for k in range(len(x_values)):
i = 1
for j in range(len(x_values)):
if j != k:
i = i*((x - x_values[j]) / (x_values[k] - x_values[j]))
y += i*y_values[k]
return sp.simplify(y)
# x_arr, y_arr, _ = to_table(0, 10, 3, math.sqrt, "sqrt(x)")
# print("Lagrange polynomial for sqrt(x):", lagrange_polynomial(x_arr, y_arr), "\n")
#
# x_arr, y_arr, _ = to_table(0, 10, 3, math.sin, "sin(x)")
# print("Lagrange polynomial for sqrt(x):", lagrange_polynomial(x_arr, y_arr), "\n")
#
# f = lambda x: x**3 + 2*x
# x_arr, y_arr, _ = to_table(0, 10, 3, f, "x^3 + 2x")
# print("Lagrange polynomial for sqrt(x):", lagrange_polynomial(x_arr, y_arr), "\n")
|
571a7eb8101ba3438e83a58b132d5d35d661625a | parwisenlared/BiologicallyInspiredCW | /Scripts/PSO_2_configurable.py | 9,170 | 3.828125 | 4 | # Import modules
import numpy as np
import random
import pandas as pd
import matplotlib.pyplot as plt
import time
import NN_2
class PSO:
def __init__(self, n_networks):
"""
The PSO object contains an input n_networks which is the number of neural networks
that are to be initialised.
networks: is a list to store the initialised networks
global_best_value: is initialised as infinity
global_best_position: gets its shape from the Neural Network's getParams function
yHat: is initialised at floating point 0. It is needed to plot a graph
yHat_l: is a list to store the yHat values that is needed to plot a graph
"""
self.neurons = int(input("Inform the number of neurons in hidden layer of NN: "))
self.n_networks = n_networks
self.networks = [NN_2.NeuralNetwork(NN_2.x,NN_2.y, self.neurons) for i in range(self.n_networks)]
self.global_best_value = float("inf")
self.global_best_position = NN_2.NeuralNetwork(NN_2.x,NN_2.y, self.neurons).getParams.shape
self.global_best_yHat = 0
def set_personal_best(self):
"""
The set_personal_best method loops through a list of networks, assisigns a
fitness_candidate which is the network's fitness. If the networks'
personal_best_value is greater that fitness_candidate; it then assigns the
personal_best_value as the fitness_candidate. It then updates the network's
personal_best_position as the network's position.
"""
for network in self.networks:
if(network.personal_best_value > network.fitness):
network.personal_best_value = network.fitness
network.personal_best_position = network.position
def get_personal_best(self):
particles_position = []
for network in self.networks:
particles_position.append(network.position)
return
# The variable informants is in each network, here I just create informants for each of them.
def set_informants(self):
for network in self.networks:
informants = random.choices(self.networks, k=3) # 3 informants for each particle
network.informants = informants
# In this funcion I am instantiating the best_value of each informant in
def set_informants_best(self):
for network in self.networks:
for informant in network.informants:
if(informant.personal_best_value > informant.fitness):
informant.informants_best_value = informant.fitness
informant.informants_best_position = informant.position
def set_global_best(self):
"""
The set_global_best method loops through a list of networks and assigns the
best_fitness_candidate to the network's fitness. If the global_best_value
is greater than the best_fitness_candidate the global_best_value is assigned as
best_fitness_candidate and the global_best_position becomes the network's position
"""
for network in self.networks:
if(self.global_best_value > network.personal_best_value):
self.global_best_value = network.personal_best_value
self.global_best_position = network.position
self.global_best_yHat = network.yHat
def get_global_best(self):
print (f"Value:{self.global_best_value}, Position: {self.global_best_position}")
def move_particles(self):
"""
The move_particles method contains: the Intertia weight(a),
Cognitive(b), Social (c) and Informants (d) weights of the PSO algorithm which can be adjusted
and affect directly the value of the velocity.
There is an extra weight value (e) that is called the Jump and is used over the whole velocity.
This method loops through a list of neural networks and stores the product of
of interia weight multiplied by network's velocity plus a random number multiplied
by the cognitive weight multiplied by the difference of the personal_best_position
of the network and network's position plus the social weight into a random number
multiplied by the difference of global_best_position of the networks and network's
position plus the weighted value of the informants best position minus the network position
in a variable called new_velocity.
This will be weighted by the jump value and then it ssigns the network's velocity
to this variable and calls the move function from the NeuralNetwork class.
"""
a = 0.5 # Intertia: proportion of velocity to be retained
b = 0.8 # Cognitive/personal velocity: proportion of personal best to be retained
c = 1 # Social velocity: proportion of the informants' best to be retained
d = 0.9 # Global: proportion of global best to be retained
e = 1 # Jump size of a particle
for network in self.networks:
new_velocity = (a*network.velocity) + (b*random.random())*\
(network.personal_best_position - network.position) +\
(c*random.random())*(network.informants_best_position - network.position) +\
(d*random.random())*(self.global_best_position - network.position)
network.velocity = e*new_velocity
network.move()
# I added the Jump (the value is 1 by the pseudocode of the book they suggest, so does not affect)
# but I think we do need to put it.
def optimise(self):
"""
The optimise method loops through a list of neural networks and:
w1: takes the first three numbers from network's position array which is then
reshaped to the dimensions of the NeuralNetwork object's W1 parameter
w2: takes the next three numbers from network's position array which is then
reshaped to the dimensions of the NeuralNetwork object's W2 parameter
b1: takes the 7th item from the array
b2: takes the 8th item from the array
and uses these variables to forward propagate the neural network with these values.
z2: is the dot product of input(x) and w1 plus bias(b1)
a2: is the activation of the z2 using the activation function in NeuralNetwork class
z3: is the dot product of a2 and W2 plus bias(b2)
yHat: is the activation of the z3 using the activation function in NeuralNetwork class
yHat_l: the yHat values are stored in a list for plotting graphs
error: is calculated by using the Mean Square Error(mse) method using the target value(y)
and predicted value(yHat). The network's fitness is updated using the error.
"""
for network in self.networks:
# by calling the methods here, the optimization is automatic and I do not need to call them outside.
# just by calling PSO(num_NN) it is done.
network.forward()
network.mse()
self.set_personal_best()
self.set_informants()
self.set_informants_best()
self.set_global_best()
self.move_particles()
# Update of weights
W1 = network.position[0:(len(network.pw1))]
W2 = network.position[(len(network.pw1)):(len(network.pw1)+len(network.pw2))]
network.W1 = np.reshape(W1,network.W1.shape)
network.W2 = np.reshape(W2,network.W2.shape)
network.b1 = network.position[len(network.position)-2]
network.b2 = network.position[len(network.position)-1]
"""
pso1.optimise()
pso1.get_global_best()
plt.figure()
yHat1 = pso1.global_best_yHat
plt.plot(NN.y,"red",yHat1,"blue")
plt.title("y,yHat")
# plt.xlabel("Iterations")
# plt.ylabel("Errors")
plt.show()
"""
if __name__ == "__main__":
pso = PSO(10)
n_iterations = 100
error_list = []
yHat = 0
# The start time to calculate how long the algorithm takes.
start = time.process_time()
# Sets the number of starting iterations/epochs
iterations = 0
while(iterations < n_iterations):
pso.optimise()
error_list.append(pso.global_best_value)
yHat = pso.global_best_yHat
iterations +=1
#the global_best_value and the time taken to execute the algorithm
print(f"GlobalBest: {pso.global_best_position} iters: {iterations} GlobalBestVal: {pso.global_best_value}")
print(f"------------------------ total time taken: {time.process_time() - start} seconds")
# Show the graph
yHat = pso.global_best_yHat
plt.figure()
plt.plot(NN_2.y,"red",yHat,"blue")
plt.xlabel("Input values")
plt.ylabel("Output values")
plt.title("Desired vs Predicted output")
plt.show()
fitness = error_list
plt.figure()
plt.plot(fitness)
plt.xlabel("Number of iterations")
plt.ylabel("Mean square error")
plt.title("Mean Square Error per iteration")
plt.show() |
c5bbd43328a8c5d6e5133d72827cbbf94c219c26 | AdaptiveStep/pokerhands | /Cards/testpairs.py | 5,930 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
import random
#Skapar en ordnad kortlek
class Cards(list):
def __init__(self,shuffled="no"):
self.pointer = 0 #used in check for wins.
#1 representerar Ess, .., 13 representerar kung
siffror = range(1,14)
# H = hjärter, R=Ruter, S=spader, T= treklöver
symboler =["♥","♦","♠","♣"] # 0,1,2,3
for r in symboler:
for s in siffror:
self.append(str(r)+str(s))
if shuffled == "shuffled":
self.shuffle()
def shuffle(self):
random.shuffle(self)
def Ntipples(self, N=2):
#check for pairs:
counter = 1
cards = self.copy()
templist =[]
for i in cards:
minilist =[]
h = cards.count("♥" + i[1:])
if h == 1:
minilist.append("♥" + i[1:])
cards.remove("♥" + i[1:])
s = cards.count("♠" + i[1:])
if s == 1:
minilist.append("♠" + i[1:])
cards.remove("♠" + i[1:])
r = cards.count("♦" + i[1:])
if r == 1:
minilist.append("♦" + i[1:])
cards.remove("♦" + i[1:])
k = cards.count("♣" + i[1:])
if k == 1:
minilist.append("♣" + i[1:])
cards.remove("♣" + i[1:])
totalt = int(h + s + r + k)
if totalt >= 2 and totalt >=N:
if N == 2 and totalt ==2 or N == 2 and totalt == 3:
templist.append(minilist)
elif N==2 and totalt ==4:
templist.append([minilist[0],minilist[1]])
templist.append([minilist[2],minilist[3]])
elif N >=3 and totalt >=3:
templist.append(minilist)
return templist
def hasPairs(self):
#check for pairs:
return len(self.Ntipples(2))>0
def hasTripples(self):
return len(self.Ntipples(3))>0
def hasQuads(self):
return len(self.Ntipples(4))>0
def hasKauk(self):
if self.hasPairs() and self.hasTripples():
return True
else:
return False
def hasLadder(self,n=5):
counter=0
cardsremaining = len(self.copy())
templist=[]
tempcards = self.copy()
tempcards.sort()
while cardsremaining > n:
if tempcards[counter] == tempcards[counter+1]-1:
counter+=1
def hasColors(self,n=5,interval="atleast"):
"""
n representerar hur många av en symbol man söker minst/mest/exakt av.
Interval kan vara någon av atleast, atmost, exact
"""
interval = str(interval)
colors = self.Colors(n,interval)
return len(colors)>0
def Colors(self,n=5,interval="atleast"):
"""
n representerar hur många av en symbol man söker minst/mest/exakt av.
Interval kan vara någon av atleast, atmost, exact
"""
counter = 1
cards = self.copy()
templist = []
interval = str(interval)
tcounter,scounter, hcounter,rcounter = 0,0,0,0
#rakna hjartan
for i in kortlek:
if "♣" in i: tcounter += 1
elif "♠" in i: scounter += 1
elif "♥" in i: hcounter += 1
elif "♦" in i: rcounter += 1
if interval == "atleast":
if tcounter >= n:
templist.append((tcounter, "♣"))
if scounter >= n:
templist.append((scounter, "♠"))
if hcounter >= n:
templist.append((hcounter, "♥"))
if rcounter >= n:
templist.append((rcounter, "♦"))
elif interval =="atmost":
if tcounter <= n:
templist.append((tcounter, "♣"))
if scounter <= n:
templist.append((scounter, "♠"))
if hcounter <= n:
templist.append((hcounter, "♥"))
if rcounter <= n:
templist.append((rcounter, "♦"))
elif interval =="exact":
if tcounter == n:
templist.append((tcounter, "♣"))
if scounter == n:
templist.append((scounter, "♠"))
if hcounter == n:
templist.append((hcounter, "♥"))
if rcounter == n:
templist.append((rcounter, "♦"))
#Skickar dock tom lista om inget har fyllts in.
return templist
## Vinster som räknas:
## Par (P), Triss (T), kåk(K),Fyrtal (F), stege (S), färg (C)
## [P,T,F,K,S,C]
## (hur många finns det av varje?)
#
#print()
#print("Pairs: ", kortlek.Pairs())
# ############ ####### SAMPLE DATA ######### ##########
loopcounter = 0
while 1:
kortlek = Cards("shuffled")
for i in range(40):
kortlek.pop()
print(kortlek)
print()
#print("Tripples: ", kortlek.Tripples())
k = 4
print("HAR,",k,"tippler: ", kortlek.Ntipples(k))
print()
q = 4
print("Dessa symboler förekommer minst", q,"antal gånger: ", kortlek.Colors(q))
print("Har",q ," färger: ", kortlek.hasColors(q))
print("HAR PAR: ", kortlek.hasPairs(), kortlek.Ntipples())
print("HAR TRISS: ", kortlek.hasTripples())
print("HAR FYRTAL: ", kortlek.hasQuads())
print("HAR FÄRG: ", kortlek.hasColors(5))
print("HAR KÅK: ", kortlek.hasKauk())
#print("This is kortlek tripples: ",kortlek.Tripples())
print(" ")
print(" ")
loopcounter +=1
print("ANTAL UTDELNINGAR: ",loopcounter,"\n -------------------")
if kortlek.hasColors(5):
break |
911d4753a01ab601346e3bc2f3b483a61d21c7ae | bspindler/python_sandbox | /classes.py | 1,180 | 4.3125 | 4 | # A class is like a blueprint for creating objects. An object has properties and methods (functions)
# associated with it. Almost everything in Python is an object
# Create Class
class User:
# constructor
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f'My name is {self.name} and I am {self.age}'
def increase_age(self):
self.age += 1
# Extends class
class Customer(User):
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
self.balance = 0
def set_balance(self, balance):
self.balance = balance
def greeting(self):
return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'
# Init user object
brad = User('Brad Traversy', 'brad@gmail.com', 37)
print(type(brad), brad)
janet = Customer('Janet Z', 'janet@gmail.com', 57)
print(type(janet), janet)
janet.set_balance(500)
print(janet.greeting())
# Access properties
print(brad.name, brad.email, brad.age)
# Run method on class
print(brad.greeting())
brad.increase_age()
print(brad.greeting()) |
87510f359917c5655e65b842d39c5e6d97656701 | kaynat149/CPS-3320 | /hangman.py | 846 | 3.9375 | 4 | from random import choice
word = choice(["Binary", "Bitmap", "Driver", "Editor", "Google",
"Laptop", "Parser", "Router", "Python", "Update"])
guessed = []
wrong = []
tries = 6
while tries > 0:
out = ""
for letter in word:
if letter in guessed:
out = out + letter
else:
out = out + "_"
if out == word:
break
print("Guess the a letter:", out)
print(tries, "chances left")
guess = input()
if guess in guessed or guess in wrong:
print("This word has been guessed already", guess)
elif guess in word:
print("GREAT JOB!")
guessed.append(guess)
else:
print("BAD GUESS!")
tries = tries - 1
wrong.append(guess)
print()
if tries:
print("GREAT JOB!", word)
else:
print("You didn't get", word)
|
7f3a1e22abc5ad919d8681847bad9097f41b631d | haitaka/mad | /src/main/python/test.py | 271 | 3.578125 | 4 |
N1 = 10
N2 = 20
M = 24
delta = 10**(-3)
def x(i):
t = i - N1
if t in range(-N1, 0):
return - float(t) / float(N1)
elif t in range(0, N2):
return float(t) / float(N2)
if __name__ == '__main__':
print([x(i) for i in range(0, N2 + N1)])
|
2a5e7d076fedc19e4dc9ad03dfbcf35826a06b67 | OncDocCoder/projects | /distance.py | 1,529 | 3.859375 | 4 | import math
blue = False
while blue == False:
dims = input('how many dimensions (2 or 3)?')
if dims == '2':
value_1 = (input('first point, x and y'))
x1, y1 = value_1.split(',')
x1, y1 = float(x1), float(y1)
value_2 = (input('second point x and y'))
x2, y2 = value_2.split(',')
x2, y2 = float(x2), float(y2)
distance_x = x2 -x1
distance_y = y2 - y1
x_sqrd = math.pow(distance_x, 2)
y_sqrd = distance_y**2
final_distance = math.sqrt(x_sqrd + y_sqrd)
print('the distance is {:.2f}'.format(final_distance))
response = input('do you want to go again y/n'.lower())
if response == 'n':
raise SystemExit
if dims == '3':
value_1 = (input('first point, x, y and z'))
x1, y1, z1 = value_1.split(',')
x1, y1, z1 = float(x1), float(y1), float(z1)
value_2 = (input('second point x, y, and Z'))
x2, y2, z2 = value_2.split(',')
x2, y2, z2 = float(x2), float(y2), float(z2)
distance_x = x2 -x1
distance_y = y2 - y1
distance_z = z2 - z1
x_sqrd = math.pow(distance_x, 2)
y_sqrd = distance_y**2
z_sqrd = math.pow(distance_z, 2)
final_distance = math.sqrt(x_sqrd + y_sqrd +z_sqrd)
print('the distance is {:.2f}'.format(final_distance))
response = input('do you want to go again y/n'.lower())
if response == 'n':
raise SystemExit |
0bf1af41e1afa7b7a5ebc0a9a08663ce138b1e8b | OncDocCoder/projects | /elipses.py | 2,593 | 3.625 | 4 | #x2/a2 + y2/b2 = 1
import matplotlib
import math
# a>b
# the length of the major axis is 2a
# the coordinates of the vertices are (±a,0)
# the length of the minor axis is 2b
# the coordinates of the co-vertices are (0,±b)
# the coordinates of the foci are (±c,0)
# , where c2=a2−b2.
#(x-h)^2/a^2 + (y-v)^2/b^2 = 1 horizontal
#center is (h, v)
#major axis is 2*a
#minor axis is 2*b
#(x-h)^2/b^2 + (y-v)^2/a^2 = 1
both_verticies = (input('do you know both verticies?'))
if both_verticies == 'y':
value_l = (input('first axis verticie, x and y'))
xl, yl = value_l.split(',')
xl, yl = float(xl), float(yl)
value_r = (input('second axis verticies, x and y'))
xr, yr = value_r.split(',')
xr, yr = float(xr), float(yr)
h = (xl + xr) / 2
a = (xr - h)
value_t = (input('upper co verticie, x and y'))
xt, yt = value_t.split(',')
xt, yt = float(xt), float(yt)
value_b = (input('lower co verticies, x and y'))
xb, yb = value_b.split(',')
xb, yb = float(xb), float(yb)
v = (yt + yb) / 2
b = (yt - v)
f = math.sqrt(a**2 - b**2)
value_f = (input('what are the foci x and y'))
if value_f == '':
pass
else:
xf, yf = valuef.split(',')
xf, yf = float(xf), float(yf)
c2 = xf ** 2
# a2 = h**2
# b2 = a2 - c2
print('the equation for the elipse is x2/',a**2, ' + y2/', b**2, ' = 1')
print('the centerpoint is ', h, ', ', v)
print('the focus is {:.2f}'.format (f))
else:
single_verticies = (input('do you know one of the verticies?'))
if single_verticies == 'y':
value_l = (input('left end point of the verticie, x and y'))
xl, yl = value_l.split(',')
xl, yl = float(xl), float(yl)
value_r = (input('right end point of the verticie, x and y'))
xr, yr = value_r.split(',')
xr, yr = float(xr), float(yr)
h = (xl + xr) / 2
a = (xr - h)
foci = (input('do you know the foci?'))
if foci == 'y':
focus_l = (input('left end point of the focus, x and y'))
flx, fly = focus_l.split(',')
flx, fly = float(flx), float(fly)
focus_r = (input('right end point of the focus, x and y'))
frx, fry = focus_r.split(',')
frx, fry = float(frx), float(fry)
f_sqrd = frx**2
b = f_sqrd - a**2
print('the equation for the elipse is x2/', a ** 2, ' + y2/', round(abs(b), 0), ' = 1')
else:
raise SystemExit
|
527d334d8909c84b131250c70d53c402556b1d30 | Manishthakur1297/Card-Game | /Card_Game.py | 5,225 | 3.953125 | 4 | import random
class Game:
# Intialize Cards and Players
def __init__(self, n):
self.size = n
self.card_names = {1: "A", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"10", 11:"J", 12:"Q", 13:"K"}
self.card_values = {"A": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "J": 11, "Q": 12, "K": 13}
self.card_quantity = dict()
self.players = [["_" for i in range(3)] for j in range(n)]
# Distribute cards to players
def distributeCards(self):
for i in range(self.size):
for j in range(3):
self.players[i][j] = self.findUniqueCard()
# Find Unique Random Card
def findUniqueCard(self):
value = random.randint(1,13)
card_name = self.card_names[value]
if card_name in self.card_quantity:
if self.card_quantity[card_name] < 4:
self.card_quantity[card_name] += 1
else:
self.findUniqueCard()
else:
self.card_quantity[card_name] = 1
return card_name
# Print Players Cards
def printCards(self):
for i,player in enumerate(self.players):
print("Player",i+1,":",player)
# Condition 1 -> 3 cards of the same number like 3,3,3
def condition1(self,player):
if len(set(player))==1:
return True
return False
# Condition 2 -> Numbers in order like 4,5,6
def condition2(self,player):
player = sorted([self.card_values[i] for i in player])
if player[0]+1==player[1] and player[1]+1==player[2]:
return True
return False
# Condition 3 -> Pair of Cards like two Kings or two 10s
def condition3(self, player):
player = sorted([self.card_values[i] for i in player])
if player[0] == player[1] or player[1] == player[2]:
return True
return False
# Condition 4 -> Maximum Sum of All 3 cards Win
def condition4(self, players):
sm = []
for i,player in enumerate(players):
tmp = 0
for j in player:
tmp+=self.card_values[j]
sm.append(tmp)
print("\n=====Players Card Sum =====")
print(sm)
mx = max(sm)
if sm.count(mx)==1:
return sm.index(mx)
else:
filter_players = [i for i in range(len(sm)) if sm[i] == mx]
return self.tieWinner(filter_players)
# Winner Function -> Check Each condition One by One
def winner(self):
tmp = [0]*self.size
tmp_count = {}
for i,v in enumerate(self.players):
if self.condition1(v):
tmp[i] = 1
if '1' not in tmp_count:
tmp_count['1'] = 1
else:
tmp_count['1'] += 1
elif self.condition2(v):
tmp[i] = 2
if '2' not in tmp_count:
tmp_count['2'] = 1
else:
tmp_count['2'] += 1
elif self.condition3(v):
tmp[i] = 3
if '3' not in tmp_count:
tmp_count['3'] = 1
else:
tmp_count['3'] += 1
if sum(tmp)==0:
return self.condition4(self.players)
else:
if '1' in tmp_count:
if tmp_count['1']>1:
filter_players = [i for i in range(len(tmp)) if tmp[i] == 1]
return self.tieWinner(filter_players)
else:
return tmp.index(1)
elif '2' in tmp_count:
if tmp_count['2']>1:
filter_players = [i for i in range(len(tmp)) if tmp[i] == 2]
return self.tieWinner(filter_players)
else:
return tmp.index(2)
elif '3' in tmp_count:
if tmp_count['3'] > 1:
filter_players = [i for i in range(len(tmp)) if tmp[i] == 3]
return self.tieWinner(filter_players)
else:
return tmp.index(3)
# Tie Winner -> Draws New Cards till Winner declared
def tieWinner(self, players):
print("\n===== Tie Condition =======\n")
print("=== Players Tie Indexes ====")
print(players)
arr = [0] * len(players)
mx = -1
for i in range(len(players)):
card_name = self.findUniqueCard()
card_value = self.card_values[card_name]
if card_name=='A':
arr[i] = 14
else:
arr[i] = card_value
if mx<arr[i]:
mx = arr[i]
print("\n==== New Cards Drawn for Each Tie Player ====");
print(arr)
count = arr.count(mx)
if count==1:
return players[arr.index(mx)]
else:
filter_players = [players[i] for i in range(len(players)) if arr[i] == mx]
return self.tieWinner(filter_players)
# Game Object
if __name__ == '__main__':
card = Game(4)
card.distributeCards()
card.printCards()
print("\nPlayer",card.winner()+1,"Wins!!")
|
ed972573af7247640ecaafc94c09b096cce1e838 | karelbondan/Intro_to_program | /1.py | 226 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 12:37:57 2020
@author: karel
"""
degrees = eval(input("Enter number= "))
radians = degrees*3.14/180
print("Degrees:", degrees)
print("Radians:", degrees*3.14/180)
|
8a8c5b36cafb18508e837b9d398c9d3516aaa5a5 | mintas123/MIW | /Class04/knn.py | 3,584 | 3.546875 | 4 | import numpy as np # for data
from matplotlib import pyplot as plt # for visualization
import math # for square root
from sklearn.preprocessing import LabelEncoder # for labeling data
from scipy.stats import mode # for voting
plt.style.use('seaborn-whitegrid')
def plot_dataset(f, l):
# Females
x0 = f[l == 0, 0]
y0 = f[l == 0, 1]
plt.plot(x0, y0, 'ok', label='all Females')
# Males
x1 = f[l == 1, 0]
y1 = f[l == 1, 1]
plt.plot(x1, y1, 'or', label='all Males')
def plot_neighbors(f, l):
x = f[:, 0]
y = f[:, 1]
k = len(f)
plt.plot(x, y, 'oy', label=f'{k} neighbors')
def plot_query(q, p):
x = q[0]
y = q[1]
label = 'Male' if p[0] == 1 else 'Female'
plt.plot(x, y, 'sg', label=f'It\'s a {label}')
print(f'Height: {x}')
print(f'Wight: {y}')
print(f'Class: {label}')
def load_data():
raw_data = []
# with open('500_Person_Gender_Height_Weight_Index.csv', 'r') as file:
with open('weight-height.csv', 'r') as file:
# Discard the first line (headings)
next(file)
# Read the data into a table
for line in file.readlines():
data_row = line.strip().split(',')
raw_data.append(data_row)
return np.array(raw_data)
def euclidean_distance(point1, point2):
sum_squared_distance = 0
for i in range(len(point1)):
sum_squared_distance += math.pow(point1[i] - point2[i], 2)
return math.sqrt(sum_squared_distance)
def manhattan_distance(point1, point2):
pass
def preprocess(raw_data):
le = LabelEncoder()
label_rows = []
features = []
labels = []
for row in raw_data:
feature_row = list(map(float, row[1:3]))
# select feature data
# label = row[0][1:-1]
label = row[0]
features.append(feature_row)
label_rows.append(label)
# transform categorical data (labels)
labels = le.fit_transform(label_rows)
return np.array(features), np.array(labels)
def knn(features, labels, query, k, distance_fn):
all_neighbors = []
for index, sample in enumerate(features):
# 1
distance = distance_fn(sample, query)
all_neighbors.append((distance, index)) # it's a tuple!
# 2
sorted_all_neighbors = sorted(all_neighbors)
# 3
k_neighbor_distances = sorted_all_neighbors[:k]
# print(np.array([labels[index] for _, index in k_neighbor_distances]))
# 4
k_labels = np.array([labels[index] for _, index in k_neighbor_distances])
k_neighbors = np.array([features[index] for _, index in k_neighbor_distances])
return k_neighbors, k_labels, mode(k_labels) # mode == voting for the class
def main():
data = load_data() # how many columns? what are they?
plt.xlabel('height [inches]')
plt.ylabel('weight [pounds]')
k = 10
features, labels = preprocess(data) # how do we split features/labels? what are we doing with N/A or '2,1'?
plot_dataset(f=features, l=labels)
query = np.array(
[70, 175]
) # what if it's a 2D array with rows as queries?
k_neighbors, k_classes, predicted_class = knn(features,
labels,
query=query,
k=k,
distance_fn=euclidean_distance) # distance
plot_neighbors(f=k_neighbors, l=k_classes)
plot_query(q=query, p=predicted_class)
plt.legend()
plt.show()
main()
|
3f30e91059cba3f37fb76224ab070c369a250611 | Demondul/python_algos | /functionIntermediateII.py | 1,057 | 3.578125 | 4 | # PART I
""" students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
for student in students:
print(str(student["first_name"]) + " " + str(student["last_name"])) """
###################
# PART II
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
for userType in users:
print(str(userType))
for user in users[userType]:
fName=str(user["first_name"])
lName=str(user["last_name"])
fullName=fName+lName
print("1 - " + fName + " " + lName + " - " + str(len(fullName)))
|
6acb4ba5dcc6ae13f0ca0552cacee774b249218f | Demondul/python_algos | /store.py | 392 | 3.53125 | 4 | import product
class Store:
def __init__(self,products,address,owner):
self.products=products
self.address=address
self.owner=owner
def add_product(item):
self.products.append(item)
def remove_product(item_name):
for item in range(0,len(self.products)):
if self.products[item].item_name == item_name:
|
c12890b5a29c284c0cd5bdc4591ea94e057ac06b | Sammyalhashe/CSC_Course_Work | /twoSum_withIceCream.py | 2,466 | 3.59375 | 4 | '''input
"2"
"4"
"5"
"1 4 5 3 2"
"4"
"4"
"2 2 4 3"
'''
class tuples2:
def __init__(self, val1, val2):
self.tupl = (val1, val2)
def comparitor(self):
return self.tupl[1]
t = int(input().strip())
for a0 in range(t):
m = int(input().strip())
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
# This next line is messy (I know), but what it does is takes the array, a, and then turns it into a sorted array
# based on the price value (the second value in the enumeration) and places the result into a 2 valued tuple object I created.
# To sort, it uses python's sorting function and sorts based on the price value (key takes a function of one paramater, in this
# case comparitor, and applies it to all elements in the list and sorts based on the result). The comparitor returns the second
# value of the tuple (the price). I then take that sorted array of tuple2
# objects, and make it look nicer.
final = list(map(lambda x: x.tupl, sorted(
[tuples2(i, j) for i, j in enumerate(a)], key=tuples2.comparitor)))
# Logic: Greedy Algorithm
# 1) Choose the largest priced item first, if it's too large, remove it as an option
# 2) If I haven't bought anything yet, try to buy one and see if you have an exact amount of money left for one of the items left
# if you don't remove it as an option
# 3) Otherwise, buy an item and subtract from the money you have available
bought = 0
ice_cream = []
while m > 0 or bought != 2:
if(final != []):
if(m < final[-1][1]):
final.pop()
else:
# Theoretically buy an ince-cream, if you can't buy anything
# else after you bought the current one you shouldn't have
# bougthen it in the first place
if(len(list(filter(lambda x: x[1] == m - final[-1][1], final[:len(final) - 1]))) == 0 and bought == 0):
final.pop()
else:
m -= final[-1][1]
bought += 1
# plus 1 due to indexing
ice_cream.append(str(final[-1][0] + 1))
final.pop() # pop because we choose distinct flavours and not the same multiple times: remove the option
else:
print("No two sum solution")
break
print(" ".join(sorted(ice_cream, key=lambda x: int(x))))
|
b92950bff370296369bee2e13b4f1e8d3cbcf79a | Sammyalhashe/CSC_Course_Work | /FindInversions.py | 1,045 | 4.09375 | 4 | def merge(left, right):
swaps = 0
result = []
i, j = 0, 0
while (len(left) > i and len(right) > j):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
swaps += len(left) - i
result.append(right[j])
j += 1
if i == len(left) or j == len(right):
result.extend(left[i:] or right[j:])
break
return result, swaps
def mergesort(lists):
if len(lists) < 2:
return lists, 0
else:
middle = (len(lists) // 2)
left, swaps0 = mergesort(lists[:middle])
right, swaps1 = mergesort(lists[middle:])
res, swaps = merge(left, right)
return res, (swaps + swaps0 + swaps1)
def countInversions(arr):
# Complete this function
sort_arr, swaps = mergesort(arr)
return sort_arr, swaps
if __name__ == '__main__':
test = [1, 32, 122, 32, 12, 311, 2, 3, 21, 2]
result, no_swaps = countInversions(test)
print("sorted array:", result, "swaps:", no_swaps)
|
7b2a85d1a6226de574ba11269572c80480f6cc9f | Sammyalhashe/CSC_Course_Work | /Merge_Sort_Pythonic.py | 1,686 | 4 | 4 | '''input
10
"12 4 19 3 2"
"2 8 9 17 7"
"2 3 15 9 4"
"16 10 20 4 17"
"18 11 7 20 12"
"19 1 3 12 9"
"13 5 7 9 6"
"9 18 3 16 10"
"16 18 6 3 9"
"1 10 14 19 6"
'''
# More pythonic implementation of merge sort
def Merge_Sort_Pythonic(array):
return mergesort_Pythonic(array)
def mergesort_Pythonic(array):
if(len(array) < 2):
return array
# Integer division for middle index
mid = ((len(array)) // 2)
# Merge-sort left and right halves
left = mergesort_Pythonic(array[:mid])
right = mergesort_Pythonic(array[mid:])
res = merge(left, right)
return res
def merge(left, right):
# size = right - left + 1 #len(temp)?
i, j, ind = 0, 0, 0
l, r = len(left), len(right)
length = l + r
temp = [0 for i in range(length)]
while(len(left) > i and len(right) > j):
if(left[i] < right[j]):
temp[ind] = left[i]
i += 1
else:
temp[ind] = right[j]
j += 1
ind += 1
# Once one of either left_ind or right_ind goes out of bounds, we have to copy into temp the rest of
# the elements
# Note: inly one of these loops will execute as one of right_ind or left_ind will have already reached
# it's boundary value
if i == len(left) or j == len(right):
temp.extend(left[i:] or right[j:])
break
return temp
if __name__ == '__main__':
test = [1, 32, 122, 32, 12, 311, 2, 3, 21, 2]
result = Merge_Sort_Pythonic(test)
print(result)
t = input()
for i in range(t):
test = list(map(lambda x: int(x), input().strip().split(' ')))
tested = Merge_Sort_Pythonic(test)
print(tested)
|
c87810a69b35215a9e8590580dd19a75ccd5029e | Sammyalhashe/CSC_Course_Work | /minimizeUnfairness.py | 1,589 | 3.890625 | 4 | """Greedy Algorithm minimizes unfairness of an array by choosing K values
unfairness == max(x0,x1,...,xk)-min(x0,x1,...,xk)
Variables:
int: N -> number of elements in list
int: K -> number of list elements to choose
list: vals -> list to minimize unfairness
Example Input:
10 (N)
4 (K)
(The Rest are list elements)
1
2
3
4
10
20
30
40
100
200
Example Output:
3 (the minimum unfairness)
"""
def calcUnfairness(reduced_array):
return (reduced_array[-1] - reduced_array[0])
def minimizeUnfairness(n, k, arr):
unfairness = (arr[k - 1] - arr[0])
if len(arr) == k or len(arr) == 1:
unfairness = calcUnfairness(arr)
else:
for i in range(1, n - (k - 1)):
if((arr[i + k - 1] - arr[i]) < unfairness):
unfairness = (arr[i + k - 1] - arr[i])
if(unfairness == 0):
break
print(unfairness)
# First Greedy Idea: Farthest from average remove and test again
# average = int(sum(arr)/len(arr))
# ldev = int(abs(arr[-1]-average))
# sdev = int(abs(arr[0]-average))
# if (ldev>=sdev):
# sorts.pop()
# return minimizeUnfairness(k,sorts)
# else:
# sorts.pop(0)
# return minimizeUnfairness(k,sorts)
if __name__ == '__main__':
N = int(input().strip())
K = int(input().strip())
vals = []
for i in range(N):
vals.append(int(input().strip()))
if(K == 0):
print("Should at least be 1")
else:
reduced_arr = minimizeUnfairness(N, K, sorted(vals)) |
304d59ca7759125373f19c497c664438c7f78b14 | DinaShaim/GB_Algorithms_data_structures | /Les_5_HomeWork/les_5_task_1.py | 2,114 | 3.515625 | 4 | # Пользователь вводит данные о количестве предприятий, их наименования и прибыль
# за 4 квартал (т.е. 4 числа) для каждого предприятия.
# Программа должна определить среднюю прибыль (за год для всех предприятий) и
# отдельно вывести наименования предприятий, чья прибыль выше среднего и ниже среднего.
from collections import Counter
print('Введите количество предприятий:')
n = int(input())
i = 0
company_array = [0]*n
total_profit = 0
for i in range(len(company_array)):
print('Введите название предприятия:')
company_name = input()
print('Введите последовательно прибыль за 4 квартала данного предприятия:')
qrt1 = input()
qrt2 = input()
qrt3 = input()
qrt4 = input()
summa_profit = int(qrt1) + int(qrt2) + int(qrt3) + int(qrt4)
company_array[i] = Counter(name=company_name, quarter_1=qrt1, quarter_2=qrt2, quarter_3=qrt3,
quarter_4=qrt4, profit=summa_profit)
total_profit += company_array[i]['profit']
average_profit = total_profit/n
print(f"Средняя прибыль за год для всех предприятий = {average_profit}.")
print()
print('Предприятия, чья прибыль выше средней:')
for i in range(len(company_array)):
if float(company_array[i]['profit']) > average_profit:
print(f"Предприятие {company_array[i]['name']} с прибылью {company_array[i]['profit']}.")
print()
print('Предприятия, чья прибыль ниже средней:')
for i in range(len(company_array)):
if float(company_array[i]['profit']) < average_profit:
print(f"Предприятие {company_array[i]['name']} с прибылью {company_array[i]['profit']}.")
|
afbb4590c1e77843dc2dbdcc20f77fa75716d2dd | DinaShaim/GB_Algorithms_data_structures | /Les_1_HomeWork/les_1_task_5.py | 811 | 3.984375 | 4 | #Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят,
# и сколько между ними находится букв.
import string
print("Введите две строчные буквы латинского алфавита от a до z:")
letter1 = str(input("первая буква = "))
letter2 = str(input("вторая буква = "))
index1 = ord(letter1) - ord("a") +1
index2 = ord(letter2) - ord("a") +1
s = abs(index1 - index2) -1
print("Буква %c является %d буквой алфавита" % (letter1, index1))
print("Буква %c является %d буквой алфавита" % (letter2, index2))
print(f'Между ними находится букв: {s}')
|
b2a620d6e016513b0c8eeddc1fdf4f48206c0e49 | DinaShaim/GB_Algorithms_data_structures | /Les_4_HomeWork/les_4_task_1.py | 8,303 | 4.3125 | 4 | # Проанализировать скорость и сложность одного любого алгоритма из разработанных
# в рамках домашнего задания первых трех уроков.
# Задание № 2 урока № 2:
# Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
# 1 Вариант
import timeit
import cProfile
even = 0 # четный
odd = 0 # нечентый
def counting_recursion(x, even=even, odd=odd):
if ((x % 10) % 2) == 0:
even = even + 1
else:
odd = odd + 1
if (x // 10) != 0:
return counting_recursion(x // 10, even=even, odd=odd)
return even, odd
# 2 Вариант
def counting_while(x, even=even, odd=odd):
while True:
if ((x % 10) % 2) == 0:
even = even + 1
else:
odd = odd + 1
x = x // 10
if not x != 0:
break
return even, odd
# 3 Вариант
def counting_list(x, even=even, odd=odd):
array_numbers = [x % 10]
while (x // 10) != 0:
x = x // 10
a = x % 10
array_numbers.append(a)
for j in range(len(array_numbers)):
if array_numbers[j] % 2 == 0:
even = even + 1
else:
odd = odd + 1
return even, odd
A1 = 1e+3
A2 = 1e+7
A3 = 1e+15
A4 = 1e+31
A5 = 1e+63
A6 = 1e+127
print(timeit.timeit('counting_recursion(A1)', number=100, globals=globals())) # 0.0009046000000000054
print(timeit.timeit('counting_recursion(A2)', number=100, globals=globals())) # 0.0020120000000000138
print(timeit.timeit('counting_recursion(A3)', number=100, globals=globals())) # 0.004119700000000004
print(timeit.timeit('counting_recursion(A4)', number=100, globals=globals())) # 0.007559099999999985
print(timeit.timeit('counting_recursion(A5)', number=100, globals=globals())) # 0.015897899999999993
print(timeit.timeit('counting_recursion(A6)', number=100, globals=globals())) # 0.0371291
print()
print(timeit.timeit('counting_while(A1)', number=100, globals=globals())) # 0.0005190999999999946
print(timeit.timeit('counting_while(A2)', number=100, globals=globals())) # 0.0009889000000000148
print(timeit.timeit('counting_while(A3)', number=100, globals=globals())) # 0.0019822999999999924
print(timeit.timeit('counting_while(A4)', number=100, globals=globals())) # 0.004015200000000024
print(timeit.timeit('counting_while(A5)', number=100, globals=globals())) # 0.009873900000000019
print(timeit.timeit('counting_while(A6)', number=100, globals=globals())) # 0.018753200000000025
print()
print(timeit.timeit('counting_list(A1)', number=100, globals=globals())) # 0.0010371999999999604
print(timeit.timeit('counting_list(A2)', number=100, globals=globals())) # 0.001844300000000021
print(timeit.timeit('counting_list(A3)', number=100, globals=globals())) # 0.0035182999999999742
print(timeit.timeit('counting_list(A4)', number=100, globals=globals())) # 0.0069190000000000085
print(timeit.timeit('counting_list(A5)', number=100, globals=globals())) # 0.015661900000000006
print(timeit.timeit('counting_list(A6)', number=100, globals=globals())) # 0.035929199999999994
# Все разработанные алгоритмы имеют линейную вычислительную сложность:
# Вариант с рекурсией пораждает вызов одной рекурсивной фукнции, что соотвествует линейной сложности O(n)
# Решение с циклом while будет реализован n раз, т.е. получаем O(n)
# Третий вариант решения цикл while пробегает n раз и формирует массив,
# далее цикл for аналогично пробегает n раз. Тогда O(n+n) = O(n), т.е. тоже линейная вычислительная сложность.
# Проведенный анализ подтверждается полученными временными значениями функции timeit,
# где с увеличением n в 2 раза, время увеличивается тоже примерно в 2 раза.
print()
cProfile.run('counting_recursion(A1)')
# 7 function calls (4 primitive calls) in 0.000 seconds
#
# Ordered by: standard name
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 0.000 0.000 0.000 0.000 <string>:1(<module>)
# 4/1 0.000 0.000 0.000 0.000 les_4_task_1.py:13(counting_recursion)
# 1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
cProfile.run('counting_recursion(A2)')
cProfile.run('counting_recursion(A3)')
cProfile.run('counting_recursion(A4)')
cProfile.run('counting_recursion(A5)')
cProfile.run('counting_recursion(A6)')
# 131 function calls (4 primitive calls) in 0.001 seconds
# Ordered by: standard name
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 0.000 0.000 0.001 0.001 <string>:1(<module>)
# 128/1 0.000 0.000 0.000 0.000 les_4_task_1.py:13(counting_recursion)
# 1 0.000 0.000 0.001 0.001 {built-in method builtins.exec}
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
print()
cProfile.run('counting_while(A1)')
cProfile.run('counting_while(A2)')
cProfile.run('counting_while(A3)')
cProfile.run('counting_while(A4)')
cProfile.run('counting_while(A5)')
cProfile.run('counting_while(A6)')
# 4 function calls in 0.000 seconds
# Ordered by: standard name
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 0.000 0.000 0.000 0.000 <string>:1(<module>)
# 1 0.000 0.000 0.000 0.000 les_4_task_1.py:25(counting_while)
# 1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
print()
cProfile.run('counting_list(A1)')
cProfile.run('counting_list(A2)')
cProfile.run('counting_list(A3)')
cProfile.run('counting_list(A4)')
cProfile.run('counting_list(A5)')
cProfile.run('counting_list(A6)')
# 132 function calls in 0.001 seconds
# Ordered by: standard name
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 0.000 0.000 0.000 0.000 <string>:1(<module>)
# 1 0.000 0.000 0.000 0.000 les_4_task_1.py:38(counting_list)
# 1 0.000 0.000 0.001 0.001 {built-in method builtins.exec}
# 1 0.000 0.000 0.000 0.000 {built-in method builtins.len}
# 127 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
# Анализируя результаты, проведенного профилирования, можно отметить, что вызовы всех функций были выполнены
# за 0.000 секунд, что говорит об отсутствии слабых (медленных) мест.
# Необходимо отметить, что в первом и третьем методах решений количество вызовов функций
# растет прямопропорционально n, что требует большего времени выполнения методов.
# Во втором алгоритме всегда происходит вызов 4 функций, что делает этот
# метод решения самым быстрым (что подтверждается вычислительными значениями функции timeit)
# и неиболее оптимальным.
|
c676c6a3e43c95656e6643a30a91120a3e3f9e4e | openseg-group/openseg.pytorch | /lib/utils/tools/average_meter.py | 626 | 3.59375 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author: Donny You (youansheng@gmail.com)
# Utils to store the average and current value.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class AverageMeter(object):
""" Computes ans stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0.
self.avg = 0.
self.sum = 0.
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
|
c9690b333c631fa91c79405707d45182ce1874f8 | Doodlebug511/hello-world | /myscraper.py | 2,412 | 3.8125 | 4 | # basic web page scraper as final project for bootcamp...
# import needed modules
import requests
from bs4 import BeautifulSoup
import pandas as pd
# bring desired webpage into python and create soup object via beautifulsoup
url = 'https://pauladeen.com/recipe/mashed-potatoes-with-sautaed-mushrooms/'
# url = 'https://pauladeen.com/recipe/hash-brown-quiche/'
# url = 'https://pauladeen.com/recipe/paulas-sugared-rose-parade-layer-cake/'
r = requests.get(url)
# parse website into soup object
soup = BeautifulSoup(r.text, 'html.parser')
# different parsers for different websites and output, these are the main ones
# soup = BeautifulSoup(r.text, 'lxml.parser')
# will need a pip install of lxml first
# soup = BeautifulSoup(r.text, 'html5lib.parser')
# pip install of html5lib first
# main container for soup object
records = []
# adding title text to records array
records.append(soup.find('title').text)
# adding spacer between texts for readability
records.append(' ')
print(soup.find('title').text)
print()
# for title of saved csv file
recipe_title = soup.find('title').text
recipe_title = str(recipe_title) + '.csv'
recipe_title = recipe_title.replace('|', '-')
# url of recipe image from soup object
pic = soup.find('img', class_='img-fluid').get('data-src')
# add url of recipe image to main container
records.append('Picture of finished dish...')
records.append(pic)
records.append(' ')
print('Picture of finished dish...')
print(pic)
print()
# create list of ingredients from soup object, add to container
records.append('Ingredients...')
ingredients = []
for results1 in soup.find_all('li', itemprop='ingredients'):
ingredients.append(results1.text)
records.append(results1.text)
records.append(' ')
print('Ingredients...')
for item in ingredients:
print(item)
print()
# create list of instructions from soup object, add to container
records.append('Directions...')
directions = []
for results in soup.find_all('p'):
directions.append(results.text)
records.append(results.text)
records.append(' ')
print('Directions...')
for item in directions:
print(item)
print()
# create data frame object out of records
df = pd.DataFrame(records)
# send to folder of source file as .csv file, open with spreadsheet app(excel)
df.to_csv(recipe_title, index=False, encoding='utf-8')
|
ec6d2983bfe00b677d39b49759406dc482e60fd0 | vankhoakmt/pyHTM | /pyhtm/support/getsetstate.py | 1,134 | 3.890625 | 4 | def GetSomeVars(self, names):
"""Grab selected attributes from an object.
Used during pickling.
Params:
names: A sequence of strings, each an attribute name strings
Returns:
a dictionary of member variable values
"""
return {i: getattr(self, i) for i in names}
def CallReader(self, readFunc, parents, state):
"""Call the function specified by name string readFunc on self
with arguments parents and state: i.e.
self.readFunc(parents, state)
Params:
self: Object to call readFunc callable on
readFunc: String name of a callable bound to self
parents: Arbitrary argument to be passed to the callable
state: Arbitrary argument to be passed to the callable
"""
getattr(self, readFunc)(parents, state)
def UpdateMembers(self, state):
"""Update attributes of self named in the dictionary keys in state
with the values in state.
Params:
self: Object whose attributes will be updated
state: Dictionary of attribute names and values
"""
for i in state.keys():
setattr(self, i, state[i])
|
b3b7bab386391dab91910d4bd64a5c094da05a94 | shwetasharma18/test_questions | /insert.py | 359 | 3.859375 | 4 | def insertion_sort(num):
i = 1
while i < len(num):
temp = num[i]
j = i - 1
while j >= 0 and temp < num[j]:
num[j+1] = num[j]
j = j -1
num[j+1] = temp
i = i + 1
return num
l = [5,7,3,9,8,2,4,1]
print insertion_sort(l) |
eba24ce1802c67d7f48289e4abd88f0084ea317b | abd124abd/algo-toolbox | /week3/1.py | 356 | 3.671875 | 4 | #python3
# money change
import sys
def get_money_change(n):
count = 0
if n <= 0: return 0
denominations = [10,5,1]
for i in denominations:
count = count + int(n / i)
n = n % i
return count
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
print(get_money_change(n))
|
3eb6094bde8eb1a842fd4cbcbd0049cb2fd81373 | abd124abd/algo-toolbox | /week2/8.py | 863 | 3.96875 | 4 | #python3
# last digit of sum of squares of fib
from sys import stdin
# last digit sum of squares at n = ((last digit at n) * (last digit at n + 1)) % 10
def last_digit_sum_squares_fib(n):
if n <= 2: return n
last_digits = last_digits_fib(n+1)
return (last_digits[0] * last_digits[1]) % 10
def last_digits_fib(n):
n = (n) % pisano_period(10)
n_one, n_two = 0, 1
for i in range(2, n+1):
n_one, n_two = n_two, (n_one + n_two) % 10
return [n_one, n_two]
def pisano_period(m):
previous, current = 0, 1
end = m * m
for i in range(end):
mod = (previous + current) % m
previous, current = current, mod
if previous == 0 and current == 1:
return i + 1
if __name__ == '__main__':
n = int(stdin.read())
print(last_digit_sum_squares_fib(n))
|
91d55ae511d7b2c47a07569496d1e55d6bbc2204 | chrispoch/adventofcode | /13.py | 1,825 | 3.5625 | 4 | import os
import sys
debug = False
fileName = ""
try:
fileName = sys.argv[1]
if len(fileName) < 1:
fileName = "13.txt"
except:
fileName = "13.txt"
print(fileName)
with open(fileName) as file:
time = int(file.readline())
note = file.readline()
note2 = note.replace(",x","")
buses = note2.split(",")
for i in range(len(buses)):
buses[i] = int(buses[i])
leaves = []
for i in range(len(buses)):
leaves.append(time + buses[i] - (time % buses[i]))
min = leaves[0]
mini = 0
for i in range(len(leaves)):
if leaves[i] < min:
min = leaves[i]
mini = i
wait = leaves[mini] - time
print(buses[mini], wait, buses[mini] * wait)
#part 2
print("Part 2")
buses = note.split(",")
#print(buses)
for i in range(len(buses)):
if buses[i] == "x":
buses[i] = 0
else:
#print(buses[i])
buses[i] = int(buses[i])
leaves = []
for bus in buses:
leaves.append(0)
time = 0
step = 1
#influenced by https://gist.github.com/joshbduncan/65f810fe821c7a3ea81a1f5a444ea81e
"""Since you must find departure times for each bus based off of the previous bus schedule (which is based on the previous bus and so on...), all following buses must depart at a multiple of all previous buses departures since they have to stay in the order provided.
Step Progression
1 * 7 = 7
7 * 13 = 91
91 * 59 = 5369
5369 * 31 = 166439
Then you just need to add the cumulative time (t) and the minute offset for each bus in the list to get the final answer."""
p2 = [(int(i), j) for j, i in enumerate(buses) if i != 0]
for bus, offset in p2:
while (time + offset) % bus != 0:
time += step
step *= bus
print(time)
|
d5dee3c68ce06e1f95046d443f68c447be0af944 | korynewton/Intro-Python-II | /src/room.py | 783 | 3.59375 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
from item import Item
class Room:
n_to = None
s_to = None
e_to = None
w_to = None
def __init__(self, name, description):
self.name = name
self.description = description
self.items = []
def __repr__(self):
string_of_items = "\n".join([str(x) for x in self.items])
return f"\nCurrent Location: {self.name}...{self.description}.\n\n \
Items availabe: \n{string_of_items}"
def add_to_room(self, item):
self.items.append(item)
print(f'**{item.name} added to room**')
def remove_from_room(self, item):
self.items.remove(item)
print(f'**{item.name} removed from room**')
|
3b4ffa6d1ced6ad6b7328cd686d6cd5868dd6b18 | KuanHsuanTiffanyLin/stanCode-project | /stanCode Projects for GitHub/breakout_game/breakout.py | 1,535 | 3.953125 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
-----------------------------------------
SC101 - Assignment 2
File: breakout.py
Name: Tiffany Lin
"""
from campy.gui.events.timer import pause
from breakoutgraphics import BreakoutGraphics
FRAME_RATE = 1000 / 120 # 120 frames per second.
NUM_LIVES = 3 # Number of times the ball can hit bottom wall before the game ends.
def main():
"""
This program creates the Breakout Game.
A ball will be bouncing around the GWindow and
bounce back if it hits the walls, paddles or the bricks.
Bricks are removed if hit by the ball.
Player can use the paddle to prevent ball from falling out of
the bottom window by moving the mouse.
The game ends if all the bricks are removed or
the ball falls out of the bottom wall for over NUM_LIVES.
"""
graphics = BreakoutGraphics()
# Add animation loop here!
lives = NUM_LIVES
while True:
pause(FRAME_RATE)
while graphics.mouse_lock is True:
if graphics.ball_out():
lives -= 1
if lives > 0:
graphics.reset_ball()
break
elif lives <= 0:
break
if graphics.brick_left == 0:
break
graphics.move_ball()
graphics.handle_collision()
pause(FRAME_RATE)
if graphics.brick_left == 0:
break
if __name__ == '__main__':
main()
|
69b7fe0a027b868cc731e45c263387893e9db832 | Tsunamicom/Hackerrank-Solutions | /FromParagraphsToSentences.py | 702 | 3.859375 | 4 | # https://www.hackerrank.com/challenges/from-paragraphs-to-sentences
sample = input()
def processSentences(text):
sentence = []
isQuote = False
charCount = 0
sentenceTerminators = ['.', '?', '!']
for character in text:
sentence.append(character)
charCount += 1
if character in sentenceTerminators:
if isQuote == False:
if charCount >= 2:
print(''.join(sentence))
charCount = 0
sentence = []
elif character == '"':
if isQuote == False:
isQuote = True
else:
isQuote == False
processSentences(sample)
|
e425c1e23f27acc4519eea7506cbaebd75e747b1 | MiaoJiawei/Python-voltage-correct | /correct.py | 606 | 3.828125 | 4 | import matplotlib.pyplot as plt
def correct_func(voltage, current, resistance):
voltage_correct = []
for i in range(len(voltage)):
voltage_correct.append(voltage[i] - (current[i] * resistance))
return voltage_correct
voltage = [8.19,2.72,6.39,8.71,4.7,2.66,3.78]
current = [7.01,2.78,6.47,6.71,4.1,4.23,4.05]
resistance = 0.6134953432516345
'''
plt.figure(figsize=(8,6))
plt.grid(alpha=0.25)
plt.xlabel('Voltage')
plt.ylabel('Current')
plt.plot(voltage, current, label='raw data')
plt.plot(voltage_correct, current, label='corrected data')
plt.legend(loc='upper left')
plt.show()
''' |
f9684d6cafaf0381618bd01423b4a7227427e665 | brunston/goeuler | /3.py | 923 | 3.828125 | 4 | """
brunston 2016
Euler 3
"""
from math import ceil, sqrt
#make is_prime only search to square root
#make main() begin with low values that % = 0, then divide n by that value to get the corresponding
# big value and test *that* value for prime-ness.
def is_prime(n):
if n % 2 == 0:
return True
else:
for i in range(3,ceil(sqrt(n)),2):
#print("now dividing "+str(n)+" by "+str(i))
if (n % i) == 0:
return False
return True
def main():
n = 600851475143
limit_of_search = ceil(sqrt(n))
highest_prime_factor = 2
for i in range(n-2,limit_of_search,-2):
if n % i == 0:
print("found candidate"+str(i))
if (is_prime(i) == True):
highest_prime_factor = i
break
print(highest_prime_factor)
return highest_prime_factor
if __name__ == '__main__':
main()
|
d17ec96b85f652027381ee14c761ecd15758e829 | sadipgiri/Sensor-DashBoard | /sensor_api.py | 2,619 | 3.59375 | 4 | #!/usr/bin/env python3
"""
sensor_api - python3 program to return sensor readings hitting the given endpoints
Author: Sadip Giri (sadipgiri@bennington.edu)
Created: 15 May, 2018
"""
import re
import requests
import json
def last_hour_sensor_data():
try:
req = requests.request('GET', 'http://54.197.182.144:5000/read/last_hour')
json_data = req.json()
return json_data
except Exception as e:
return offline_sensor_data()
def particular_sensor_data(id=1):
if id:
try:
req = requests.request('GET', 'http://54.197.182.144:5000/read/{0}'.format(id))
json_data = req.json()
return json_data["data"]
except Exception as e:
return offline_sensor_data()
try:
req = requests.request('GET', 'http://34.201.69.120:5000/read/1')
json_data = req.json()
return json_data["data"]
except Exception as e:
return offline_sensor_data()
def offline_sensor_data():
with open('./offline_data/sensor_readings.json') as json_file:
json_data = json.load(json_file)
sensor_readings = json_data
return sensor_readings
def dict_of_sensors_list(data):
temps = []
humids = []
timestamps = []
for i in data:
temps.append(i["data"]["temperature"]["value"])
humids.append(i["data"]["humidity"]["value"])
timestamps.append(i["timestamp"])
dicts = {"temps": temps, "humids": humids, "timestamps": timestamps}
return dicts
def scan_sensors():
dct = {}
req = requests.request('GET', 'http://54.197.182.144:5000/scan')
json_data = req.json()
data = json_data["sensors"]
for i in data:
dct[i['id']] = i['location']
return dct
def split_location(location):
location = location.lower()
match = re.match(r"([a-z]+)([0-9]+)", location, re.I)
items = match.groups()
return items
def convert():
sensors = scan_sensors()
x = []
y = []
temp = []
id = []
req = requests.request('GET', 'http://54.197.182.144:5000/read/last_hour')
json_data = req.json()
for i in json_data:
if i["id"] not in id:
id.append(i["id"])
loc_info = split_location(sensors[int(i["id"])])
y.append(loc_info[0])
x.append(loc_info[1])
temp.append(i["data"]["temperature"]["value"])
return {'y': y, 'x': x, 'temp': temp}
if __name__ == '__main__':
# print(dict_of_sensors_list(last_hour_sensor_data()))
# print(particular_sensor_data(id=5))
print(scan_sensors())
print(convert())
|
c246c6a153b6bc176ed0e279a60d32f1b2100711 | ntkawasaki/complete-python-masterclass | /7: Lists, Ranges, and Tuples/tuples.py | 1,799 | 4.5625 | 5 | # tuples are immutable, can't be altered or appended to
# parenthesis are not necessary, only to resolve ambiguity
# returned in brackets
# t = "a", "b", "c"
# x = ("a", "b", "c") # using brackets is best practice
# print(t)
# print(x)
#
# print("a", "b", "c")
# print(("a", "b", "c")) # to print a tuple explicitly include parenthesis
# tuples can put multiple data types on same line
welcome = "Welcome to my Nightmare", "Alice Cooper", 1975
bad = "Bad Company", "Bad Company", 1974
budgie = "Nightflight", "Budgie", 1981
imelda = "More Mayhem", "Emilda Way", 2011
metallica = "Ride the Lightening", "Metallica", 1984
# print(metallica)
# print(metallica[0]) # print one part of tuple
# print(metallica[1])
# print(metallica[2])
# cant change underlying tuple, immutable object
# metallica[0] = "Master of Puppets"
# ca get around this like this though
imelda = imelda[0], "Emilda Way", imelda[2]
# python also evaluates the right side of this expression first, then assigns it to a new variable "imelda"
# creates a new tuple
print(imelda)
# can alter a list though
metallica2 = ["Ride the Lightening", "Metallica", 1984]
print(metallica2)
metallica2[0] = "Master of Puppets"
print(metallica2)
print()
# metallica2.append("Rock")
# title, album, year = metallica2
# print(title)
# print(album)
# print(year)
# will draw a too many values to unpack error because not enough variables assigned
# unpacking the tuple, extract values from and assign to variables
title, album, year = imelda
print(imelda)
print("Title: {}".format(title))
print("Album: {}".format(album))
print("Year: {}".format(year))
# tuples don't have an append() method
imelda.append("Rock")
# notes
# lists are intended to hold objects of the same type, tuples not necessarily
# tuples not changing can protect code against bugs
|
acf3384d648aa16c781ac82c61b8e3c275538bae | ntkawasaki/complete-python-masterclass | /10: Input and Output/shelve_example.py | 1,638 | 4.25 | 4 | # like a dictionary stored in a file, uses keys and values
# persistent dictionary
# values pickled when saved, don't use untrusted sources
import shelve
# open a shelf like its a file
# with shelve.open("shelf_test") as fruit: # makes a shelf_test.db file
# fruit["orange"] = "a sweet, orange fruit"
# fruit["apple"] = "good for making cider"
# fruit["lemon"] = "a sour, yellow fruit"
# fruit["grape"] = "a small, sweet fruit grown in bunches"
# fruit["lime"] = "a sour, green citrus fruit"
# when outside of the with, it closes the file
# print(fruit) # prints as a shelf and not a dictionary
# to do this with manual open and closing
fruit = shelve.open("shelf_test")
# fruit["orange"] = "a sweet, orange fruit"
# fruit["apple"] = "good for making cider"
# fruit["lemon"] = "a sour, yellow fruit"
# fruit["grape"] = "a small, sweet fruit grown in bunches"
# fruit["lime"] = "a sour, green citrus fruit"
# # change value of "lime"
# fruit["lime"] = "goes great with tequila!"
#
# for snack in fruit:
# print(fruit[snack])
# while True:
# dict_key = input("Please enter a fruit: ")
# if dict_key == "quit":
# break
#
# if dict_key in fruit:
# description = fruit[dict_key]
# print(description)
# else:
# print("We don't have a " + dict_key)
# alpha sorting keys
# ordered_keys = list(fruit.keys())
# ordered_keys.sort()
#
# for f in ordered_keys:
# print(f + " - " + fruit[f])
#
# fruit.close() # remember to close
for v in fruit.values():
print(v)
print(fruit.values())
for f in fruit.items():
print(f)
print(fruit.items())
fruit.close() |
fcd60015393e712316586a32f75462eff2f4543f | ntkawasaki/complete-python-masterclass | /11: Modules and Functions/Functions/more_functions.py | 2,460 | 4.125 | 4 | # more functions!
# function can use variables from main program
# main program cannot use local variables in a function
import math
try:
import tkinter
except ImportError: # python 2
import Tkinter as tkinter
def parabola(page, size):
"""
Returns parabola or y = x^2 from param x.
:param page:
:param size
:return parabola:
"""
for x_coor in range(size):
y_coor = x_coor * x_coor / size
plot(page, x_coor, y_coor)
plot(page, -x_coor, y_coor)
# modify the circle function so that it allows the color
# of the circle to be specified and defaults to red
def circle(page, radius, g, h, color="red"):
""" Create a circle. """
for x in range(g * 100, (g + radius) * 100):
page.create_oval(g + radius, h + radius, g - radius, h - radius, outline=color, width=2)
# x /= 100
# print(x)
# y = h + (math.sqrt(radius ** 2 - ((x - g) ** 2)))
# plot(page, x, y)
# plot(page, x, 2 * h - y)
# plot(page, 2 * g - x, y)
# plot(page, 2 * g - x, 2 * h - y)
def draw_axis(page):
"""
Draws a horizontal and vertical line through middle of window to be used as
the x and y axis.
:param page:
:return:
"""
page.update() # allows you to use winfo_width/height
x_origin = page.winfo_width() / 2
y_origin = page.winfo_height() / 2
page.configure(scrollregion=(-x_origin, -y_origin, x_origin, y_origin))
# create_line(x1, y1, x2, y2)
page.create_line(-x_origin, 0, x_origin, 0, fill="black") # horizontal
page.create_line(0, y_origin, 0, -y_origin, fill="black") # vertical
# shows all local variables in this function
print(locals())
def plot(page, x_plot, y_plot):
"""
Plots points on canvas from params x and y.
:param page:
:param x_plot:
:param y_plot:
:return:
"""
page.create_line(x_plot, -y_plot, x_plot + 1, -y_plot + 1, fill="red")
# window
main_window = tkinter.Tk()
main_window.title("Parabola")
main_window.geometry("640x480")
# canvas
canvas = tkinter.Canvas(main_window, width=640, height=480, background="gray")
canvas.grid(row=0, column=0)
# call function
draw_axis(canvas)
parabola(canvas, 300)
parabola(canvas, 20)
circle(canvas, 100, 100, 100, color="blue")
circle(canvas, 100, 100, 100, color="yellow")
circle(canvas, 100, 100, 100, color="green")
circle(canvas, 10, 30, 30, color="black")
main_window.mainloop()
|
b9096be499b5324792acee537eb36a6cf1121c5b | ntkawasaki/complete-python-masterclass | /6: Flow Control/if_program_flow.py | 1,098 | 4.0625 | 4 | print()
name = input("Please tell me your name: ")
age = int(input("How old are you, {0}? ".format(name)))
if not (age < 18):
print("You are old enough to vote.")
print("Please put an X in the box.")
else:
print("Please come back in {0} years".format(18 - age))
# print("Please guess a number between 1 and 10.")
# guess = int(input())
#
# if guess != 5:
# if guess < 5:
# print("Please guess higher.")
# else:
# print("Please guess lower.")
# guess = int(input())
#
# if guess == 5:
# print("Well done!")
# else:
# print("Sorry, you are wrong again.")
# else:
# print("Nice, first try!!!")
# age = int(input("How old are you? "))
# if (age >= 16) and (age <= 65):
# if 15 < age < 66:
# print("Have a great day at work!")
# if (age < 16) or (age > 65):
# print("Enjoy your free time!")
# else:
# print("Have a good day at work!")
# x = input("Please enter some text: ")
#
# if x:
# print("You entered {0}.".format(x))
# else:
# print("You did not enter anything.")
#
# print(not True)
# print(not False) |
053003b71dcec146dcccdfcbba06c4bcd8406f54 | ntkawasaki/complete-python-masterclass | /6: Flow Control/for_loops.py | 862 | 3.59375 | 4 | # for i in range(1, 21):
# print("i is now {}".format(i))
number = "9,333,455,768,234"
cleaned_number = ""
# for i in range(0, len(number)):
# if number[i] in "0123456789":
# cleaned_number = cleaned_number + number[i] # concatenation of strings
# through a sequence of values
for char in number:
if char in "0123456789":
cleaned_number = cleaned_number + char
new_number = int(cleaned_number)
print("The new number is: {}.".format(new_number))
for state in ["not pinin'", "no more", "sad", "a stiff", "bereft of life"]:
print("This parrot is " + state)
# print("This parrot is {}".format(state))
for i in range(0, 100, 5):
print("i is {0}.".format(i))
for i in range(1, 13):
for j in range(1, 13):
print("{0} times {1} = {2}".format(j, i, i * j), end="\t")
# print("===============")
print("") |
4ef8a7a07238c6930ff101f62fed0eead560b3bd | TheLoneGuy/Home-Loan-Calculator | /index.py | 8,544 | 3.546875 | 4 | from tkinter import *
from tkinter import ttk
from tkinter import font
from threading import Timer
import math
import random
from Graph import *
from background import Background
random.seed()
TRANSPARENT = "#576890"
DECIMAL_POINTS = "{:.2f}"
inputs = {
'loan': 10000,
'down': 10,
'rate': 4.5,
'year': 10
}
outputs = {
'repayment': 0,
'principle': 0,
'interest': 0,
'month': 0
}
LargeFont = ("Times New Roman", 15)
def debounce(wait):
""" Decorator that will postpone a functions
execution until after wait seconds
have elapsed since the last time it was invoked. """
def decorator(func):
def debounced(*args, **kwargs):
def call_it():
func(*args, **kwargs)
try:
debounced._timer.cancel()
except(AttributeError):
pass
debounced._timer = Timer(wait, call_it)
debounced._timer.start()
return debounced
return decorator
def is_float(potential_float):
try:
float(potential_float)
return True
except ValueError:
return False
def mortgage(loan, down, rate, year, format="%"):
if format == "%":
# down payment in percentage format
principle = loan * (100 - down) / 100
elif format == "RM":
# down payment in cash format
principle = loan - down
month = int(year * 12)
monthly_rate = rate / 12 / 100
compound = (1 + monthly_rate) ** month
repayment = principle / ((compound - 1) / (monthly_rate * compound)) * month
interest = repayment - principle
return repayment, principle, interest, month
@debounce(0.3)
def mortgage_list():
debt = outputs['repayment']
interest = outputs['interest']
rate = inputs['rate']
month = outputs['month']
# Use treeview or something to display the data in a table like forma
month_debt = debt/month
interest /= month
results = ResultListTopLevel(root)
for i in range(1, month + 1):
interest = debt * rate / 100 / 12
principle = month_debt - interest
debt = debt - principle - interest
results.list.insert('', 'end', text=i, values=(DECIMAL_POINTS.format(principle), DECIMAL_POINTS.format(interest), DECIMAL_POINTS.format(debt)))
# Widget function callbacks
@debounce(0.3)
def display_update(repayment, prin, rate, month):
debt.label.config(text=DECIMAL_POINTS.format(repayment))
principle.label.config(text=DECIMAL_POINTS.format(prin))
interest.label.config(text=DECIMAL_POINTS.format(rate))
outputs.update({
'repayment': repayment,
'principle': prin,
'interest': rate,
'month': month
})
circle_graph.cal([
{
"subject": "Principle",
"value": prin,
"color": "#90ee90"
},
{
"subject": "Interest",
"value": rate,
"color": "#006400"
}
])
circle_graph.animate()
# widgets
class ValidatedEntry(Entry):
def __init__(self, master, name, default, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.name = name
self.default = default
self.upperbound = None
self.insert(0, self.default)
vcmd = (root.register(self._validation), "%P")
self.configure(validate="key", validatecommand=vcmd)
def _validation(self, value):
tmp = None
try:
if value == "":
value = float(self.default)
elif is_float(value):
value = float(value)
if self.upperbound:
if self.upperbound <= value:
raise ValueError("Sorry, no numbers {} and above".format(self.upperbound))
else:
raise TypeError("Entry only allows floats input")
tmp, inputs[self.name] = inputs[self.name], value
output = mortgage(**inputs)
display_update(*output)
return True
except Exception as ex:
if tmp:
inputs[self.name] = tmp
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print(message)
return False
def set_range(self, upperbound=None):
self.upperbound=upperbound
class EntryFrame(LabelFrame):
def __init__(self, master, name, default, *args, **kwargs):
super().__init__(master, bg=TRANSPARENT, *args, **kwargs)
self.ent = ValidatedEntry(self, name, default, font=LargeFont)
self.ent.grid()
class ResultFrame(LabelFrame):
def __init__(self, master, *args, value="", **kwargs):
super().__init__(master, *args, **kwargs)
self.label = Label(self, bg=TRANSPARENT)
self.label.grid()
class ResultListTopLevel(Toplevel):
def __init__(self, master):
super().__init__(master)
self.geometry("600x600+700+50")
headings = 'Principle', 'Interest', 'Debt'
self.list = ttk.Treeview(self, columns=headings, selectmode='browse')
self.sb = Scrollbar(self, orient=VERTICAL)
self.sb.pack(side=RIGHT, fill=Y)
self.list.config(yscrollcommand=self.sb.set)
self.sb.config(command=self.list.yview)
self.list.heading("#0", text="Month")
self.list.column("#0", minwidth=0, width=100, anchor="center")
for heading in headings:
self.list.heading(heading, text=heading)
self.list.column(heading, minwidth=0, width=100, anchor="center")
self.list.pack(fill=BOTH,expand=1)
self.list.bind('<Button-1>', self.handle_click)
def handle_click(self, event):
if self.list.identify_region(event.x, event.y) == "separator":
return "break"
root = Tk()
root.title("Home Loan Calculator")
root.wm_attributes("-transparentcolor", TRANSPARENT)
root.resizable(False, False)
root.wm_attributes("-topmost", True)
root.geometry("600x600+50+50")
root.configure(bg=TRANSPARENT)
root.bind_all("<1>", lambda event:event.widget.focus_set())
bg_root = Toplevel(root)
bg_root.geometry("600x600+50+50")
bg = Background(bg_root)
topframe = Frame(root, bg=TRANSPARENT)
topframe.place(relx=0.5, rely=0.5, anchor=CENTER)
loan = EntryFrame(topframe, 'loan', inputs['loan'], font=LargeFont)
down = EntryFrame(topframe, 'down', inputs['down'], font=LargeFont)
rate = EntryFrame(topframe, 'rate', inputs['rate'], font=LargeFont)
year = EntryFrame(topframe, 'year', inputs['year'], font=LargeFont)
loan.config(text="Loan:")
down.config(text="Down Payment:")
rate.config(text="Interest Rate:")
year.config(text="Year:")
down.ent.set_range(upperbound=100)
rate.ent.set_range(upperbound=100)
loan.grid()
down.grid()
rate.grid()
year.grid()
debt = ResultFrame(topframe, text="Debt:", bg=TRANSPARENT, font=LargeFont)
principle = ResultFrame(topframe, text="Principle:", bg=TRANSPARENT, font=LargeFont)
interest = ResultFrame(topframe, text="Interest:", bg=TRANSPARENT, font=LargeFont)
debt.label.config(justify="center", font=LargeFont)
principle.label.config(justify="center", font=LargeFont)
interest.label.config(justify="center", font=LargeFont)
debt.grid(sticky="EW")
principle.grid(sticky="EW")
interest.grid(sticky="EW")
graph_frame = Frame(topframe, bg=TRANSPARENT)
graph_frame.grid(column=1, row=0, rowspan=7)
circle_graph = GraphCanvas(graph_frame, width=250, height=250, bg=TRANSPARENT, highlightthickness=0)
graph_title = Label(graph_frame, text="Payment Breakdown", bg=TRANSPARENT, font=LargeFont)
graph_frame_label = Frame(graph_frame, width=100, bg=TRANSPARENT)
graph_label1 = GraphLabel(graph_frame_label, text="Principle", color="#90ee90")
graph_label2 = GraphLabel(graph_frame_label, text="Interest", color="#006400")
graph_label1.text.config(bg=TRANSPARENT, font=LargeFont)
graph_label2.text.config(bg=TRANSPARENT, font=LargeFont)
graph_label1.grid(sticky="W")
graph_label2.grid(sticky="W")
graph_title.grid()
circle_graph.grid()
graph_frame_label.grid()
btn_print = Button(root, text="Print List", command=mortgage_list)
btn_print.place(relx=0.9, rely=0.9)
loan.ent._validation("")
bg.setup()
bg.animation()
root.mainloop() |
72808324afe7943941c3ea9673bfba435561ab82 | ZibingZhang/Minesweeper | /src/minesweeper.py | 13,869 | 3.859375 | 4 | import tkinter as tk
from random import randint
from itertools import product
from cell import Cell
class Minesweeper(object):
""" The minesweeper game.
The minesweeper game. It includes all the widgets for the GUI.
Class Attributes:
PAD_X (int): The amount of horizontal padding for the top and bottom half frames.
PAD_Y (int): The amount of vertical padding for the top and bottom half frames.
Instance Attributes:
rows (int): The number of cells, vertically, for the minesweeper game.
columns (int): The number of cells, horizontally, for the minesweeper game.
bombs (int): The number of bombs on the board.
root (Tk): The root window.
top (Frame): The top half of the window, the part where the game is played.
bottom (Frame): The bottom half of the window, the part where information is displayed.
menu_bar (Menu): The menu bar.
message (StringVar): The message being displayed at the bottom.
message_label (Label): The widget where the number of bombs left is displayed.
cells (List-of (List-of Cell)): 2D array of all the Cell objects.
generated_bombs (bool): Has the bombs been generated yet?
game_over (bool): Is the game over?
Methods:
bind_shortcuts: Binds the appropriate keyboard shortcuts.
resize: Resize the board.
create_menu_bar: Creates the menu bar.
new: Resets the game.
generate_bombs: Randomly generates the bombs and updates the 2D cell array accordingly.
uncover_neighbors: Uncovers neighboring cells.
neighboring_bombs: Counts the number of neighboring bombs.
neighboring_flags: Counts the number of neighboring flags.
alter_counter: Updates the counter.
has_won: Has the user won the game?
win_game: Win the game.
lose_game: Lose the game.
"""
PAD_X = 10
PAD_Y = 10
def __init__(self, root):
""" Initializes the object.
Initializes the instance attributes as described above.
Generates the GUI components for the game, namely the two halves and the menu bar.
The top half includes the 2D array of buttons that represents the cells.
The bottom half includes the display message which indicates how many bombs are left or if the game is over.
The menu bar has options to restart, change the size, and exit.
Binds shortcuts to various key combinations as described below.
Args:
root: The root window.
"""
self.root = root
# Board size
self.rows = 16
self.columns = 16
self.bombs = 40
# Window Settings
self.root.title("Minesweeper")
self.root.resizable(False, False)
# Two halves of the screen
self.top = tk.Frame(root, padx=self.PAD_X, pady=self.PAD_Y)
self.top.pack(side=tk.TOP)
self.bottom = tk.Frame(root, padx=self.PAD_X, pady=self.PAD_Y)
self.bottom.pack(side=tk.BOTTOM)
# Menu Bar
self.menu_bar = tk.Menu(self.root)
self.create_menu_bar()
self.root.config(menu=self.menu_bar)
# Footer
self.message = tk.StringVar()
self.message_label = tk.Label(self.bottom, textvariable=self.message)
self.message.set(str(self.bombs))
self.message_label.pack()
# Tkinter Board
self.cells = []
for row in range(self.rows):
self.cells.append([])
for column in range(self.columns):
button = Cell(self, self.top, row, column)
self.cells[row].append(button)
self.generated_bombs = False
self.game_over = False
# Keyboard Shortcuts
self.bind_shortcuts()
def bind_shortcuts(self):
""" Binds the appropriate keyboard shortcuts.
<Ctrl-q> : exits the game.
<Ctrl-n> : or F2 starts a new game.
<Ctrl-z> : starts a new game with a small sized board.
<Ctrl-x> : starts a new game with a medium sized board.
<Ctrl-c> : starts a new game with a large sized board.
"""
self.root.bind("<Control-q>", lambda event: self.root.destroy())
self.root.bind("<Control-n>", lambda event: self.new())
self.root.bind("<F2>", lambda event: self.new())
self.root.bind("<Control-z>", lambda event: self.resize(9, 9, 10))
self.root.bind("<Control-x>", lambda event: self.resize(16, 16, 40))
self.root.bind("<Control-c>", lambda event: self.resize(16, 30, 99))
def create_menu_bar(self):
""" Creates the menu bar. """
file_menu = tk.Menu(self.menu_bar, tearoff=0)
file_menu.add_command(label="New", command=self.new)
# create more pull down menus
size_menu = tk.Menu(file_menu, tearoff=0)
size_menu.add_command(label="Small", command=lambda: self.resize(9, 9, 10))
size_menu.add_command(label="Medium", command=lambda: self.resize(16, 16, 40))
size_menu.add_command(label="Large", command=lambda: self.resize(16, 30, 99))
file_menu.add_cascade(label="Size", menu=size_menu)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.destroy)
self.menu_bar.add_cascade(label="File", menu=file_menu)
def resize(self, rows, columns, bombs):
""" Resize the board.
Args:
rows: The new number of rows.
columns: The new number of columns.
bombs: The new number of bombs.
"""
for row in range(self.rows):
for column in range(self.columns):
self.cells[row][column].button.destroy()
self.cells = []
self.rows = rows
self.columns = columns
self.bombs = bombs
self.message.set(self.bombs)
for row in range(self.rows):
self.cells.append([])
for column in range(self.columns):
self.cells[row].append(Cell(self, self.top, row, column))
self.new()
def new(self):
""" Resets the game. """
for row in range(self.rows):
for column in range(self.columns):
self.cells[row][column].reset()
self.generated_bombs = False
self.game_over = False
self.message.set(self.bombs)
def generate_bombs(self, initial_row, initial_column):
""" Randomly generates the bombs and updates the 2D cell array accordingly.
Generates the bombs such that they do not they do not border the first cell clicked.
Args:
initial_row: The row of the cell that should not border a bomb.
initial_column: The column of the cell that should not border a bomb.
"""
self.generated_bombs = True
bombs = self.bombs
while bombs > 0:
row = randint(0, self.rows-1)
column = randint(0, self.columns-1)
if not self.cells[row][column].is_bomb and \
((row-initial_row)**2 + (column-initial_column)**2)**0.5 > 1.5:
self.cells[row][column].is_bomb = True
bombs -= 1
# Test Case :
# 1 bomb left, guessing required
# -------------------------------
# self.generated_bombs = True
# self.cells[0][2].is_bomb = True
# self.cells[1][1].is_bomb = True
# self.cells[1][2].is_bomb = True
# self.cells[2][2].is_bomb = True
# self.cells[3][0].is_bomb = True
# self.cells[3][7].is_bomb = True
# self.cells[5][1].is_bomb = True
# self.cells[6][8].is_bomb = True
# self.cells[8][6].is_bomb = True
# self.cells[8][7].is_bomb = True
# Test Case :
# 3 bombs left
# ---------------------------------
# self.generated_bombs = True
# self.cells[2][4].is_bomb = True
# self.cells[3][0].is_bomb = True
# self.cells[4][1].is_bomb = True
# self.cells[5][2].is_bomb = True
# self.cells[5][4].is_bomb = True
# self.cells[5][8].is_bomb = True
# self.cells[6][0].is_bomb = True
# self.cells[7][0].is_bomb = True
# self.cells[7][1].is_bomb = True
# self.cells[7][7].is_bomb = True
# Test Case :
# 5 bombs left (right half)
# ---------------------------------
# self.generated_bombs = True
# self.cells[0][6].is_bomb = True
# self.cells[1][4].is_bomb = True
# self.cells[3][4].is_bomb = True
# self.cells[4][5].is_bomb = True
# self.cells[5][1].is_bomb = True
# self.cells[5][4].is_bomb = True
# self.cells[5][6].is_bomb = True
# self.cells[6][4].is_bomb = True
# self.cells[7][3].is_bomb = True
# self.cells[8][1].is_bomb = True
# Test Case :
# 7 bombs left (upper right)
# ---------------------------------
# self.generated_bombs = True
# self.cells[1][1].is_bomb = True
# self.cells[3][1].is_bomb = True
# self.cells[3][2].is_bomb = True
# self.cells[4][2].is_bomb = True
# self.cells[5][5].is_bomb = True
# self.cells[7][1].is_bomb = True
# self.cells[7][4].is_bomb = True
# self.cells[7][7].is_bomb = True
# self.cells[8][0].is_bomb = True
# self.cells[8][5].is_bomb = True
def uncover_neighbors(self, row, column):
""" Uncovers neighboring cells.
Uncovers the neighbors of the cell at the position given by row and column.
Args:
row: The row of the cell whose neighbors are being uncovered.
column: The column of the cell whose neighbors are being uncovered.
"""
for row_offset, column_offset in product((-1, 0, 1), (-1, 0, 1)):
try:
if (self.cells[row + row_offset][column + column_offset].state == "covered" and
row + row_offset >= 0 and column + column_offset >= 0):
self.cells[row + row_offset][column + column_offset].left_click()
except (TypeError, IndexError):
pass
def neighboring_bombs(self, row, column):
""" Counts the number of neighboring bombs.
Args:
row: The row of the cell whose neighboring bombs are being counted.
column: The column of the cell whose neighboring bombs are being counted.
Returns:
int: The number of neighboring bombs.
"""
# Unable to see the number of the cell unless it is uncovered.
assert self.cells[row][column].state == "uncovered"
bombs = 0
for row_offset, column_offset in product((0, -1, 1), (0, -1, 1)):
try:
if (not (row_offset == 0 and column_offset == 0) and
row + row_offset >= 0 and column + column_offset >= 0 and
self.cells[row + row_offset][column+column_offset].is_bomb):
bombs += 1
except IndexError:
pass
return bombs
def neighboring_flags(self, row, column):
""" Counts the number of neighboring flags.
Args:
row: The row of the cell whose neighboring flags are being counted.
column: The column of the cell whose neighboring flags are being counted.
Returns:
int: The number of neighboring flags.
"""
flags = 0
for row_offset, column_offset in product((0, -1, 1), (0, -1, 1)):
try:
if (not (row_offset == 0 and column_offset == 0) and
row + row_offset >= 0 and column + column_offset >= 0 and
self.cells[row + row_offset][column + column_offset].state == "flagged"):
flags += 1
except IndexError:
pass
return flags
def alter_counter(self, increment):
""" Changes the counter by the increment to indicate the number of bombs remaining.
Args:
increment: The change to the counter.
"""
try:
self.message.set(int(self.message.get()) + increment)
except ValueError:
# Not sure why it sometimes throws errors...
pass
def has_won(self):
""" Has the user won the game?
Is the total number of uncovered cells plus the number of cells that are bombs
equal to the total number of cells?
Returns:
bool: Has the user won the game?
"""
total = self.rows*self.columns
for row in range(self.rows):
for column in range(self.columns):
if self.cells[row][column].is_bomb:
total -= 1
elif not self.cells[row][column].state == "covered":
total -= 1
return total == 0
def win_game(self):
""" Win the game.
Flags the remaining bombs that have not yet been flagged
"""
for row in range(self.rows):
for column in range(self.columns):
if self.cells[row][column].is_bomb and not self.cells[row][column].state == "flagged":
self.cells[row][column].flag()
self.game_over = True
self.message.set("You Win")
def lose_game(self):
""" Lose the game.
Removes all flags, presses all cells down, and displays all the cells.
"""
for row in range(self.rows):
for column in range(self.columns):
self.cells[row][column].state = "uncovered"
self.cells[row][column].show_text()
self.cells[row][column].remove_flag()
self.game_over = True
self.message.set("You Lose")
|
b44f64493cd2afd91cb134580625091c4ca0aa96 | dlcios/coding-py | /basic/mail_re.py | 376 | 3.546875 | 4 | import re
#验证email的正则表达式,邮箱名可以使英文字母或数字或 -,_ 符号,后巷后缀网址名可以是英文或数字,域名可以使 com,org,edu
#例: chu-tian-shu_1981@heibanke2015.com
# mail = "1905790854@qq.com"
mail = "chu-tian-shu_1981@heibanke2015.com"
pattern = re.compile(r"^[\w\-\,]+@[a-zA-Z0-9]+\.(com|org|edu){1}$")
match = pattern.match(mail)
if match :
print('ok')
else:
print('false') |
42b5a11339851544418f71b3cd7e1ceb8ab46966 | dlcios/coding-py | /basic/def.py | 594 | 3.65625 | 4 | #coding: utf-8
# to16mod = hex
# n1 = to16mod(25)
# print(n1)
# #定义函数
# def mabs(num):
# if num > 0:
# return num
# else:
# return -num
# a = -15
# b = 15
# print(mabs(a), mabs(b))
# def power(x):
# return x * x
# print(power(a))
# def powern(x,y = 2):
# s = 1
# while y > 0:
# s = s * x
# y -= 1
# return s
# print(powern(2,1))
def add_append(l=None):
if l == None:
l = []
l.append('hello')
return l
print(add_append([1,2]))
print(add_append([3,4]))
print(add_append())
print(add_append())
|
50c94f0dcf4ed5abc4af1bd3a4b6fe7a190a3471 | Geo-Root/code5 | /code5/console_scripts.py | 2,526 | 3.71875 | 4 | #!/usr/bin/env python
"""
code5 - Convert stdin (or the first argument) to a Code5 Code.
When stdout is a tty the Code5 Code is printed to the terminal and when stdout is
a pipe to a file an image is written. The default image format is PNG.
"""
import sys
import optparse
import os
import code5
def main(args=sys.argv[1:]):
parser = optparse.OptionParser(usage=__doc__.strip())
opts, args = parser.parse_args(args)
c5 = code5.Code5()
image_factory = None
decode = False
alphabet = False
if args:
data = ''
if args[0] == 'alphabet':
alphabet = True
else:
if '.png' in args[0]:
decode = True
data = args[0]
else:
try:
with open(args[0], 'r') as data_file:
data = data_file.read()
data = data.replace('\n',',')
except:
data = args[0]
else:
stdin_buffer = getattr(sys.stdin, 'buffer', sys.stdin)
data = stdin_buffer.read()
if args[0] == 'alphabet':
alphabet = True
else:
if '.png' in args[0]:
decode = True
data = args[0]
else:
try:
with open(args[0], 'r') as data_file:
data = data_file.read()
data = data.replace('\n',',')
except:
data = args[0]
if alphabet:
c5.dump_alphabet(image_factory=image_factory)
else:
if not decode:
blocks = data.split(',')
for block in blocks:
c5.add_data(block)
img = c5.make_image(image_factory=image_factory)
with open('debug.txt', 'w') as debug_file:
debug_file.write(c5.UR+'\n')
debug_file.write(c5.C+'\n')
debug_file.write(c5.DL+'\n')
debug_file.write(c5.DR+'\n')
try:
img.save_to_path('%s.png'%block, format=None)
except:
img.save('%s.png'%block)
else:
result = c5.revert(image_factory=image_factory, image_path=data)
with open('debug.txt', 'w') as debug_file:
debug_file.write(c5.log)
with open('result.txt', 'w') as result_file:
result_file.write(result)
if __name__ == "__main__":
main()
|
b0bce312122d6b733dc4c63bd6f7e432e8084d78 | georgebzhang/Python_LeetCode | /14_longest_common_prefix.py | 854 | 3.703125 | 4 | class Solution(object):
def longestCommonPrefix(self, strs):
if not strs:
return ''
lcp = ''
ind = 0
while True:
letters = []
for item in strs:
if ind == len(item):
return lcp
letters.append(item[ind])
letter = set(letters) # convert list to set
if len(letter) == 1: # only 1 element in set if all items in list were same
lcp += letter.pop()
else:
return lcp
ind += 1
return lcp
def print_answer(self, ans):
print(ans)
def test(self):
strs = ["flower", "flow", "flight"]
ans = self.longestCommonPrefix(strs)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
af3a21971e6ca7593bdc88efb05563dd37892cb6 | georgebzhang/Python_LeetCode | /142_linked_list_cycle_II_2.py | 1,838 | 3.734375 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
def hasCycle():
slow = head
while fast[0] and fast[0].next:
slow = slow.next
fast[0] = fast[0].next.next
if slow is fast[0]:
return True
return False
fast = [head]
if hasCycle():
slow, fast = head, fast[0]
while fast:
if slow is fast:
return slow
slow, fast = slow.next, fast.next
return None
def print_answer(self, ans, head):
ind = 0
ptr = head
while ptr:
if ans is ptr:
break
ind += 1
ptr = ptr.next
print('tail connects to node index {}'.format(ind))
def build_linked_list(self, vals, pos):
n = len(vals)
head = ListNode(vals[0])
prev = head
for i in range(1, n):
curr = ListNode(vals[i])
prev.next = curr
prev = curr
if i == n-1: # tail
if pos != -1:
loop = head
for i in range(pos):
loop = loop.next
curr.next = loop
return head
def print_linked_list(self, head):
ptr = head
while ptr:
print(ptr.val, ' ', end='')
ptr = ptr.next
print()
def test(self):
vals = [3, 2, 0, -4]
pos = 1
head = self.build_linked_list(vals, pos)
# self.print_linked_list(head)
ans = self.detectCycle(head)
self.print_answer(ans, head)
if __name__ == '__main__':
s = Solution()
s.test()
|
4bc07ecb11ed78ec76815d8058ea67924109584d | georgebzhang/Python_LeetCode | /88_merge_sorted_array_2.py | 670 | 3.78125 | 4 | class Solution(object):
def merge(self, nums1, m, nums2, n):
if not n:
return
i, j = m-1, n-1
ind = m+n-1
while j >= 0:
if i < 0 or nums2[j] > nums1[i]:
nums1[ind] = nums2[j]
j -= 1
else:
nums1[ind] = nums1[i]
i -= 1
ind -= 1
def print_answer(self, ans):
print(ans)
def test(self):
nums1 = [1, 2, 3, 0, 0, 0]
m = 3
nums2 = [2, 5, 6]
n = 3
self.merge(nums1, m, nums2, n)
self.print_answer(nums1)
if __name__ == '__main__':
s = Solution()
s.test()
|
b0757ed59534e19f646e054abb4ba6b001e5cc2e | georgebzhang/Python_LeetCode | /22_generate_parentheses.py | 958 | 3.578125 | 4 | class Solution:
def generateParenthesis(self, n):
def permute(perm, rem):
if not rem:
perms.add(perm[:])
for i in range(len(rem)):
permute(perm+rem[i], rem[:i]+rem[i+1:])
def validParenthesis(s):
mapping = {')': '('}
stack = ''
for k in s:
if k in mapping:
if not stack or mapping[k] != stack[-1]:
return False
stack = stack[:-1]
else:
stack += k
return not stack
perms = set()
s = '('*n + ')'*n
permute('', s)
return [s for s in perms if validParenthesis(s)]
def print_answer(self, ans):
print(ans)
def test(self):
n = 3
ans = self.generateParenthesis(n)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
a3788a58c6702af9e8bd0c397f298bf6c74f979f | georgebzhang/Python_LeetCode | /690_employee_importance_2.py | 1,224 | 3.8125 | 4 | from collections import deque
class Employee:
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
self.subordinates = subordinates
class Solution(object):
def getImportance(self, employees, id):
def dfs(e):
result[0] += e.importance
for s in e.subordinates:
dfs(e_dict[s])
result = [0]
e_dict = {}
for e in employees:
e_dict[e.id] = e
dfs(e_dict[id])
return result[0]
def print_ans(self, ans):
print(ans)
def build_employees_list(self, vals):
employees = []
for val in vals:
employees.append(Employee(val[0], val[1], val[2]))
return employees
def test(self):
vals = [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]]
id = 1
employees = self.build_employees_list(vals)
ans = self.getImportance(employees, id)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
7bce04d20e4c7b828831040372bfddb25820ebd0 | georgebzhang/Python_LeetCode | /62_unique_paths_2.py | 509 | 3.640625 | 4 | from math import factorial
class Solution(object):
def uniquePaths(self, m, n):
def num_combinations(n, k):
return int(factorial(n)/(factorial(k)*factorial(n-k)))
steps = m-1 + n-1
down_steps = m-1
return num_combinations(steps, down_steps)
def print_ans(self, ans):
print(ans)
def test(self):
m, n = 3, 2
ans = self.uniquePaths(m, n)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
cf66a9a5256601495187f39d1db14b329138207b | georgebzhang/Python_LeetCode | /139_word_break.py | 729 | 3.5625 | 4 | class Solution(object):
def wordBreak(self, s, wordDict):
def wordBreakRec(s):
if s in wordSet:
return True
for i in range(len(s)):
s1 = s[:i+1]
if s1 in wordSet:
s2 = s[i+1:]
if wordBreakRec(s2):
return True
return False
wordSet = set(wordDict)
return wordBreakRec(s)
def print_ans(self, ans):
print(ans)
def test(self):
s = "goalspecial"
wordDict = ["go", "goal", "goals", "special"]
ans = self.wordBreak(s, wordDict)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
ff90d9c953787cbb9975ca6130b5a2cd810a3716 | georgebzhang/Python_LeetCode | /973_k_closest_points_to_origin_6.py | 714 | 3.5 | 4 | from heapq import heapify, heappop, heappush, nsmallest
class Point(object):
def __init__(self, c): # c for coords
self.c = c
self.dist2 = c[0] ** 2 + c[1] ** 2
class Solution(object):
def kClosest(self, points, K):
l_points = []
for c in points:
l_points.append(Point(c))
l_points_k = nsmallest(K, l_points, key=lambda point: point.dist2)
return [point.c for point in l_points_k]
def print_ans(self, ans):
print(ans)
def test(self):
points = [[3, 3], [5, -1], [-2, 4]]
K = 2
ans = self.kClosest(points, K)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
07cb7d2e8c636cb9ba70afe4d555be52a9cad251 | georgebzhang/Python_LeetCode | /287_find_the_duplicate_number.py | 470 | 3.65625 | 4 | class Solution(object):
def findDuplicate(self, nums):
s = set()
for i in range(len(nums)):
if nums[i] in s:
return nums[i]
else:
s.add(nums[i])
return -1
def print_ans(self, ans):
print(ans)
def test(self):
nums = [1, 3, 4, 2, 2]
ans = self.findDuplicate(nums)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
cbc9d6af1d0a443eb6c9f4c2c0da318e9653a911 | georgebzhang/Python_LeetCode | /102_binary_tree_level_order_traversal.py | 2,149 | 3.765625 | 4 | from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root):
if not root:
return []
q = deque()
q.append(root)
levels_vals = []
while q:
level_vals = []
for i in range(len(q)):
node = q.popleft()
level_vals.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
levels_vals.append(level_vals)
return levels_vals
def print_answer(self, ans):
print(ans)
def build_tree_inorder(self, vals):
def build_tree_rec(node, i):
if i < n:
if vals[i] != 'null':
node = TreeNode(vals[i])
node.left = build_tree_rec(node.left, 2*i+1)
node.right = build_tree_rec(node.right, 2*i+2)
return node
n = len(vals)
root = None
root = build_tree_rec(root, 0)
return root
def print_tree(self, root):
q = deque()
q.append(root)
level_order_vals = []
while q:
level_vals = []
for i in range(len(q)):
node = q.popleft()
level_vals.append(node.val)
if node.val == 'null':
continue
if node.left:
q.append(node.left)
else:
q.append(TreeNode('null'))
if node.right:
q.append(node.right)
else:
q.append(TreeNode('null'))
level_order_vals.append(level_vals)
print(level_order_vals)
def test(self):
vals = [3, 9, 20, 'null', 'null', 15, 7]
root = self.build_tree_inorder(vals)
self.print_tree(root)
ans = self.levelOrder(root)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
6e393d2f96a5cc60b428b5fb699079e75586280e | georgebzhang/Python_LeetCode | /python_heapq.py | 1,443 | 3.8125 | 4 | import heapq
class Solution(object):
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
class PersonHeap(object):
def __init__(self, l_init=None, key=lambda person: person.age): # -person.age for max heap on age
self.key = key
if l_init:
self._data = [(key(person), person) for person in l_init]
heapq.heapify(self._data)
else:
self._data = []
def push(self, person):
heapq.heappush(self._data, (self.key(person), person))
def pop(self):
return heapq.heappop(self._data)[1]
def peek(self):
return self._data[0][1]
def heappushpop(self, person): # good for heaps of fixed size
return heapq.heappushpop(self._data, (self.key(person), person))[1]
def test_personheap(self):
names = ['George', 'Alice', 'Bob', 'Jane', 'Will']
ages = [24, 17, 12, 45, 30]
l_init = []
for i in range(len(names)):
p = Solution.Person(names[i], ages[i])
l_init.append(p)
ph = Solution.PersonHeap(l_init)
print(ph.peek().age)
# print(ph.pop())
# print(ph.heappushpop(Solution.Person('Max', 19)))
def test_heapq(self):
self.test_personheap()
if __name__ == '__main__':
s = Solution()
s.test_heapq()
|
22f0b2868c705c4980c2cfac39349ff93974cc80 | georgebzhang/Python_LeetCode | /43_multiply_strings_2.py | 857 | 3.609375 | 4 | class Solution:
def multiply(self, num1, num2):
def str2int(s):
result = 0
for k in s:
result = 10*result + ord(k)-ord('0')
return result
def int2str(i):
digits = []
while i > 0:
digits.append(i % 10)
i = i // 10
digits.reverse()
keys = '0123456789'
result = ''
for d in digits:
result += keys[d]
return result
result = int2str(str2int(num1)*str2int(num2))
return '0' if not result else result
def print_answer(self, ans):
print(ans)
def test(self):
num1, num2 = '2', '3'
ans = self.multiply(num1, num2)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
205d757e0e6aa561f8a9ab0a42e6d0e74247a7a3 | georgebzhang/Python_LeetCode | /310_minimum_height_trees.py | 1,227 | 3.71875 | 4 | import sys
from collections import defaultdict
class Solution(object):
def findMinHeightTrees(self, n, edges):
def max_height(v):
if v in visited:
return 0
visited.add(v)
n_heights = []
for n in g[v]: # for neighbor of vertex
n_heights.append(max_height(n))
return max(n_heights)+1
if n == 1:
return [0]
g = defaultdict(list)
for e in edges:
g[e[0]].append(e[1])
g[e[1]].append(e[0])
visited = set()
v_heights = {}
min_height = sys.maxsize
for v in g: # for vertex in graph
h = max_height(v)
v_heights[v] = h
min_height = min(min_height, h)
visited.clear()
result = []
for v in g:
if v_heights[v] == min_height:
result.append(v)
return result
def print_ans(self, ans):
print(ans)
def test(self):
n = 6
edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
ans = self.findMinHeightTrees(n, edges)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
98f137239463f7aac4534ed3a594111572727ded | georgebzhang/Python_LeetCode | /39_combination_sum_2.py | 844 | 3.8125 | 4 | class Solution:
def combinationSum(self, candidates, target):
def backtrack(candidates, nums, rem):
# print(nums) # uncomment this to understand how backtrack works
if rem == 0:
result.append(nums)
for i, cand in enumerate(candidates):
if rem >= cand:
backtrack(candidates[i:], nums+[cand], rem-cand) # candidates[i:] guarantees no duplicate lists in result
candidates.sort()
result = []
backtrack(candidates, [], target)
return result
def print_answer(self, ans):
print(ans)
def test(self):
candidates = [2, 3, 6, 7]
target = 7
ans = self.combinationSum(candidates, target)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
6d6d97e0070e2d0177c2a35d8d39fb636eec391a | georgebzhang/Python_LeetCode | /200_number_of_islands_2.py | 1,313 | 3.625 | 4 | class Solution(object):
def numIslands(self, grid):
dirs = ((-1, 0), (1, 0), (0, -1), (0, 1))
def neighbors(i0, j0):
result = []
for di, dj in dirs:
i, j = i0 + di, j0 +dj
if 0 <= i < N and 0 <= j < M and grid[j][i] == '1':
result.append((i, j))
return result
def sink(i, j):
if (i, j) in visited:
return
visited.add((i, j))
grid[j][i] = '0'
for n in neighbors(i, j):
sink(*n)
if not grid:
return 0
M, N = len(grid), len(grid[0])
visited = set()
result = 0
for j in range(M):
for i in range(N):
if grid[j][i] == '1':
result += 1
sink(i, j)
return result
def print_grid(self, grid):
for row in grid:
print(row)
def print_ans(self, ans):
print(ans)
def test(self):
grid = [["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"]]
self.print_grid(grid)
ans = self.numIslands(grid)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
41fe3b7409fb596692851d7887d4750795996189 | georgebzhang/Python_LeetCode | /29_divide_two_integers.py | 714 | 3.765625 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
sign_dividend = -1 if dividend < 0 else 1
sign_divisor = -1 if divisor < 0 else 1
dividend = abs(dividend)
divisor = abs(divisor)
result = 0
while True:
dividend -= divisor
if dividend >= 0:
result += 1
else:
break
return sign_dividend * sign_divisor * result
def print_answer(self, ans):
print(ans)
def test(self):
dividend = 10
divisor = 3
ans = self.divide(dividend, divisor)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
4ccdd7851dc2177d6a35e72cb57069685d75f72c | echo001/Python | /python_for_everybody/exer9.1.py | 706 | 4.21875 | 4 | #Exercise 1 Write a program that reads the words in words.txt and stores them as
# keys in a dictionary. It doesn’t matter what the values are. Then you
# can use the in operator as a fast way to check whether a string is
# in the dictionary.
fname = input('Enter a file name : ')
try:
fhand = open(fname)
except:
print('Ther is no this file %s ' % fname)
exit()
word = dict()
for line in fhand:
line = line.rstrip()
# if line not in word:
# word[line] = 1
# else:
# word[line] = word[line] + 1 #count how many times the same word appear
word[line] = word.get(line,0) + 1 # the same as if.... else...
print(word)
|
19e74e3bc318021556ceec645597199996cfba98 | echo001/Python | /python_for_everybody/exer10.11.3.py | 1,251 | 4.40625 | 4 | #Exercise 3 Write a program that reads a file and prints the letters in
# decreasing order of frequency. Your program should convert all the
# input to lower case and only count the letters a-z. Your program
# should not count spaces, digits, punctuation, or anything other than
# the letters a-z. Find text samples from several different languages
# and see how letter frequency varies between languages. Compare your
# results with the tables at wikipedia.org/wiki/Letter_frequencies.
import string
fname = input('Enter a file name : ')
try:
fhand = open(fname)
except:
print('This file can not be opened. ')
exit()
letterCount = dict()
for line in fhand:
line = line.rstrip()
line = line.translate(line.maketrans('','',string.punctuation)) #delete all punctuation
linelist = line.lower()
for letter in linelist:
if letter.isdigit(): #delete all digit
continue
letterCount[letter] = letterCount.get(letter,0) + 1 #count letters from files
letterCountList = list(letterCount.items())
letterCountList.sort() #sort letters from a to z
for letter,count in letterCountList:
print(letter,count)
|
4d2c3cc265f440b827c555747ed6df82b811ebac | noamm19-meet/meet2017y1lab6 | /part4.py | 1,123 | 4.03125 | 4 | import turtle
UP_ARROW='Up'
LEFT_ARROW='Left'
DOWN_ARROW='Down'
RIGHT_ARROW='Right'
SPACEBAR='space'
UP=0
LEFT=1
DOWN=2
RIGHT=3
direction=UP
def up():
global direction
direction=UP
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x , y+10)
print(turtle.pos())
print('you pressed up')
def left():
global direction
direction=LEFT
print('you pressed left')
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x-10 , y)
print(turtle.pos())
def down():
global direction
direction=DOWN
print('you pressed down')
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x , y-10)
print(turtle.pos())
def right():
global direction
direction=RIGHT
print('you pressed right')
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x+10 , y)
print(turtle.pos())
turtle.onkeypress(up, UP_ARROW)
turtle.onkeypress(down, DOWN_ARROW)
turtle.onkeypress(left, LEFT_ARROW)
turtle.onkeypress(right, RIGHT_ARROW)
turtle.listen()
turtle.mainloop()
|
76f3d4905ac4e6d1900f10595b2988390317f54e | Himanshu1222/Perceptronalgorithm | /perceptron.py | 9,272 | 4.09375 | 4 | #Daniel Fox
#Student ID: 201278002
#Assignment 1: COMP527
import numpy as np
import random #redundant unless random.seed/random shuffle is used
class Data(object):
"""Main class which focuses on reading the dataset and sorting the data into samples,features.
filleName = name of file in string format.
Using dictionary and arrays to store the split the data between output feature y and sample x.
Dictionary makes it easy to select what classes to use when it comes to classification discrimination.
Using random to shuffle on the file data will help determine how well the algorithm performs when it is not fed with the data,
it has been commented out to make it easier to test the program.
"""
def __init__(self,fileName):
#open the file and split \n lines
self.fileData = open(fileName).read().splitlines()
self.data=[]#store all final data in the list
# randomise data set
random.seed(2)
random.shuffle(self.fileData)
temp=[]#sort out y values while looping
for i,j in enumerate(self.fileData):
#split the data between x and y
split=j.split(',class-')#split the class labels [0]=x , [1]=y
#sample data parsed out as float instead of string
x=np.array(split[0].split(',')).astype(float)#couldnt split data using numpy
y=split[1]
if y not in temp:
np.append(temp,y)
#append the samples and features into a data list.
self.data.append({'x': x, 'class-id': y})#append the dictionary
#samples
self.row = len(self.data[0]["x"]) #calculate length of each row = (4)
class Perceptron(object):
""" Create Perceptron for Assignment
Implimenting the perceptron is part of Question 2
pos is the positive class (+1)
neg is the negative class (-1) neg is set default at false so if user doesnt select a negative class number then it performs the 1 vs rest approach for question 3 and 4.
maxIter= max iteration loop to train the perceptron
D=Data class which will pass the relative information into the perceptron functions. Train data / Test data
regularisationFactor= regularisation coefficent allows user to input regularisation coefficent for question 4. It is default set to 0 for questions 2,3,4.
perceptronTrain = Uses the trianing data and calculate the weights
perceptronTest= Once training is complete test the trained perceptron with the training data using the new weights calculated.
"""
def __init__(self, pos, neg=None,maxIter=20):
self.pos = pos #positive class
self.neg = neg #negative class
self.maxIter=maxIter
def perceptronTrain(self,D,regularisationFactor = 0):
weights = np.zeros(D.row)#adding bias value and create weigths set to zero
bias=1
y = parseClassLabels(D,self.pos,self.neg)#call class function which returns the expected output values
#loop through iterations which is at 20 for assignment
for j in range(self.maxIter):
correct,incorrect=0,0 #used to find testing accuracy
#loop through the lengths of dataset
for i in range(len(D.data)):
x = D.data[i]["x"]#go through each x values
activation=np.sign(np.dot(weights,x)+bias)#activation function to determine if weights need updating
if y[i]==0: pass #first look to ignore any outputs which are set at 0
elif activation==y[i]:#then check if activation and expected output match
correct+=1
elif y[i]* activation <= 0:#update condition
#update weights formula added (1-2*regularisationFactor) cancels out while set to 0
weights=(1- 2*regularisationFactor)*weights + y[i]*x
bias+=y[i]
incorrect+=1
else:
incorrect+=1
self.weights=weights
self.accuracy=correct/(correct+incorrect)*100 #working out accuracy
return self.accuracy #return accuracy for printing data in terminal
def perceptronTest(self, D):
# get labels for test dataset
y = parseClassLabels(D,self.pos,self.neg)#get expected outputs for testing data
correct,incorrect = 0,0
#loop through the lengths of dataset
for i in range(len(D.data)):
x = D.data[i]['x']#go through each x values
activation=np.sign(np.dot(self.weights,x))#activation function to determine output
if y[i]==0:pass #check if the expected output values are 0 then dont do anything
elif y[i]==activation:#activation and expected output match
correct += 1
else:
incorrect += 1
self.accuracy=correct/(correct+incorrect)*100#calc accuracy
return self.accuracy#return accuracy for printing data in terminal
#Used to sort class labels and allow 1vs all approach
#note didnt work while in data class
def parseClassLabels(D,pos,neg):
#sets the class label relating to the dataset D.
y = {}#Store the classes in dictionary
for i in range(len(D.data)):
classNum = D.data[i]["class-id"]
if classNum == pos: #as user inputs a pos value this will become +1
y[i] = 1 #key i and value 1
elif neg: #as user inputs a neg value this will become -1
y[i] = -1 if classNum == neg else 0
else:y[i] = -1 #fix for 1vsall method , saved remaking a new function
return y
def main():
"""The main function runs all questions and prints accuracy to user.
Question 2:
Impliment the Perceptron class.
Question 3 compare:
class 1 and 2
class 2 and 3
class 1 and 3
Question 4:
Compare 1 vs all
Question 5:
add regularisation coefficent values to the 1 vs all appoach
regularisation coefficent:
[0.01, 0.1, 1.0, 10.0, 100.0]
"""
print("-------------Question 2 and 3-------------------")
train_data = Data("train.data")
train_1 = Perceptron("1","2")
train_2 = Perceptron("2","3")
train_3 = Perceptron("1","3")
print("Training Perceptron")
train_1.perceptronTrain(train_data)
train_2.perceptronTrain(train_data)
train_3.perceptronTrain(train_data)
train=[train_1,train_2,train_3]
for i in train:
print("Training Accuracy rate:%.2f%%"%i.accuracy)
test_data = Data("test.data")
print("\nTesting data")
train_1.perceptronTest(test_data)
train_2.perceptronTest(test_data)
train_3.perceptronTest(test_data)
for i in train:
print("Testing Accuracy rate:%.2f%%"%i.accuracy)
print("-----------------------------------------------")
print("----------------Question 4---------------------")
train_data = Data("train.data")
train_1 = Perceptron("1")
train_2 = Perceptron("2")
train_3 = Perceptron("3")
print("Training Perceptron")
train_1.perceptronTrain(train_data)
train_2.perceptronTrain(train_data)
train_3.perceptronTrain(train_data)
train=[train_1,train_2,train_3]
for i in train:
print("Training Accuracy rate:%.2f%%"%i.accuracy)
test_data = Data("test.data")
print("\nTesting data")
train_1.perceptronTest(test_data)
train_2.perceptronTest(test_data)
train_3.perceptronTest(test_data)
for i in train:
print("Testing Accuracy rate:%.2f%%"%i.accuracy)
print("-----------------------------------------------")
print("--------------Question 5-----------------------")
train_data = Data("train.data")
regularisation = [0.01, 0.1, 1.0, 10.0, 100.0]
train_1 = Perceptron("1")
train_2 = Perceptron("2")
train_3 = Perceptron("3")
test_data = Data("test.data")
print("Testing data")
for i in (regularisation):
print("\nRegularisation factor:%.2f\n"%i)
train_1.perceptronTrain(train_data,i)
#print("Training Accuracy rate:%.2f%%"%train_1.accuracy)#testing the training accuracy
train_1.perceptronTest(test_data)
print("Testing Accuracy rate:%.2f%%"%train_1.accuracy)
train_2.perceptronTrain(train_data,i)
#print("Training Accuracy rate:%.2f%%"%train_2.accuracy)#testing the training accuracy
train_2.perceptronTest(test_data)
print("Testing Accuracy rate:%.2f%%"%train_2.accuracy)
train_3.perceptronTrain(train_data,i)
#print("Training Accuracy rate:%.2f%%"%train_3.accuracy)#testing the training accuracy
train_3.perceptronTest(test_data)
print("Testing Accuracy rate:%.2f%%"%train_3.accuracy)
print("-----------------------------------------------")
if __name__ == '__main__':
main() |
170ba09d016d552111884a9a8802caf57c38d5a7 | gvsurenderreddy/software | /wprowadzenie_python/lotto.py | 187 | 3.75 | 4 | #!/usr/bin/env python
from random import randint
lista = []
def lotto():
a = randint(1,49)
if a not in lista:
lista.append(a)
else:
lotto()
for x in range(6):
lotto()
print lista
|
884c0ecc5e544b25657765b55c64c13b6b22ed96 | randyLobb/Rock-Ppapper-Scissors | /RPS.py | 1,577 | 4.09375 | 4 | import random
from random import randint
repeat = True
cursewords = ['fuckyou','fuck you', 'FuckYou', 'fuck','shit','fucker']
while repeat:
user_choice = input("Rock(1), Paper(2), Scisors(3): Type 1, 2, or 3. type exit to close the game: ")
Comp_choice = randint(1,3)
if user_choice == "exit":
break
if user_choice in cursewords:
print("well " + user_choice + " too!!!")
elif user_choice not in['1','2','3']:
print("I told you to type 1, 2 , or 3!")
elif int(user_choice) == 1 and Comp_choice == 1:
print("both chose Rock.it's a tie!")
elif int(user_choice) == 2 and Comp_choice == 2:
print("both chose Paper.it's a tie!")
elif int(user_choice) == 3 and Comp_choice == 3:
print("both chose scissors. It's a tie!")
elif int(user_choice) == 1 and Comp_choice == 2:
print("Computer chose paper, computer wins!")
elif int(user_choice) == 1 and Comp_choice == 3:
print("Computer chose scissors. you win!")
elif int(user_choice) == 2 and Comp_choice == 1:
print("Computer chose Rock. you win!")
elif int(user_choice) == 2 and Comp_choice == 3:
print("Computer chose sciccors. Computer wins!")
elif int(user_choice) == 3 and Comp_choice == 1:
print("Computer chose Rock. Computer Wins")
elif int(user_choice) == 3 and Comp_choice == 2 :
print("Computer chose paper. you Win!")
else:
print("I guess you can't follow simple instructions...")
print("Thanks for playing!")
|
688ef8d0f61313d828492d10031c888a65187803 | bonaert/NeuralNet | /xor.py | 876 | 3.5 | 4 | import random
from NeuralNet import NeuralNet
data = {
(0, 0): 0,
(0, 1): 1,
(1, 0): 1,
(1, 1): 0
}
TRAINING_SAMPLES = 10000
network = NeuralNet(input_size=2, hidden_layer_size=3, output_size=1, learning_rate=0.75, momentum=0.4)
# Step 1: training
samples = list(data.items())
errors = []
for i in range(TRAINING_SAMPLES):
neural_net_input, result = random.choice(samples)
error = network.train(neural_net_input, result)
errors.append(abs(error))
# Step 2: test
final_errors = []
for neural_net_input, result in data.items():
prediction = network.predict(neural_net_input)[0]
print("Input: ", neural_net_input, " -> Output: ",prediction)
final_errors.append(abs(result - prediction))
avg_error = sum(final_errors) / len(final_errors)
print("Average error: ", avg_error)
import matplotlib.pyplot as plt
plt.plot(errors)
plt.show() |
5648e2935a971992a4ccb03aae3c7b474318fb39 | uriyapes/VCL_DC | /my_utilities.py | 3,186 | 3.765625 | 4 | import os
import logging
from datetime import datetime
def set_a_logger(log_name='log', dirpath="./", filename=None, console_level=logging.DEBUG, file_level=logging.DEBUG):
"""
Returns a logger object which logs messages to file and prints them to console.
If you want to log messages from different modules you need to use the same log_name in all modules, by doing so
all the modules will print to the same files (created by the first module).
By default, when using the logger, every new run will generate a new log file - filename_timestamp.log.
If you wish to write to an existing file you should set the dirpath and filename params to the path of the file and
make sure you are the first to call set_a_logger with log_name.
:param log_name: The logger name, use the same name from different modules to write to the same file. In case no filename
is given the log_name will used to create the filename (timestamp and .log are added automatically).
:param dirpath: the logs directory.
:param filename: if value is specified the name of the file will be filename without any suffix.
:param console_level: logging level to the console (screen).
:param file_level: logging level to the file.
:return: a logger object.
"""
assert type(log_name) == str
assert type(dirpath) == str or type(dirpath) == unicode
assert type(console_level) == int
assert type(file_level) == int
if filename:
assert type(filename) == str
else:
timestamp = "_" + str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
filename = log_name + timestamp + ".log"
filepath = os.path.join(dirpath, filename)
# create logger
logger = logging.getLogger(log_name)
logger.setLevel(level=logging.DEBUG)
if not logger.handlers:
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(console_level)
fh = logging.FileHandler(filepath)
fh.setLevel(file_level)
# create formatter
formatter = logging.Formatter('%(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
logger.addHandler(fh)
# 'application' code
logger.critical('Logging level inside file is: {}'.format(logging._levelNames[file_level]))
return logger
if __name__ == '__main__':
# Test the logger wrap function - write inside log.log
logger_name = 'example'
dirpath = "./Logs"
logger = set_a_logger(logger_name, dirpath)
logger.debug('log')
# Test the logger wrap function - create a different log file and write inside it
logger_name = 'example2'
logger2 = set_a_logger(logger_name, dirpath)
logger2.debug('log2')
# Test that getting the logger from different module is possible by writing to the same file the logger used.
logger2_diff_module = set_a_logger(logger_name)
logger2_diff_module.debug('example2_diff_module')
|
e43348c97ff6d6b0ce16c9cb90d133038eb9b2a5 | optirg-39/dailycode | /F_450_58.py | 182 | 4.125 | 4 | Print all the duplicates in the input string?
#Using Hashing
r="Rishabhrishabh"
def strigduplcate(S):
d={}
for i in S:
d[i]=S.count(i)
print(strigduplcate(r))
|
6b17a0b06b3d25f439cc2951da7c0bf2528e7ffc | marialui/ADS | /quick sort.py | 674 | 3.703125 | 4 | def partition(lista,p,r):
x=lista[r]
i= p-1
for j in range (p,r):
if lista[j]< x:
i=i+1
estremo=lista[i]
lista[i] = lista[j]
lista[j]= estremo
lista[i+1], lista[r] = lista[r] , lista[i+1]
return (i+1)
#x, y = y, x is a good way to exchange variables values.
def quick_sort(lista,p,r):
if p<r:
q= partition(lista,p,r)
print('sortint on', lista[p:q - 1])
quick_sort(lista,p,q-1)
print(lista[p:q - 1])
print('sortint on', lista[q + 1:r])
quick_sort(lista, q+1,r)
array=[2,8,7,1,3,5,6,4]
quick_sort(array,0,len(array)-1)
print(array) |
f30b7b68b9b3fbfa14adc4bd4981e2b7a5bdc492 | nav-bajaj/python-course | /Intro Course/counting in a loop.py | 159 | 3.9375 | 4 | #counting in a loop
i = 0
print("Before",i)
for counter in [5,21,34,5,4,6,12,3445,4432]:
i=i+1
print(i,counter)
print("Done, total items:", i)
|
d52a1639d49854a0bc7846e74faa1d0051768da3 | CarlosTrejo2308/TestingSistemas | /ago-dic-2019/practicas/practica.py | 321 | 3.546875 | 4 | import math
def v_cilindro(radio = None, altura = None):
if radio == None:
radio = float( input("Radio: ") )
if altura == None:
altura = float( input("Volumen: ") )
volumen = math.pi * (math.pow(radio, 2)) * altura
return volumen
print(v_cilindro())
|
86a414b4486661edeca46d5b53e76d00704861c0 | marcluettecke/programming_challenges | /python_scripts/floor_puzzle.py | 2,170 | 4.09375 | 4 | """
Function to solve the following puzzle with a generator.
------------------
User Instructions
Hopper, Kay, Liskov, Perlis, and Ritchie live on
different floors of a five-floor apartment building.
Hopper does not live on the top floor.
Kay does not live on the bottom floor.
Liskov does not live on either the top or the bottom floor.
Perlis lives on a higher floor than does Kay.
Ritchie does not live on a floor adjacent to Liskov's.
Liskov does not live on a floor adjacent to Kay's.
Where does everyone live?
Write a function floor_puzzle() that returns a list of
five floor numbers denoting the floor of Hopper, Kay,
Liskov, Perlis, and Ritchie.
"""
# imports
import itertools
def is_adjacent(floor1, floor2):
"""
Function to determine if two floors are adjacent.
Args:
floor1: [int] level of floor 1
floor2: [int] level of floor 2
Returns:
[bool] if two floors are adjacent
"""
return abs(floor1 - floor2) == 1
def floor_puzzle():
"""
Function to include a bunch of restrictions on 5 inhabitants and find the solution by brute force or possible
permutations.
Returns:
[List] of the five floor numbers for the five people in the order: [Hopper, Kay, Liskov, Perlis, Ritchie]
"""
floors = bottom, _, _, _, top = [1, 2, 3, 4, 5]
orderings = list(itertools.permutations(floors))
return next([Hopper, Kay, Liskov, Perlis, Ritchie]
for [Hopper, Kay, Liskov, Perlis, Ritchie] in orderings
# Hopper does not live on the top floor.
if Hopper is not bottom
# Kay does not live on the bottom floor.
if Kay is not bottom
# Liskov does not live on either the top or the bottom floor.
if Liskov not in [bottom, top]
# Perlis lives on a higher floor than does Kay.
if Perlis > Kay
# Ritchie does not live on a floor adjacent to Liskov's.
if is_adjacent(Ritchie, Liskov) == False
# Liskov does not live on a floor adjacent to Kay's.
if is_adjacent(Liskov, Kay) == False)
|
3168d9379b4ff8064b60ed5e6db65d504c91f5a0 | marcluettecke/programming_challenges | /python_scripts/rot13_translation.py | 482 | 4.125 | 4 | """
Function to shift every letter by 13 positions in the alphabet. Clever use of maketrans and translate.
"""
trans = str.maketrans('ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
def rot13(message):
"""
Translation by rot13 encoding.
Args:
message: string such as 'Test'
Returns:
translated string, such as 'Grfg'
"""
return message.translate(trans)
|
9694eb43b3219502319ca40dbf580a88bf309c85 | khaleeque-ansari/CodeChef-Problem-Solutions-Python | /Python Codes/HS08TEST.py | 255 | 3.671875 | 4 |
amount, balance = [float(x) for x in raw_input().split()]
if amount%5 != 0:
print '%.2f' %balance
elif amount > balance - 0.50:
print '%.2f' %balance
else :
print '%.2f' % (balance - amount - 0.50)
|
ae038beb027640e3af191d24c6c3abbb172e398e | mihaidobri/DataCamp | /SupervisedLearningWithScikitLearn/Classification/02_TrainTestSplit_FitPredictAccuracy.py | 777 | 4.125 | 4 | '''
After creating arrays for the features and target variable, you will split them into training and test sets,
fit a k-NN classifier to the training data, and then compute its accuracy using the .score() method.
'''
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
# Create feature and target arrays
X = digits.data
y = digits.target
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=42, stratify=y)
# Create a k-NN classifier with 7 neighbors: knn
knn = KNeighborsClassifier(n_neighbors = 7)
# Fit the classifier to the training data
knn.fit(X_train,y_train)
# Print the accuracy
print(knn.score(X_test, y_test))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.