blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
7268b115110cd7b7564f7819a252c1ad71337111
StudiousStone/CNN_Accelerator
/Deep_Learning_from_Scratch/Ch03_Neural_Network/Activiation_Functions/step_function.py
231
3.578125
4
import numpy as np def step_function(x): y = x > 0 # Compare x with 0 which returns boolean type to y. return y.astype(np.int) # Transform boolean type to int value. # Test function print(step_function(np.array([-1.0, 2.0])))
640cdfbd67bcc920e76ab66aed2a1eabcbebed03
MaazShah2060/Hangman_game
/hint.py
501
3.6875
4
import random def give_clue(word): hinti1 = random.randrange(len(word)) hinti2 = random.randrange(len(word)) def replace_all(hinti): for i in range(len(word)): if word[i] == word[hinti]: cluelist[i] = word[hinti] return cluelist while hinti2 == hinti1: hinti2 = random.randrange(len(word)) cluelist = ['*' for i in range(len(word))] cluelist = replace_all(hinti1) if len(word) > 8: cluelist = replace_all(hinti2) return ''.join(cluelist)
e833be3ea7d7014127926e2a405a5c128ef3de5e
guli732/python_simple
/stars.py
174
3.8125
4
for i in range(5): print(' ' * (5 - i), end='') print('*' * (i * 2 + 1)) for i in range(5, -1, -1): print(' ' * (5 - i), end='') print('*' * (i * 2 + 1))
94b6dc2022b9daf0a2a8c6c4e5a191faeb51f3eb
Chloe-Codes/project-euler-python
/eu4.py
904
3.84375
4
#################################################### ## ## ## Project Euler Exercise 4 Solution ## ## Chloe Dyke 2017 ## ## ## ## Solution: 906609 ## #################################################### # Find the largest palindrome made from the product of two 3-digit numbers. from itertools import product largest_palindrome = 0 # Check if palindrome def check_palindrome(num): str_num = str(num) if str_num == str_num[::-1]: # Check if the reversed string is the same as the string return True else: return False #Tried to find max palindrome in most pythonic way I could palindromes = [i * j for i in range(999) for j in range(999) if check_palindrome(i*j)] print(max(palindromes))
2d91c7b4559bbaeef7988e13dce4b125e85ed655
slarkcc/common_web
/common/class_object.py
25,529
3.859375
4
# -*- coding: utf-8 -*- # @Time : 2018/2/8 13:55 # @author : slark # @File : class_object.py # @Software: PyCharm from functools import partial import math # 创建大量对象时节省内存 class Date(object): __slots__ = ["year", "month", "day"] # 使用slots后,不能再给实例添加新属性 def __init__(self, year, month, day): self.year = year self.month = month self.day = day # 创建可管理的属性 class Person: def __init__(self, first_name): self.first_name = first_name # Getter function @property def first_name(self): return self._first_name # Setter function @first_name.setter def first_name(self, value): if not isinstance(value, str): raise TypeError('Expected a string') self._first_name = value # Deleter function (optional) @first_name.deleter def first_name(self): raise AttributeError("Can't delete attribute") class Person1(object): def __init__(self, first_name): self.set_first_name(first_name) def get_first_name(self): return self._first_name def set_first_name(self, value): if not isinstance(value, str): raise TypeError("Expected a string") self._first_name = value def del_first_name(self): raise AttributeError("Can't delete attribute") name = property(get_first_name, set_first_name, del_first_name) class Circle(object): def __init__(self, radius): self.radius = radius @property def area(self): return math.pi * self.radius ** 2 @property def diameter(self): return self.radius * 2 @property def perimeter(self): return 2 * math.pi * self.radius # 调用父类方法 class A1(object): def spam(self): print('A.spam') class B1(A1): def spam(self): print('B.spam') super(B1, self).spam() class A2(object): def __init__(self): self.x = 0 class B2(A2): def __init__(self): super(B2, self).__init__() # 用来保障父类的初始化被正确执行 self.y = 1 class Proxy(object): def __init__(self, obj): self._obj = obj def __getattr__(self, item): return getattr(self._obj, item) def __setattr__(self, key, value): if key.startswith('_'): super(Proxy, self).__setattr__(key, value) else: setattr(self._obj, key, value) # 在子类中扩展property class Person2(object): def __init__(self, name): self.name = name @property def name(self): return self._name @name.setter def name(self, value): if not isinstance(value, str): raise TypeError("Expected a string") self._name = value @name.deleter def name(self): raise AttributeError("Can't delete attribute") class SubPerson(Person2): @property def name(self): print("Getting name") return super(SubPerson, self).name @name.setter def name(self, value): print('Setting name to', value) super(Person2, self).name.__set__(self, value) @name.deleter def name(self): print("Deleting name") super(Person2, self).name.__delete__(self) # 创建新的类或实例属性 class Integer(object): def __init__(self, name): self.name = name def __get__(self, instance, cls): if instance is None: return self else: return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value, int): raise TypeError("Expected an int") instance.__dict__[self.name] = value def __delete__(self, instance): del instance.__dict__[self.name] # 改变对象的字符串显示 class Pair(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): # __repr__() 方法返回一个实例的代码表示形式,通常用来重新构造这个实例。 内置的 repr() 函数返回这个字符串,跟我们使用交互式解释器显示的值是一样的 return "Pair {0.x!r}, {0.y!r}".format(self) # !r 格式化代码指明输出使用 __repr__() 来代替默认的 __str__() def __str__(self): # __str__() 方法将实例转换为一个字符串,使用 str() 或 print() 函数会输出这个字符串,如果str没有定义就会被repr代替 return "{0.x!s}, {0.y!s}".format(self) # 自定义字符串的格式化 _formats = { 'ymd': '{d.year}-{d.month}-{d.day}', 'mdy': '{d.month}/{d.day}/{d.year}', 'dmy': '{d.day}/{d.month}/{d.year}', } class Date(object): def __init__(self, year, month, day): self.year = year self.month = month self.day = day def __format__(self, format_spec): if format_spec == '': format_spec = 'ymd' fmt = _formats[format_spec] return fmt.format(d=self) # 让对象支持上下文管理协议 from socket import socket, AF_INET, SOCK_STREAM class LazyConnection(object): def __init__(self, address, family=AF_INET, type=SOCK_STREAM): self.address = address self.family = family self.type = type self.sock = None def __enter__(self): if self.sock is not None: raise RuntimeError("Already connected") self.sock = socket(self.family, self.type) self.sock.connect(self.address) return self.sock def __exit__(self, exc_type, exc_val, exc_tb): self.sock.close() self.sock = None class LazyConnection1(object): def __init__(self, address, family=AF_INET, type=SOCK_STREAM): self.address = address self.family = family self.type = type self.connections = [] def __enter__(self): sock = socket(self.family, self.type) sock.connect(self.address) self.connections.append(sock) return sock def __exit__(self, exc_type, exc_val, exc_tb): self.connections.pop().close() from functools import partial conn1 = LazyConnection1(('www.python.org', 80)) with conn1 as s1: pass with conn1 as s2: pass conn = LazyConnection(('www.python.org', 80)) with conn as s: s.send(b'GET /index.html HTTP/1.0\r\n') s.send(b'Host: www.python.org\r\n') s.send(b'\r\n') resp = b''.join(iter(partial(s.recv, 8192), b'')) # 创建大量对象时节省内存方法 class Date(object): __slots__ = ['year', 'month', 'day'] def __init__(self, year, month, day): self.year = year self.month = month self.day = day # 在类中封装属性名 class A(object): def __init__(self): self._internal = 0 self._public = 1 def public_method(self): pass def _internal_method(self): pass class B(object): def __init__(self): self.__private = 0 # 变成_B__private def __private_method(self): # 变成_B__private_method pass def public_method(self): pass class C(B): def __init__(self): super().__init__() # python3中可以直接super().method()但在python2中super(C, self).method() self.__private = 1 # 不能覆盖父类的属性 def __private_method(self): print("hell") # super()用法,super()根据传进去的两个参数: # 通过第一参数传进去的类名确定当前在MRO中的哪个位置。MRO(Method Resolution Order) # 通过第二个参数传进去的self,确定当前的MRO列表 # def super(cls, inst): # mro = inst.__class__.mro() #确定当前MRO列表 # return mro[mro.index(cls) + 1] #返回下一个类 # MRO列表遵循的三条准则(C3 算法): # 子类会先于父类被检查 # 多个父类会根据它们在列表中的顺序被检查 # 如果对下一个类存在两个合法的选择,选择第一个父类 class A(object): def name(self): print('from A') super(A, self).name() class B(object): def name(self): print('from B') class C(A, B): def name(self): print('from C') super(C, self).name() # 创建可管理的属性 class Person(object): def __init__(self, first_name): self.first_name = first_name @property def first_name(self): # 必须先定义first_name属性 return self._first_name # 数据实际保存的地方 @first_name.setter def first_name(self, value): if not isinstance(value, str): raise TypeError("Expected a string") self._first_name = value @first_name.deleter def first_name(self): raise AttributeError("Can't delete attribute") class Person(object): def __init__(self, first_name): self.first_name = first_name def get_first_name(self): return self.first_name def set_first_name(self, value): if not isinstance(value, str): raise TypeError("Expected a string") self.first_name = value def del_first_name(self): raise AttributeError("Can't delete attribute") name = property(get_first_name, set_first_name, del_first_name) # 调用父类方法 class A(object): def spam(self): print("A: spam") class B(A): def spam(self): print("B: spam") super(B, self).spam() class A(object): def __init__(self): self.x = 0 class B(A): def __init__(self): super(B, self).__init__() self.y = 1 class Proxy(object): def __init__(self, obj): self.obj = obj def __getattr__(self, item): return getattr(self.obj, item) def __setattr__(self, key, value): if key.startswith('_'): super(Proxy, self).__setattr__(key, value) else: setattr(self.obj, key, value) # 子类中扩展property class Person(object): def __init__(self, name): self.name = name @property def name(self): return self._name @name.setter def name(self, value): if not isinstance(value, str): raise TypeError("Expected a string") self._name = value @name.deleter def name(self): raise AttributeError("Can't delete attribute") # 重写父类的name属性 class SubPerson(Person): @property def name(self): print('Getting name') return super().name @name.setter def name(self, value): print('Setting name to') super(SubPerson, SubPerson).name.__set__(self, value) @name.deleter def name(self): print('Deleting name') super(SubPerson, SubPerson).name.__delete__(self) # 只重写某个方法 class SubPerson(object): @Person.name.getter def name(self): print("Getting name") return super().name class SubPerson(Person): @Person.name.setter def name(self, value): print('Setting name to', value) super(SubPerson, SubPerson).name.__set__(self, value) # 创建新的类或实例属性 class Integer(object): def __init__(self, name): self.name = name def __get__(self, instance, owner): if instance is None: return self else: return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value, int): raise TypeError("Expected int") instance.__dict__[self.name] = value def __delete__(self, instance): del instance.__dict__[self.name] class Point(object): x = Integer('x') y = Integer('y') def __init__(self, x, y): self.x = x self.y = y class Typed(object): def __init__(self, name, expected_type): self.name = name self.expected_type = expected_type def __get__(self, instance, owner): if instance is None: return self else: return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value, self.expected_type): raise TypeError('Expected' + str(self.expected_type)) instance.__dict__[self.name] = value def __delete__(self, instance): del instance.__dict__[self.name] def typeassert(**kwargs): def decorate(cls): for name, expected_type in kwargs.items(): setattr(cls, name, Typed(name, expected_type)) return cls return decorate @typeassert(name=str, shares=int, price=float) class Stock(object): def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price # 使用延迟计算属性 class Lazyproperty(object): def __init__(self, func): self.func = func def __get__(self, instance, owner): if instance is None: return self else: value = self.func(instance) setattr(instance, self.func.__name__, value) return value import math class Circle(object): def __init__(self, radius): self.radius = radius @Lazyproperty def area(self): print("Computing area") return math.pi * self.radius * 2 @Lazyproperty def perimeter(self): print("Computing perimeter") return 2 * math.pi * self.radius # 简化数据结构的初始化 import math class Structure1(object): _fields = [] def __init__(self, *args): if len(args) != len(self._fields): raise TypeError("Expected {} arguments".format(len(self._fields))) for name, value in zip(self._fields, args): setattr(self, name, value) class Stock(Structure1): _fields = ['name', 'shares', 'price'] class Point(Structure1): _fields = ['x', 'y'] class Circle(Structure1): _fields = ['radius'] def area(self): return math.pi * self.radius ** 2 class Structure2(object): _fields = [] def __init__(self, *args, **kwargs): if len(args) > len(self._fields): raise TypeError("Expected {} arguments".format(len(self._fields))) for name, value in zip(self._fields, args): setattr(self, name, value) for name in self._fields[len(args):]: setattr(self, name, kwargs.pop(name)) if kwargs: raise TypeError("Invalid argument(s):".format(','.join(kwargs))) class Structure3(object): _fields = [] def __init__(self, *args, **kwargs): if len(args) != len(self._fields): raise TypeError("Expected {} arguments".format(len(self._fields))) for name, value in zip(self._fields, args): setattr(self, name, value) extra_args = kwargs.keys() - self._fields for name in extra_args: setattr(self, name, kwargs.pop(name)) if kwargs: raise TypeError("Duplicate values for {}".format(','.join(kwargs))) # 定义接口或者抽象基类 from abc import ABCMeta, abstractmethod class IStream(metaclass=ABCMeta): @abstractmethod def read(self, maxbytes=-1): pass @abstractmethod def write(self, data): pass def serialize(obj, stream): if not isinstance(stream, IStream): raise TypeError("Expected an IStream") pass import io IStream.regester(io.IOBase) f = open('foo.txt') isinstance(f, IStream) # 实现数据模型的类型约束 class Descriptor(object): def __init__(self, name=None, **opts): self.name = name for key, value in opts.items(): setattr(self, key, value) def __set__(self, instance, value): instance.__dict__[self.nane] = value class Typed(Descriptor): expected_type = type(None) def __set__(self, instance, value): if not isinstance(value, self.expected_type): raise ValueError("expected" + str(self.expected_type)) super(Typed, self).__set__(instance, value) class Unsigned(Descriptor): def __set__(self, instance, value): if value < 0: raise ValueError("Expected >= 0") super().__set__(instance, value) class MaxSized(Descriptor): def __init__(self, name=None, **opts): if 'size' not in opts: raise TypeError("missing size option") super(MaxSized, self).__init__(name, **opts) def __set__(self, instance, value): if len(value) >= self.size: raise ValueError('size must be <' + str(self.size)) super(MaxSized, self).__set__(instance, value) # 使用类装饰器 def check_attribute(**kwargs): def decorator(cls): for key, value in kwargs.items(): if isinstance(value, Descriptor): value.name = key setattr(cls, key, value) else: setattr(cls, key, value(key)) return cls return decorator @check_attribute(name=SizedString(size=8), shares=UnsignedInteger, price=UnsignedFloat) class Stock(object): def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price # 使用元类实现 class checkedmeta(type): def __new__(cls, clsname, bases, methods): for key, value in methods.items(): if isinstance(value, Descriptor): value.name = key return type.__new__(cls, clsname, bases, methods) # 实现自定义容器 import collections import bisect class A(collections.Iterable): pass class SortedItems(collections.Sequence): def __init__(self, initial=None): self._items = sorted(initial) if initial is not None else [] def __getitem__(self, item): return self._items[item] def __len__(self): return len(self._items) def __add__(self, other): bisect.insort(self._items, other) # 属性的代理访问 class A(object): def spam(self, x): pass def foo(self): pass class B1(object): def __init__(self): self._a = A() def spam(self, x): return self._a.spam(x) def foo(self): return self._a.foo() def bar(self): pass # 当有大量方法时 class B2(object): def __init__(self): self._a = A() def bar(self): pass def __getattr__(self, item): return getattr(self._a, item) # 实现代理模式 class Proxy(object): def __init__(self, obj): self._obj = obj def __getattr__(self, item): print("getattr:", item) return getattr(self._obj, item) def __setattr__(self, key, value): if key.startswith("_"): super().__setattr__(key, value) else: print("setattr:", key, value) setattr(self._obj, key, value) def __delattr__(self, item): if item.startswith("_"): super().__delattr__(item) else: print("delattr:", item) delattr(self._obj, item) class Spam(object): def __init__(self, x): self.x = x def bar(self, y): print('spam.bar:', self.x, y) s = Spam(3) p = Proxy(s) print(p.x) p.bar() p.x = 37 # 在类中定义多个构造器 import time class Date(object): def __init__(self, year, month, day): self.year = year self.month = month self.day = day @classmethod def today(cls): t = time.localtime() return cls(t.tm_year, t.tm_mon, t.tm_mday) # 创建不调用init方法的实例 class Date(object): def __init__(self, year, month, day): self.year = year self.month = month self.day = day d = Date.__new__(Date) # 绕过__init__方法,这样d是没有year, month, day属性的 d.year # 报错 from time import localtime class Date(object): def __init__(self, year, month, day): self.year = year self.month = month self.day = day @classmethod def today(cls): d = cls.__new__(cls) t = localtime() d.year = t.tm_mday d.month = t.tm_mon d.day = t.tm_mday return d # 利用Mixins扩展功能 class LoggedMappingMixin(object): __slots__ = () def __getitem__(self, item): print("Getting " + str(item)) return super().__getitem__(item) def __setitem__(self, key, value): print("Setting {} = {!r}".format(key, value)) return super().__setitem__(key, value) def __delitem__(self, key): print("Deleting " + str(key)) return super().__delitem__(key) class SetOnceMappingMixin(object): __slots__ = () def __setitem__(self, key, value): if key in self: raise KeyError(str(key) + "already set") return super().__setitem__(key, value) class StringKeyMappingMixin(object): __slots__ = () def __setitem__(self, key, value): if not isinstance(key, str): raise TypeError('key must be strings') return super().__setitem__(key, value) class LoggedDict(LoggedMappingMixin, dict): pass # 实现状态对象或者状态机 class Connection(object): def __init__(self): self.state = "CLOSED" def read(self): if self.state != "OPEN": raise RuntimeError('Not open') print('reading') def write(self, data): if self.state != "OPEN": raise RuntimeError("Not open") print("writing") def open(self): if self.state == "OPEN": raise RuntimeError("Already open") self.state = "OPEN" def close(self): if self.state == "CLOSED": raise RuntimeError("Already closed") self.state = "CLOSED" class Connection1(object): def __init__(self): self.new_state(ClosedConnectionState) def new_state(self, newstate): self._state = newstate def read(self): return self._state.read(self) def write(self, data): return self._state.write(self, data) def open(self): return self._state.open(self) def close(self): return self._state.close(self) class ConnectionState(object): @staticmethod def read(conn): raise NotImplementedError() @staticmethod def write(conn): raise NotImplementedError() @staticmethod def open(): raise NotImplementedError() @staticmethod def close(): raise NotImplementedError() class ClosedConnectionState(ConnectionState): @staticmethod def read(conn): raise RuntimeError('Not open') @staticmethod def write(conn): raise RuntimeError("Not open") @staticmethod def open(conn): conn.new_state(OpenConnectionState) @staticmethod def close(conn): raise RuntimeError('Already closed') class OpenConnectionState(ConnectionState): @staticmethod def read(conn): print('reading') @staticmethod def write(conn, data): print('writing') @staticmethod def open(conn): raise RuntimeError('Already open') @staticmethod def close(conn): conn.new_state(ClosedConnectionState) # 通过字符串调用对象方法 import math class Point(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return 'Point({!r:},{!r:})'.format(self.x, self.y) def distance(self, x, y): return math.hypot(self.x - x, self.y - y) p = Point(2, 3) d = getattr(p, 'distance')(0, 0) import operator operator.methodcaller('distance', 0, 0)(p) # 实现访问者模式 class Node(object): pass class UnaryOperator(Node): def __init__(self, operand): self.operand = operand class BinaryOperator(Node): def __init__(self, left, right): self.left = left self.right = right class Add(BinaryOperator): pass class Sub(BinaryOperator): pass class Mul(BinaryOperator): pass class Div(BinaryOperator): pass class Negate(UnaryOperator): pass class Number(Node): def __init__(self, value): self.value = value class NodeVisitor(object): def visit(self, node): methname = 'visit_' + type(node).__name__ meth = getattr(self, methname, None) if meth is None: meth = self.generic_visit return meth(node) def generic_visit(self, node): raise RuntimeError("No {} method".format('visit_' + type(node).__name__)) class Evaluator(NodeVisitor): def visit_number(self, node): return node.value def visit_Add(self, node): return self.visit(node.left) + self.visit(node.right) def visit_Sub(self, node): return self.visit(node) # 创建缓存实例 class Spam: def __init__(self, name): self.name = name import weakref _spam_cache = weakref.WeakValueDictionary() def get_spam(name): if name not in _spam_cache: s = Spam(name) _spam_cache[name] = s else: s = _spam_cache[name] return s class Spam(object): _spam_cache = weakref.WeakKeyDictionary() def __new__(cls, name): if name in cls._spam_cache: return cls._spam_cache[name] else: self = super(Spam, cls).__new__(cls) cls._spam_cache[name] = self return self def __init__(self, name): print("initializing spam") self.name = name
ae9e8ccfee70ada5d6f60a9e8a16f3c2204078ca
OmarSamehMahmoud/Python_Projects
/Pyramids/pyramids.py
381
4.15625
4
height = input("Please enter pyramid Hieght: ") height = int(height) row = 0 while row < height: NumOfSpace = height - row - 1 NumOfStars = ((row + 1) * 2) - 1 string = "" #Step 1: Get the spaces i = 0 while i < NumOfSpace: string = string + " " i += 1 #step 2: Get the stars i = 0 while i < NumOfStars: string = string + "*" i +=1 print(string) row += 1
b61f342e7ce8ec8859e07dbe1ab4c1917f79743f
OmarSamehMahmoud/Python_Projects
/To_Do/Todo.py
769
4.09375
4
ToDo=list() Done=list() print("************************************") print("To Add New Item Press 1") print("To Print the To Do List Press 2") print("To Mark an item as Done Press 3") print("To Print the Done list Press 4") print("************************************") i=1 while i > 0 : choice=input("Please enter your choice: ") if choice == '1': item=input("Please Enter Item to add: ") ToDo.append(item) print("Thank you, Item added successfully.") elif choice == '2': print(ToDo) elif choice == '3': index=input("Please enter item index : ") index=int(index) DoneItem=ToDo.pop(index) Done.append(DoneItem) print("Thank you, Item added successfully.") elif choice == '4': print(Done) else: print("Wrong Choice, Please Try Again.") i+=1
4a2c3eb31eeb2b162d28fd64c80823550718e093
kapilchandrawal/Decorators-and-Generators
/print_file_content_generator.py
677
3.90625
4
#3) Use Generators to read the file And Print all the words in a file. def read_large_file(file_handler): for line in file_handler: word_arr= [] for i in line: if(i != " " and i != "/n"): word_arr.append(i) else: yield word_arr word_arr = [] with open('/Python practice/Problems on deco and gen/text_content.txt', 'r') as file_handler: x = read_large_file(file_handler) print(x.__next__()) print(x.__next__()) print(x.__next__()) print(x.__next__()) print(x.__next__()) print(x.__next__())
11bfd401d28dd8a98793ab5576f12f4a413d9db3
hectorpla/inference_fol
/unification_test.py
2,403
3.5625
4
import homework3 as hw3 import itertools def var_name_generator(): name_tab = ['x', 'y', 'z', 'w', 'p', 'q'] counter = itertools.count(1) while True: num = next(counter) stack = [] name = '' while num: num -= 1 stack.append(name_tab[num % 6]) num //= 6 while len(stack): name += stack.pop() yield name def std_var_in_clause(clause, name_gen, map): assert isinstance(clause, hw3.Clause) cur = clause.next while cur: std_var_in_pred(cur, name_gen, map) cur = cur.next # map: variable name(string) to variable object, # for example: 'a' -> Variable('x') def std_var_in_pred(pred, name_gen, map): assert isinstance(pred, hw3.Predicate) l = pred.args for i in range(len(l)): if l[i].type == 'var': if l[i].value not in map: map[l[i].value] = l[i] print('std var: new pair added ', map) l[i].value = next(name_gen) else: l[i] = map[l[i].value] w = ''' Bird(x) Bird(Kak) Mother(x,y) Mother(Salsa,John) Love(x, Rose) Love(Jack,y) ''' # variable standardization q = '''Sells(Bob, x) Sells(x, Coke) Kicks(a, Football) Kicks(Even, a) Beats(Donnie, x, y, z) Beats(x, Kimura, Santos, Clinton) A(x, y, z) A(y, x, Bob)''' # between constant p = '''Tall(Bob) Tall(Bob) Fakes(Tony, Gold) Fakes(x, Gold)''' # can't unify e = ''' K(A) K(B) K(B,C) K(M,N)''' # compound clause o = ''' A(x) | B(x) B(David) D(y) | C(x,y) C(x, Wenger)''' lines = o.splitlines() cls = [] for line in lines: l = line.replace(' ', '') print(l) cl = hw3.tell(hw3.KB, l) hw3.print_clause(cl) cls.append(cl) l = [cl.next.args for cl in cls] for i in range(0, len(cls), 2): print ('\nunification: ') var_name_gen = var_name_generator() std_var_in_clause(cls[i], var_name_gen, {}) hw3.print_clause(cls[i]) std_var_in_clause(cls[i+1], var_name_gen, {}) hw3.print_clause(cls[i+1]) sub = hw3.unify(l[i],l[i+1], {}) hw3.print_subst(sub) hw3.subst(sub, cls[i]) print('after substitution') hw3.print_clause(cls[i])
9ed6da10988cdca419a06290c6f66b8540f0a773
jaehyek/Raspberri-Pi-GoPiGo-Robot-EKF-SLAM
/CalibrateRobot.py
1,061
3.640625
4
import MoveRobot import SenseLandmarks # Commands that are used to measure robot movement and sensing uncertainty. # The outputs wil be used to compte the move and sense uncertainty covariance matrices. # Constants NUMBER_OF_ITERATIONS = 15 # Get data for movement forward uncertainty def calibrate_move(): count = 0 while (True): count += 1 if count > NUMBER_OF_ITERATIONS: break MoveRobot.go_forward(MoveRobot.ROBOT_LENGTH_CM) raw_input("Press Enter to continue") # Get data for rotation uncertainty def calibrate_turn(): angle = 5 count = 0 while (True): count += 1 if count > NUMBER_OF_ITERATIONS: break print("Going to turn ", angle, " degrees.") MoveRobot.turn_in_place(angle) angle += 5 raw_input("Press Enter to continue") # Get data for landmark sensing uncertainty def calibrate_sense(): count = 0 while (True): count += 1 if count > NUMBER_OF_ITERATIONS: break obstacle_range = SenseLandmarks.make_sweep() print("Obstacle range ", obstacle_range) raw_input("Press Enter to continue")
4e2ee1f8ba0536c153fb239fe59c363374adeda8
adityahari95/MachineLearning-HandsON
/Stemming.py
1,474
3.625
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 22 11:35:20 2019 @author: 10649929 """ import nltk from nltk.stem import PorterStemmer from nltk.corpus import stopwords paragraph="""I have three visions for India. In 3000 years of our history people from all over the world have come and invaded us, captured our lands, conquered our minds. From Alexander onwards the Greeks, the Turks, the Moguls, the Portuguese, the British, the French, the Dutch, all of them came and looted us, took over what was ours. Yet we have not done this to any other nation. We have not conquered anyone. We have not grabbed their land, their culture and their history and tried to enforce our way of life on them. Why? Because we respect the freedom of others. That is why my FIRST VISION is that of FREEDOM. I believe that India got its first vision of this in 1857, when we started the war of Independence. It is this freedom that we must protect and nurture and build on. If we are not free, no one will respect us.""" sentences= nltk.sent_tokenize(paragraph) stemmer= PorterStemmer() for i in range(len(sentences)): words=nltk.word_tokenize(sentences[i]) words=[stemmer.stem(word) for word in words if word not in set(stopwords.words('english'))] sentences[i]=''.join(words)
5a4558a55bd9337d9b08cfb8cae9bd6fd32c65a8
fortunesd/PYTHON-TUTORIAL
/dictionary.py
1,232
3.828125
4
# A Dictionary is a collection that is unordered, chanagableand indexed. No duplicate member is allowed for this #create a Dictionary person_detail = { 'first_name': 'fortunes', 'last_name': 'onyekwere', 'age': 21 } # Use of a constructor person_details2 = dict(first_name = 'fortunes', last_name='onyekwere') print(person_detail) # Getting a value print(person_detail['first_name']) # Add key value person_detail['phone_number'] = '+2347067162698' print(person_detail) # Get dictionary keys print(person_detail.keys()) # Get dictionary items print(person_detail.items()) #copy dictionary person_information = person_detail.copy() print(person_information) # Remove item del (person_detail['last_name']) person_detail.pop('phone_number') print(person_detail) # Clear #person_detail.clear() print(person_detail) # Get length print(len(person_detail)) # make a list of dictionaries persons = [ {'name':'fortunes','age': 21, 'phone_number': '+234706012548'}, {'name':'fortunes','age': 21, 'phone_number': '+2347083915552'}, {'name':'ola','age': 30, 'phone_number': '+2348156243419'}, ] print(persons[1]['name']) print(persons[0]['age']) print(persons[2]['phone_number']) print(persons[2]['age'])
b746c7e3d271187b42765b9bf9e748e79ba29eca
fortunesd/PYTHON-TUTORIAL
/loops.py
792
4.40625
4
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a set, or a string). students = ['fortunes', 'abdul', 'obinaka', 'amos', 'ibrahim', 'zaniab'] # simple for loop for student in students: print(f'i am: {student}') #break for student in students: if student == 'odinaka': break print(f'the student is: {student}') #continue for student in students: if student == 'odinaka': continue print(f'the people included: {students}') #range for person in range(len(student)): print(f'number: {person}') # custom range for n in range(0, 12): print(f'number: {n}') # while loops excute a set of statements as long as a condition is true. count = 0 while count < 10: print(f'count: {count}') count += 1
ba268ca83e056fe2fc07057d54f1e85018697e27
bangour2/Pyhton-codes-project
/cgi-html-141023/usr/lib/cgi-bin/clubs_sqlite/databaseSqlite.py
3,123
3.859375
4
''' Created on Aug 12, 2013 Database methods for the clubs example @author: Ben ''' import sqlite3 def getConnection(): ''' Return a connection to the database ''' conn = sqlite3.connect('clubs.db') return conn def getPersonById(ident): ''' Return a tuple with data from the person table for the given id. Returns in order: ident, name, email ''' conn = getConnection() cmd = "select ident, name, email from person where ident=?" cursor = conn.execute(cmd,(ident,)) pdata = cursor.fetchone() conn.close() return pdata def getListOfPeople(): ''' return a list of tuples with information from the person database. Each tuple is (ident, name, email) ''' conn = getConnection() cmd = "select ident, name, email from person" cursor = conn.execute(cmd) rtval = cursor.fetchall() conn.close() return rtval def getGroupById(ident): ''' Return a tuple with data from the group table for the given id. Returns in order: ident, name, description ''' conn = getConnection() cmd = "select ident, name, description from `group` where ident=?" cursor = conn.execute(cmd,(ident,)) pdata = cursor.fetchone() conn.close() return pdata def getListOfGroups(): ''' return a list of tuples with information from the group database. Each tuple is (ident, name, description) ''' conn = getConnection() cmd = "select ident, name, description from `group`" cursor = conn.execute(cmd) rtval = cursor.fetchall() conn.close() return rtval def getClubById(ident): ''' Return a tuple with data from the club table for the given id. Returns in order: ident, name, description, president_id ''' conn = getConnection() cmd = "select ident, name, description, president_id from `club` where ident=?" cursor = conn.execute(cmd,(ident,)) pdata = cursor.fetchone() conn.close() return pdata def getListOfClubs(): ''' return a list of tuples with information from the club database. Each tuple is (ident, name, description, president_id) ''' conn = getConnection() cmd = "select ident, name, description, president_id from club" cursor = conn.execute(cmd) rtval = cursor.fetchall() conn.close() return rtval def savePersonData(pdata): ''' Save the data given in the tuple: (ident, name, email) ''' conn = getConnection() cmd = 'update person set name = ?, email = ? where ident = ?' conn.execute(cmd, (pdata[1], pdata[2], pdata[0])) conn.commit() conn.close() def saveGroupData(gdata): ''' Save the data given in the tuple: (ident, name, description) ''' conn = getConnection() cmd = 'update `group` set name = ?, description = ? where ident = ?' conn.execute(cmd, (gdata[1], gdata[2], gdata[0])) conn.commit() conn.close() if __name__ == '__main__': pass
6d3f673aad4128477625d3823e3cf8688fc89f2f
CollinNatterstad/RandomPasswordGenerator
/PasswordGenerator.py
814
4.15625
4
def main(): #importing necessary libraries. import random, string #getting user criteria for password length password_length = int(input("How many characters would you like your password to have? ")) #creating an empty list to store the password inside. password = [] #establishing what characters are allowed to be chosen. password_characters = string.ascii_lowercase + string.ascii_uppercase + string.digits #for loop to iterate over the password_length choosing a character at random from the pool of choices in password_characters. for x in range (password_length): password.append(random.choice(password_characters)) #printing the password to the terminal. print("".join(password)) if __name__ == "__main__": main()
2b33a5ed96a8a8c320432581d71f2c46b2a3998a
laufzeitfehlernet/Learning_Python
/math/collatz.py
305
4.21875
4
### To calculate the Collatz conjecture start = int(input("Enter a integer to start the madness: ")) loop = 1 print(start) while start > 1: if (start % 2) == 0: start = int(start / 2) else: start = start * 3 + 1 loop+=1 print(start) print("It was in total", loop, "loops it it ends!")
dfa330f673a2b85151b1a06ca63c3c78214c722e
joq0033/ass_3_python
/with_design_pattern/abstract_factory.py
2,239
4.25
4
from abc import ABC, abstractmethod from PickleMaker import * from shelve import * class AbstractSerializerFactory(ABC): """ The Abstract Factory interface declares a set of methods that return different abstract products. These products are called a family and are related by a high-level theme or concept. Products of one family are usually able to collaborate among themselves. A family of products may have several variants, but the products of one variant are incompatible with products of another. """ @abstractmethod def create_serializer(self): pass class ConcretePickleFactory(AbstractSerializerFactory): """ Concrete Factories produce a family of products that belong to a single variant. The factory guarantees that resulting products are compatible. Note that signatures of the Concrete Factory's methods return an abstract product, while inside the method a concrete product is instantiated. """ def create_serializer(self): return MyPickle('DocTestPickle.py', 'test') class ConcreteShelfFactory(AbstractSerializerFactory): """ Concrete Factories produce a family of products that belong to a single variant. The factory guarantees that resulting products are compatible. Note that signatures of the Concrete Factory's methods return an abstract product, while inside the method a concrete product is instantiated. """ def create_serializer(self): return Shelf('source_file') def test_serializers(factory): """ The client code works with factories and products only through abstract types: AbstractFactory and AbstractProduct. This lets you pass any factory or product subclass to the client code without breaking it. """ serialize = factory.create_serializer() serialize.make_data() serialize.unmake_data() if __name__ == "__main__": """ The client code can work with any concrete factory class. """ print("Client: Testing client code with the first factory type: MyPickle") test_serializers(ConcretePickleFactory())
8e5d40347622a1343bd63412cfff36569b59a7ed
rahulrsr/pythonStringManipulation
/reverse_each_word_in_sentence.py
270
3.875
4
def rev_words_in_sentence(statement): stm=statement.split() l=[] for s in stm: l.append(s[::-1]) final_l=' '.join(l) return final_l if __name__ == '__main__': m=input("Enter sentence for processing: ") print(rev_words_in_sentence(m))
1af1818dfe2bfb1bab321c87786ab356f7cff2d4
rahulrsr/pythonStringManipulation
/reverse_sentence.py
241
4.25
4
def reverse_sentence(statement): stm=statement.split() rev_stm=stm[::-1] rev_stm=' '.join(rev_stm) return rev_stm if __name__ == '__main__': m=input("Enter the sentence to be reversed: ") print(reverse_sentence(m))
44a267cf12ea6964c629eb312d8f2dbb0bc1d4fc
kjangeles/CyberSecurityProjects
/SimpleEncryptionProgram/simpleEncryptor.py
649
3.84375
4
#Team Members: Keren Angeles and Kimlong Seng def encrypt(text): result = [] for letter in text: l = ord(letter) - 42069 result.append(l) print("This is your encrypted message: ") for numbers in result: print(numbers, end='') print("", end='') decrypt(result) def decrypt(result): end_string = "" for numbers in result: l = int(numbers) l = l + 42069 l = chr(l) end_string = end_string + l print("\nYour decrypted text is: ") print(end_string) def main(): t = input("Input a text to be encrypted: ") encrypt(t) if __name__ == '__main__': main()
590419d3a0fa5cbf2b1d907359a22a0aa7fe92b5
kopelek/pycalc
/pycalc/stack.py
837
4.1875
4
#!/usr/bin/python3 class Stack(object): """ Implementation of the stack structure. """ def __init__(self): self._items = [] def clean(self): """ Removes all items. """ self._items = [] def push(self, item): """ Adds given item at the top of the stack. """ self._items.append(item) def pop(self): """ Returns with removing from the stack the first item from the top of the stack. """ return self._items.pop() def peek(self): """ Returns the first item from the top of the stack. """ return self._items[len(self._items) - 1] def is_empty(self): """ Returns True if stack is empty, False otherwise. """ return self._items == []
7458151206849493ec6d11c461e58f3e57fdc41c
sophyphreak/Other
/MIT Class 1/square root.py
998
3.9375
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 2 04:03:21 2017 @author: Andrew """ ans = 0 neg_flag = False x = float(input("Enter an integer: ")) if x < 0: neg_flag = True while ans**2 < x: ans = ans + 1 if ans**2 != x: ans -= 1 while ans**2 < x: ans = ans + .1 if ans**2 != x: ans -= .1 while ans**2 < x: ans = ans + .01 if ans**2 != x: ans -= .01 while ans**2 < x: ans = ans + .001 if ans**2 != x: ans -= .001 while ans**2 < x: ans = ans + .0001 if ans**2 != x: ans -= .0001 while ans**2 < x: ans = ans + .00001 if ans**2 != x: ans -= .00001 while ans**2 < x: ans = ans + .000001 if ans**2 != x: ans -= .000001 while ans**2 < x: ans = ans + .0000001 if ans**2 >= x: print("Square root of", x, "is", ans) else: print(x, "is not a perfect square") if neg_flag: print("Just checking... did you mean", -x, "?")
7bab6e6b4d6328d1d7e1f081acc39db79a172371
sophyphreak/Other
/MIT Class 1/hangman2.py
6,495
4.03125
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 6 22:41:15 2017 @author: Andrew """ # Hangman game # # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print(" ", len(wordlist), "words loaded.") return wordlist def chooseWord(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = loadWords() def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' secretWord1 = [] secretWord = list(secretWord) secretWord1 = secretWord1 + secretWord for i in range(len(secretWord1)): secretWord1[i] = [secretWord1[i], False] for i in range(len(secretWord)): for j in lettersGuessed: if secretWord[i] == j: secretWord1[i] = [secretWord[i], True] for i in range(len(secretWord)): if (secretWord1[i] == [secretWord[i], False]): return False return True def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' secretWord1 = [] display = "" secretWord = list(secretWord) secretWord1 = secretWord1 + secretWord for i in range(len(secretWord1)): secretWord1[i] = [secretWord1[i], False] for i in range(len(secretWord)): for j in lettersGuessed: if secretWord[i] == j: secretWord1[i] = [secretWord[i], True] for i in range(len(secretWord)): if (secretWord1[i] == [secretWord[i], True]): display = display + secretWord[i] + " " else: display = display + "_" + " " return display def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. ''' alphabet = "abcdefghijklmnopqrstuvwxyz" alphabet = list(alphabet) display = "" for i in alphabet: if not i in lettersGuessed: display = display + i return display def hangman(secretWord): ''' secretWord: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secretWord contains. * Ask the user to supply one guess (i.e. letter) per round. * The user should receive feedback immediately after each guess about whether their guess appears in the computers word. * After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed. Follows the other limitations detailed in the problem write-up. ''' lettersGuessed = [] # availableLetters = getAvailableLetters(lettersGuessed) dashes = "-----------" guessesLeft = 8 lettersFrequency = ['e', 't', 'a', 'o', 'i', 'n', 's', 'h', 'r', 'd', 'l', 'c', 'u', 'm', 'w', 'f', 'g', 'y', 'p', 'b', 'v', 'k', 'j', 'x', 'q', 'z'] freq = 0 print('Welcome to the game Hangman!') print("I'm thinking of a word that is", len(secretWord), "letters long.") print(dashes) iterations = 0 guessesLeft = 1 lettersGuessed = lettersFrequency while (isWordGuessed(secretWord, lettersGuessed)) == False: iterations += 1 print('This is guess number', iterations) print('Available letters:', getAvailableLetters(lettersGuessed)) print(freq) guess = lettersGuessed[freq] freq += 1 if(guess in lettersGuessed): print("Oops! You've already guessed that letter:", getGuessedWord(secretWord, lettersGuessed)) else: lettersGuessed += [guess] if not guess in secretWord: print('Oops! That letter is not in my word: ', getGuessedWord(secretWord, lettersGuessed)) guessesLeft -= 1 else: print('Good guess: ', getGuessedWord(secretWord, lettersGuessed)) print(dashes) if guessesLeft == 0: print('Sorry, you ran out of guesses. The word was ' + secretWord + '.') return iterations else: print('Congratulations, you won!') return iterations # When you've completed your hangman function, uncomment these two lines # and run this file to test! (hint: you might want to pick your own # secretWord while you're testing) secretWord = chooseWord(wordlist).lower() #print(hangman(secretWord)) def findWinRatio(iterations): ''' iterations: int, number of you want to run to find the win ratio for a hangman win method returns: ratio of wins to losses of the hangman method used ''' numberOfIterations = 0 list1 = [] itr = 0 while itr < iterations: list1 += [hangman(chooseWord(wordlist).lower())] numberOfIterations += 1 itr += 1 x = 0 for i in list1: x += list1[i] average = x / len(list1) print("Number of Iterations:", numberOfIterations) return average print(findWinRatio(10))
757507b13da0f5967ffa77a0f44a98384e879042
sophyphreak/Other
/checkio/friends.py
2,168
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 1 09:22:30 2017 @author: Andrew """ class Friends: def __init__(self, connections): ''' input: a tuple of sets with two items in each set returns: nothing ''' self.connections = connections def getConnections(self): ''' input: nothing returns: tuple of sets ''' return self.connections def add(self, connection): ''' input: set of two strings returns: boolean True if this set already exists in object, False otherwise ''' if connection in self.connections: return False else: self.connections += (connection,) return True def __repr__(self): answer = str(self.connections) return answer def remove(self, connection): ''' input: set of two strings returns: boolean True if this connection exists, False otherwise ''' if connection in self.connections: temp = self.connections[:] self.connections = () for i in temp: if not connection == i: self.connections += (i,) return True else: return False def names(self): ''' input: nothing returns: set of names ''' answer = set() for entry in self.connections: if len(entry) == 2: for item in entry: if not item in answer: answer.add(item) return answer def connected(self, a): ''' input: string returns: set with all connections to input ''' answer = set() for entry in self.connections: if a in entry: for item in entry: if item != a: answer.add(item) return answer
1c6f4e5ad0fec2cc8e05afd01ff5bcdefe0ef477
sophyphreak/Other
/MIT Class 1/alphabet challenge.py
2,141
3.546875
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 1 21:15:27 2017 @author: Andrew """ s = "zyxwvutsrqponmlkjihgfedcba" if (len(s) != 1): alpha = "abcdefghijklmnopqrstuvwxyz" count = 0 alp1 = 0 alp2 = 0 begin = 0 end = 0 ans = "-" for letter in range(len(s)-1): if (len(s) - count < 2): break for alp1 in range(26): if (s[letter] == alpha [alp1]): break for alp2 in range(26): if (s[letter + 1] == alpha [alp2]): break if (alp1 <= alp2): ans = ans + "1" else: ans = ans + "0" #print (ans) longest = 0 longestdigit = 0 for digit in range(1, len(ans)-1): # for everything here we need to find out if the current # digit is a 1 and then find out if the next digit is a 1 templong = 0 # We will do this using templong. templong will be the # length of our current row of 1's, and that will be compared # to our longest row of 1's later to determine the longest # row of places in alphabetical order for num in range(digit, len(ans)): if (ans[num] == "1"): templong += 1 if (ans[num] == "0"): break if (templong > longest): longest = templong longestdigit = digit # print ("longest: " + str(longest)) # print ("longestdigit: " + str(longestdigit)) # print (type(longest)) # print (type(longestdigit)) if (longest == 0 and longestdigit == 0): longestdigit = 1 answerstring = "" for i in range(longestdigit - 1, longestdigit + longest): answerstring += s[i] if answerstring == "": answerstring = s[0] # print (s[longestdigit-1]) # print ("Longest substring in alphabetical order is: " + answerstring) print ("Longest substring in alphabetical order is: " + s[longestdigit - 1: longestdigit + longest]) else: print ("Longest substring in alphabetical order is: " + s[0])
7318acc044159b268cf0e54c6dd333da7b403e5e
sophyphreak/Other
/MIT Class 2/Lecture 1 scratchpaper 2.py
3,861
4.21875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 22 01:31:21 2017 @author: Andrew """ class item(object): def __init__(self, name, value, weight): #create an item with a name, value, and weight self.name = name self.value = value self.weight = weight def getName(self): #returns name of item return self.name def getValue(self): #returns value of item return self.value def getWeight(self): #returns weight of item return self.weight def getRatio(self): #returns ratio of value to weight return self.getValue()/self.getWeight() def __repr__(self): return self.name def __str__(self): return self.name + ': <' + str(self.value) + \ ', ' + str(self.weight) + '>' class knapsack(object): def __init__(self, name, maxWeight): #creates a knapsack with a name and a max weight self.name = name self.maxWeight = maxWeight self.weight = 0 self.value = 0 self.itemsInside = [] def getName(self): #returns name of knapsack return self.name def getMaxWeight(self): #returns max weight of knapsack return self.maxWeight def getWeight(self): #returns current weight of items in knapsack return self.weight def getValue(self): #returns current value of items within knapsack return self.value def printItemsInside(self): #prints list of names of items inside knapsack print("Items:") for i in self.itemsInside: print(self.getName()) def getItemsInside(self): #returns list of items inside return self.itemsInside def getRatio(self): #returns ratio of value/weight return self.value/self.weight def addItem(self, item): #adds an item to the knapsack if self.getWeight() + item.getWeight() <= self.getMaxWeight(): self.itemsInside += [item] self.weight += item.getWeight() self.value += item.getValue() def removeItem(self, item): #removes an item from the knapsack tempStr = [] for i in self.getItemsInside(): tempStr += [i] if item in tempStr: tempStr.remove(item) self.itemsInside = tempStr def checkCanFit(self, item): if self.getWeight() + item.getWeight() > self.getMaxWeight(): return False else: return True def optimize(itemList, knapsack): itemList1 = [] for i in itemList: itemList1 += [i] ratioList = [] for item in itemList1: ratioList += [item.getRatio()] while len(itemList1) > 0: maxRatioSpot = 0 maxRatio = 0 for i in range(len(ratioList)): if ratioList[i] > maxRatio: maxRatio = ratioList[i] maxRatioSpot = i # print("itemList1:", itemList1) # print("maxRatioSpot:", maxRatioSpot, "of", len(itemList1)) # print("ratioList:", ratioList) # print("item:", itemList1[maxRatioSpot]) # print() if knapsack.checkCanFit(itemList1[maxRatioSpot]) and \ itemList1[maxRatioSpot].getValue() > 0: knapsack.addItem(itemList1[maxRatioSpot]) ratioList.remove(maxRatio) itemList1.remove(itemList1[maxRatioSpot]) itemList = [ item("wine", 89, 123), item("beer", 90, 154), item("pizza", 30, 258), item("burger", 50, 354), item("fries", 90, 365), item("coke", 79, 150), item("apple", 90, 95), item("donut", 10, 195) ] bag = knapsack("stomach", 800) optimize(itemList, bag) print(bag.getItemsInside())
e2b92d3846bd3f2ae279893f87da8cc93c1aa59e
sophyphreak/Other
/fucking around/tkinterrrr.py
407
3.609375
4
# -*- coding: utf-8 -*- """ Created on Mon May 15 08:45:03 2017 @author: Andrew """ from tkinter import * top = Tk() L1 = Label(top, text = "Tax Calculator") L1.pack(side = TOP) L2 = Label(top, text = "Tax rate:") L2.pack(side = LEFT) E1 = Entry(top, bd = 4) E1.pack(side = RIGHT) L4 = Label(top, text = "") L4.pack(side = TOP) L3 = Label(top, text = "Total price:") L3.pack(side = LEFT) top.mainloop()
8887355e340c2dc3f96e53c691ccd9ec138e34d8
sophyphreak/Other
/MIT Class 2/Lecture 2 problem 1.py
1,228
3.875
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 30 11:13:15 2017 @author: Andrew """ def yieldAllCombos(items): """ Generates all combinations of N items into two bags, whereby each item is in one or zero bags. Yields a tuple, (bag1, bag2), where each bag is represented as a list of which item(s) are in each bag. """ N = len(items) # enumerate the 3**N possible combinations for i in range(3**N): bag1 = [] bag2 = [] def toStr(n,base): convertString = "0123456789ABCDEF" if n < base: return convertString[n] else: return toStr(n//base,base) + convertString[n%base] iBase3 = toStr(i,3) while len(iBase3) < N: iBase3 = "0" + iBase3 # print(iBase3) for j in range(N): # test bit jth of integer i # print(j) if (int(iBase3[j])) == 1: bag1.append(items[j]) if (int(iBase3[j])) == 2: bag2.append(items[j]) yield (bag1, bag2) #n = 2 #L= [] # #for i in range(n): # L += [i+1] # #test = yieldAllCombos(L) # #for i in range(3**n): # print(next(test))
2aad357016ad9d363ea5c2f52da24fcd4b1a84f6
sophyphreak/Other
/MIT Class 1/problem set 2 exercise 3.py
2,372
3.734375
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 3 04:43:48 2017 @author: Andrew """ # -*- coding: utf-8 -*- """ Created on Fri Feb 3 03:31:42 2017 @author: Andrew """ # round(number[, ndigits]) # (3329, 310) # (4773, 440) # (3926, 360) balance = 4773 annualInterestRate = .2 monthlyInterestRate = annualInterestRate / 12 monthlyUnpaidBalance = balance updatedBalanceEachMonth = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) time = 12 #months def creditCard(balance, monthlyInterestRate, monthlyUnpaidBalance, payment, time): if (time == 0): return balance else: # print("original balance: " + str(balance)) monthlyUnpaidBalance = balance - (payment) balance = monthlyUnpaidBalance + monthlyInterestRate * monthlyUnpaidBalance time -= 1 # print("payment: " + str(payment)) # print("monthlyUnpaidBalance: " + str(monthlyUnpaidBalance)) # print("monthlyInterestRate: " + str(monthlyInterestRate)) # print("time: " + str(time)) # print("new balance: " + str(balance)) # print("") # print ("Month " + str(abs(12-time)) + " Remaining balance: " + str(round(balance, 2))) return creditCard(balance, monthlyInterestRate, monthlyUnpaidBalance, payment, time) #balance = creditCard(balance, annualInterestRate, monthlyUnpaidBalance, payment, 12) #print(balance) low = balance / 12 high = (balance * (1 + monthlyInterestRate)**12) / 12 payment = (low + high) / 2 def paymentCalc(balance, monthlyInterestRate, low, high, payment): if abs(creditCard(balance, monthlyInterestRate, monthlyUnpaidBalance, payment, 12)) < .0001: return round (payment, 2) else: # print ("year-end balance: " + str(creditCard(balance, monthlyInterestRate, payment, 12))) if creditCard(balance, monthlyInterestRate, monthlyUnpaidBalance, payment, 12) > 0: low = payment payment = (low + high) / 2 else: high = payment payment = (low + high) / 2 # print("payment guess = " + str(payment)) return paymentCalc(balance, monthlyInterestRate, low, high, payment) payment = paymentCalc(balance, monthlyInterestRate, low, high, payment) print("Lowest Payment: " + str(payment))
b94b4ab4bd64d84541e3decd164503daa21bd037
sophyphreak/Other
/checkio/power supply.py
5,311
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 1 11:31:22 2017 @author: Andrew """ ''' Input: Two arguments. The first one is the network, represented as a list of connections. Each connection is a list of two nodes that are connected. A city or power plant can be a node. Each city or power plant is a unique string. The second argument is a dict where keys are power plants and values are the power plant's range. Output: A set of strings. Each string is the name of a blacked out city. Example: power_supply([['p1', 'c1'], ['c1', 'c2']], {'p1': 1}) == set(['с2']) power_supply([['c0', 'c1'], ['c1', 'p1'], ['c1', 'c3'], ['p1', 'c4']], {'p1': 1}) == set(['c0', 'c3']) power_supply([['p1', 'c1'], ['c1', 'c2'], ['c2', 'c3']], {'p1': 3}) == set([]) ''' class Powa: def __init__(self, connections, power): self.connections = connections self.power = power def connected(self, a): ''' input: string returns: set with all connections to string ''' conReturn = [] for entry in self.connections: # print('entry =',entry) if a in entry: # print('entry with a=',entry) for item in entry: # print('item =',item) if item != a: # print('item not a=',item) conReturn += [item] return conReturn def onePlantPowered(self, plant, powerNum, answer): ''' input: string, a power plant int, the amount of power for that plant list, current partial answer output: partial answer string for powered cities ''' while True: #set place for the loop to start when it goes to the first city index = 0 current = plant #current plant or city #loop until we run out of power while powerNum > 0: #find all connections of that power plant connections = self.connected(current) currentcon = 0 #start at index 0 of connections #loop until we run out of direct connections to current while not currentcon == len(connections): #gives power to each city connected until we run out of #power and adds each powered city to answer list #first, opens up the connection we are working with, #sets to city variable city = connections[currentcon] #first, checks if city is a city if city[0] == 'c': #if so, then checks if it's already in answer if not city in answer: #if not, then adds it to answer answer += [city] #and subtracts one from powerNum powerNum -= 1 #if we are out of power, return list of powered #cities if powerNum < 1: return answer currentcon += 1 #after the loop, current changes to next city connection if len(answer) < index: current = answer[index] else: return answer def powered(self): ''' input: nothing output: list of powered cities ''' #create powered cities list answer = [] #first, go through each power plant #plant is the current power plant we are working with #powerNum is the number of units of power that power plant has for plant in self.power: # print(answer) powerNum = self.power[plant] answer = self.onePlantPowered(plant, powerNum, answer) # print(answer) return answer def unpowered(self): ''' input: nothing returns: set with a list inside of all unpowered cities ''' answer = [] poweredList = self.powered() for entry in self.connections: for item in entry: if not item in poweredList and not item[0] == 'p': answer += [item] return answer def power_supply(lst, dic): ''' input: list of connected cities and power plants dictionary of power per power plant returns: set of list of unpowered cities ''' stuff = Powa(lst, dic) answer = set(stuff.unpowered()) return answer print(power_supply([['p1', 'c1'], ['c1', 'c2']], {'p1': 1})) print(power_supply([['c0', 'c1'], ['c1', 'p1'], ['c1', 'c3'], ['p1', 'c4']], {'p1': 1})) print(power_supply([['p1', 'c1'], ['c1', 'c2'], ['c2', 'c3']], {'p1': 3})) print(power_supply([['p1', 'c1'], ['c1', 'c2']], {'p1': 1}) == set(['с2'])) print(power_supply([['c0', 'c1'], ['c1', 'p1'], ['c1', 'c3'], ['p1', 'c4']], {'p1': 1}) == set(['c0', 'c3'])) print(power_supply([['p1', 'c1'], ['c1', 'c2'], ['c2', 'c3']], {'p1': 3}) == set([]))
ba33a9cab7cde2c44a50016c9743bd72327240e1
hzhang22/hack
/grep-exercises/phone-numbers/gen_numbers.py
4,388
3.6875
4
import random import sys verbose = True numberQuality = 1 def getRandomNumberWithDelim(curNumbers, delim): thisNumber = '' while True: for x in range (1, 11): thisNumber += str(random.randrange(0,10)) if x%3 == 0 and x <=6 and not (numberQuality == 3 and random.uniform(0,1) > .5): thisNumber += delim if thisNumber not in curNumbers: break return thisNumber def getFancyFormat(curNumbers): if (numberQuality >= 2 and random.uniform(0,1) > .85): thisNumber = '' else: thisNumber = '(' while True: for x in range (1, 11): thisNumber += str(random.randrange(0,10)) if x==6 and not (numberQuality == 3 and random.uniform(0,1) > .5) : thisNumber += "-" if x == 3 and not (numberQuality >=2 and random.uniform(0,1) > .5): thisNumber += ")" if thisNumber not in curNumbers: break return thisNumber def defineRandomPhoneNumbers(numRandom, type): numbersList = [] for x in range (numRandom): if type == 1: numbersList.append(getRandomNumberWithDelim(numbersList, "-")) elif type == 2: if random.uniform(0,1) > .5: numbersList.append(getRandomNumberWithDelim(numbersList, "-")) else: numbersList.append(getRandomNumberWithDelim(numbersList, "")) elif type >= 3: if random.uniform(0,1) > .6: numbersList.append(getRandomNumberWithDelim(numbersList, "-")) elif random.uniform(0,1) > .3: numbersList.append(getRandomNumberWithDelim(numbersList, "")) else : numbersList.append(getFancyFormat(numbersList)) return numbersList def makeAFile(randomPhoneNumbers, numNumbers, lineLen, lineNum, fileNum, dir): thisFile = '' numsRemaining = numNumbers charactersTotal = lineLen*lineNum charactersMade = 0; curProbability = float(charactersMade)/float(charactersTotal) f = open(dir+"/cs1u_file_"+str(fileNum), "w") for x in range(lineNum): thisLine = '' for y in range(lineLen): if random.uniform(0,1) > .90: thisLine += ' ' elif random.uniform(0,1) > .95: thisLine += '.' else: thisCh = chr(random.randrange(97, 123)) thisLine += thisCh charactersMade += 1 curProbability = float(charactersMade)/float(charactersTotal) if random.uniform(0,1) < curProbability and numsRemaining > 0: thisLine += " "+randomPhoneNumbers.pop()+" " numsRemaining -= 1 thisLine += '\n' thisFile += thisLine for x in range(numsRemaining): thisLine += " "+randomPhoneNumbers.pop()+" " f.write(thisFile) f.close() return thisFile def makeRandomFiles(randomPhoneNumbers, numRandomNumbers, numTextFiles, lineLen, lineNum, dir): for file in range(numTextFiles): print "----File "+str(file)+"----" if verbose == True : print makeAFile(randomPhoneNumbers, numRandomNumbers/numTextFiles, lineLen, lineNum, file, dir) else : makeAFile(randomPhoneNumbers, numRandomNumbers/numTextFiles, lineLen, lineNum, file, dir) if len(sys.argv) < 7: print "Please specify two integers for the # of phone numbers, #files, #chars per line, #lines per file, dir to save, and:" print "1 - numbers only of form xxx-xxx-xxxx" print "2 - numbers of form 1 and xxxxxxxxxx" print "3 - numbers of form 2 and (xxx)xxx-xxxx" print "4 - numbers of form 3 and some missing parens" print "5 - numbers of form 4 and some missing dashes" sys.exit(-1) numRandomNumbers = int(sys.argv[1]) numTextFiles = int(sys.argv[2]) lineLength = int(sys.argv[3]) lineNumbers = int(sys.argv[4]) dir = sys.argv[5] type = int(sys.argv[6]) verboseParam = sys.argv[7] if type == 4: numberQuality = 2; elif type == 5: numberQuality = 3; if len(sys.argv) == 8: if verboseParam == 'v': verbose = True print "verbose mode" elif verboseParam == '-v': verbose = False print "quiet mode" if numRandomNumbers > numTextFiles: numRandomNumbers = (numRandomNumbers/numTextFiles)*numTextFiles else: numRandomNumbers = (numTextFiles/numRandomNumbers)*numRandomNumbers print "Generating "+str(numRandomNumbers)+" phone numbers of type "+str(type) randomNumbers = defineRandomPhoneNumbers(numRandomNumbers, type) print randomNumbers f = open(dir+"/golden", "w") f.write(repr(randomNumbers)) f.close() makeRandomFiles(randomNumbers, numRandomNumbers, numTextFiles, lineLength, lineNumbers, dir)
2b549601aa4c1cea3bcdda541284f8a17a3ce794
Ankur-Bhalla/email_using_smtp
/email_sender.py
1,242
3.578125
4
# Sending Emails with Python using smtplib and email modules. import smtplib from email.message import EmailMessage email = EmailMessage() email['from'] = 'Ankur Bhalla' email['to'] = '<enter receiver email>' email['subject'] = 'You won 1,000,000 dollars!' email.set_content('I am a Python Master!') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: # SMTP.ehlo(name=''). Identify yourself to an ESMTP server using EHLO. smtp.ehlo() # SMTP.starttls(keyfile=None, certfile=None, context=None) # Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow # will be encrypted. You should then call ehlo() again. smtp.starttls() # SMTP.login(user, password, *, initial_response_ok=True) # Log in on an SMTP server that requires authentication. The arguments are the username and the # password to authenticate with. smtp.login('<enter sender email>', '<enter sender password>') # SMTP.send_message(msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=()). # This is a convenience method for calling sendmail() with the message represented by an # email.message.Message object. smtp.send_message(email) print('all good boss!')
289d459d9e0dda101f443edaa9bf65d2985b4949
YaraBader/python-applecation
/Ryans+Notes+Coding+Exercise+16+Calculate+a+Factorial.py
604
4.1875
4
''' Create a Factorial To solve this problem: 1. Create a function that will find the factorial for a value using a recursive function. Factorials are calculated as such 3! = 3 * 2 * 1 2. Expected Output Factorial of 4 = 24 Factorial at its recursive form is: X! = X * (X-1)! ''' # define the factorial function def factorial(n): # Sets to 1 if asked for 1 # This is the exit condition if n==1: return 1 else: # factorial in recursive form for >= 2 result = n * factorial(n-1) return result # prints factorial of 4 print ("Factorial of 4 =", factorial(4))
84e848c7b3f7cd20142ce6326a8a5131b1ecacad
YaraBader/python-applecation
/Ryans+Notes+Coding+Exercise+8+Print+a+Christmas+Tree.py
1,956
4.34375
4
''' To solve this problem: Don't use the input function in this code 1. Assign a value of 5 to the variable tree_height 2. Print a tree like you saw in the video with 4 rows and a stump on the bottom TIP 1 You should use a while loop and 3 for loops. TIP 2 I know that this is the number of spaces and hashes for the tree 4 - 1 3 - 3 2 - 5 1 - 7 0 - 9 Spaces before stump = Spaces before top TIP 3 You will need to do the following in your program : 1. Decrement spaces by one each time through the loop 2. Increment the hashes by 2 each time through the loop 3. Save spaces to the stump by calculating tree height - 1 4. Decrement from tree height until it equals 0 5. Print spaces and then hashes for each row 6. Print stump spaces and then 1 hash Here is the sample program How tall is the tree : 5      #    ###    ##### ####### #########      # ''' # Sets 5 for tree_height (as an integer) height = int(5) # spaces starts as height - 1 spaces = stumpspaces = height -1 # hashes start as 1 hashes = 1 # This loop goes until the height limit is reached # height will be decreased by 1 each iteration of the loop while height >= 1: # Prints a space for the number of spaces before the hashes # This starts at height-1, just like the stump, and decreases 1 per iteration # end="" does not print a new line for i in range(spaces): print(" ", end="") # Prints the hashes # which starts at 1 and increases by 2 per iteration for j in range(hashes): print('#', end="") # prints a new line after each iteration of the spaces and hashes print() # spaces decreases 1 per iteration spaces -= 1 # hashes increase 2 per iteration hashes += 2 # This is what makes it go down to the next level height -= 1 # Prints the spaces before the hash stump # which is height-1 for i in range(stumpspaces): print(' ', end="") # Prints the hash stump print("#")
241fa0c22d7775e05d937f0008f899fd545e05ad
tweninger/PSHRG
/graph.py
17,528
3.609375
4
import collections import heapq import itertools import random import bigfloat import treewidth PSEUDOROOT = 'multi-sentence' class Graph(object): """ This data structure does triple duty. It is used for: - semantic graphs - tree decompositions - derivation forests """ def __init__(self, arg): if isinstance(arg, Node): self.root = arg elif type(arg) in [str, unicode]: self.root = amr_to_graph(arg).root else: raise ValueError("can't initialize Graph from type {0}".format(type(arg))) self.update() def update(self): """Call this method after the graph structure has been modified""" self._compute_inedges() def _compute_inedges(self): # Add upward pointers to Nodes and Edges. # The reason we don't do this at the time that they are constructed # is to allow the structure to be modified afterwards. # However, after the Graph is constructed, please don't modify the structure for node in self.dfs(): node.inedges = [] for node in self.dfs(): for edge in node.outedges: edge.head = node for child in edge.tails: child.inedges.append(edge) def copy(self, memo=None): if memo is None: memo = {} if id(self) not in memo: memo[id(self)] = Graph(self.root.copy(memo)) return memo[id(self)] def __str__(self): return self.to_amr() def to_amr(self, node_to_str=None, edge_to_str=None): count = collections.Counter() def visit(node): count[node] += 1 if count[node] > 1: return node.var # Format node label if node_to_str: label = node_to_str(node) # elif " " in node.label: # label = '"%s"' % node.label else: label = str(node.label) if node.var: label = "{0} / {1}".format(node.var, label) if node.outedges: edgestrings = [] for ei, edge in enumerate(node.outedges): if edge_to_str: edgestrings.append(":{0}".format(edge_to_str(edge))) elif edge.label: edgestrings.append(":{0}".format(edge.label)) elif ei > 0: # it's ok if the first edge has no explicit label edgestrings.append(":") edgestrings.extend([visit(child) for child in edge.tails]) s = "({0} {1})".format(label, " ".join(edgestrings)) else: if node.var: # parens are obligatory in this case s = "({0})".format(label) else: s = label return s return visit(self.root) def to_dot(self): # assign name to each node name = {} for node in self.dfs(): if node.var: s = "%s / %s" % (node.var, node.label) assert s not in name name[node] = s elif node.label not in name: name[node] = node.label else: name[node] = "%s_%s" % (node.label, len(name)) result = [] result.append("digraph G {\n") for node in self.dfs(): if node.label == PSEUDOROOT: continue for edge in node.outedges: if len(edge.tails) > 1: raise ValueError("hypergraphs not allowed") (tail,) = edge.tails result.append(' "%s" -> "%s" [label="%s"];\n' % ( name[node].replace('"', '\\"'), name[tail].replace('"', '\\"'), edge.label.replace('"', '\\"'))) result.append("}\n") return "".join(result) def undirected_graph(self): """Return an adjacency list of the graph, viewed as an undirected graph""" graph = collections.defaultdict(set) for node in self.dfs(): if node.label == PSEUDOROOT: continue graph.setdefault(node, set()) for edge in node.outedges: treewidth.make_clique(graph, [node] + edge.tails) return graph def directed_graph(self): """Return an adjacency list of the graph, viewed as an directed graph""" graph = collections.defaultdict(set) for node in self.dfs(): if node.label == PSEUDOROOT: continue graph.setdefault(node, set()) for edge in node.outedges: for tail in edge.tails: graph[node].add(tail) return graph def tree_decomposition(self): graph = self.undirected_graph() tree = treewidth.quickbb(graph) return tree def dfs(self): memo = set() result = [] def visit(node): if node in memo: return memo.add(node) result.append(node) for edge in node.outedges: for child in edge.tails: visit(child) visit(self.root) return result def dfs_edges(self): for node in self.dfs(): for edge in node.outedges: yield edge def scc(self): """Tarjan's algorithm""" order = {} lowlink = {} stack = [] components = [] def visit(v): i = len(order) order[v] = i lowlink[v] = i stack.append(v) for edge in v.outedges: for tail in edge.tails: if tail not in order: visit(tail) lowlink[v] = min(lowlink[v], lowlink[tail]) elif tail in stack: lowlink[v] = min(lowlink[v], order[tail]) if lowlink[v] == order[v]: vi = stack.index(v) component = set(stack[vi:]) del stack[vi:] components.append(component) for v in self.dfs(): if v not in order: visit(v) return components def frontier(self): return [node for node in self.dfs() if len(node.outedges) == 0] def viterbi_edges(self): """return a dict of Node -> (probability, Edge)""" memo = {} def visit(node): if node in memo: p, _ = memo[node] return p # We put a zero probability into the memo already # in case one of our descendants points back to self. # This will cause the descendant not to choose self. memo[node] = pmax, emax = (0., None) for edge in node.outedges: p = bigfloat.bigfloat(edge.weight) for child in edge.tails: p *= visit(child) if emax is None or p > pmax: pmax, emax = p, edge memo[node] = pmax, emax return pmax visit(self.root) return memo def construct(self, edges): def visit(node): edge = edges[node] newedge = Edge(edge.label, tails=[visit(tail) for tail in edge.tails], weight=edge.weight) newnode = Node(node.label, outedges=[newedge]) newnode.original = node return newnode return Graph(visit(self.root)) def viterbi(self): edges = {node: edge for (node, (_, edge)) in self.viterbi_edges().items()} return self.construct(edges) def inside(self): memo = {} def visit(node): if node in memo: p = memo[node] return p memo[node] = psum = 0. for edge in node.outedges: p = bigfloat.bigfloat(edge.weight) for child in edge.tails: p *= visit(child) psum += p memo[node] = psum return psum visit(self.root) return memo def sample(self, inside): edges = {} for node in self.dfs(): ps = [] # Recompute the edge inside weights because we threw them away before for edge in node.outedges: p = bigfloat.bigfloat(edge.weight) for child in edge.tails: p *= inside[child] ps.append((p / inside[node], edge)) r = random.random() psum = 0. for p, edge in ps: psum += p if psum > r: edges[node] = edge break else: assert False return self.construct(edges) def all_pairs_shortest_paths(self): """Returns a dictionary paths, where paths[u,v] is a pair of the shortest path from u to v and the last edge along that path.""" paths = {} g = self.undirected_graph() for u in g: paths[u, u] = (0, None) for edge in u.outedges: for v in edge.tails: paths[u, v] = (1, edge) for w in g: for u in g: for v in g: if paths[u, v][0] > paths[u, w][0] + paths[w, v][0]: paths[u, v] = (paths[u, w][0] + paths[w, v][0], paths[w, v][1]) return paths def amr_to_graph(s, start=0, return_end=False): def scan_space(i): while s[i].isspace(): i += 1 return i def scan_label(i): j = i if s[j] == '"': j += 1 while s[j] != '"': j += 1 j += 1 else: # while not s[j].isspace() and s[j] != ')': while not s[j].isspace() and s[j] != ')' and s[j] not in "./:": j += 1 return s[i:j], j def scan_edge(i): i = scan_space(i) if s[i] == ')': return None, i else: if s[i] == ':': label, i = scan_label(i + 1) else: label = 'E' tails = [] while True: tail, i = _scan_node(i) if tail is None: break else: tails.append(tail) return Edge(label=label, tails=tails), i def _scan_node(i): i = scan_space(i) if s[i] in [')', ':']: return None, i elif s[i] == '(': i = scan_space(i + 1) label, i = scan_label(i) # look ahead for a / memoize = False i = scan_space(i) # if s[i] == '/': if s[i] in '/.': var = label i = scan_space(i + 1) label, i = scan_label(i) memoize = True edges = [] while True: edge, i = scan_edge(i) if edge is None: assert s[i] == ')' i += 1 break else: edges.append(edge) node = Node(label=label, outedges=edges) if memoize: node.var = var memo[var] = node return node, i else: label, i = scan_label(i) # need for Bolinas format: memoize = False i = scan_space(i) # if s[i] == '/': if s[i] == '.': var = label i = scan_space(i + 1) label, i = scan_label(i) memoize = True node = Node(label=label) # need for Bolinas format: if memoize: node.var = var memo[var] = node return node, i def resolve(node): if node.outedges: for edge in node.outedges: edge.tails = [resolve(tail) for tail in edge.tails] return node else: if len(node.outedges) == 0 and node.var is None and node.label in memo: return memo[node.label] else: return node def scan_node(s, start=0, return_end=False): root, end = _scan_node(start) if root: resolve(root) if return_end: return root, end else: return root memo = {} i = start while i < len(s) and s[i].isspace(): i += 1 if i == len(s): g = None else: root, i = scan_node(s, i, True) g = Graph(root) if return_end: return g, i else: return g class Node(object): def __init__(self, label='E', outedges=None): self.label = label self.var = None self.inedges = [] self.outedges = outedges or [] self.marker = False def copy(self, memo=None): if memo is None: memo = {} if id(self) not in memo: memo[id(self)] = Node(self.label, [edge.copy(memo) for edge in self.outedges]) return memo[id(self)] def __str__(self): if self.var: return "{0} / {1}".format(self.var, self.label) else: return str(self.label) def edges(self): for edge in self.inedges: yield edge for edge in self.outedges: yield edge class Edge(object): def __init__(self, label='E', tails=None, weight=1.): self.label = label self.head = None self.tails = tails or [] self.weight = weight def copy(self, memo=None): if memo is None: memo = {} if id(self) not in memo: memo[id(self)] = Edge(self.label, [tail.copy(memo) for tail in self.tails], self.weight) return memo[id(self)] def __str__(self): return str(self.label) def nodes(self): yield self.head for tail in self.tails: yield tail class NBestInfo(object): """Information about a Node that is needed for n-best computation""" def __init__(self, node, viterbi): self.nbest = [] # of (viterbi, edge, tailranks) self.cands = [] # priority queue of (viterbi, edge, tailranks) self.index = set() # of (edge, tailranks) for edge in node.outedges: zeros = (0,) * len(edge.tails) p = bigfloat.bigfloat(edge.weight) for tail in edge.tails: tail_viterbi, _ = viterbi[tail] p *= tail_viterbi self.cands.append((-p, edge, zeros)) self.index.add((edge, zeros)) heapq.heapify(self.cands) (p, edge, ranks) = heapq.heappop(self.cands) self.nbest.append((p, edge, ranks)) class NBest(object): def __init__(self, graph): self.graph = graph self.nbinfos = {} viterbi_edges = graph.viterbi_edges() for node in graph.dfs(): self.nbinfos[node] = NBestInfo(node, viterbi_edges) def compute_nbest(self, node, n): nb = self.nbinfos[node] while len(nb.nbest) < n: # Extend the candidate pool p, edge, ranks = nb.nbest[-1] for tail_i in xrange(len(edge.tails)): tail, rank = edge.tails[tail_i], ranks[tail_i] if self.compute_nbest(tail, rank + 2) >= rank + 2: tail_nb = self.nbinfos[tail] nextranks = list(ranks) nextranks[tail_i] += 1 nextranks = tuple(nextranks) if (edge, nextranks) not in nb.index: nextp = p / tail_nb.nbest[rank][0] * tail_nb.nbest[rank + 1][0] heapq.heappush(nb.cands, (nextp, edge, nextranks)) nb.index.add((edge, nextranks)) if len(nb.cands) > 0: # Get the next best and add it to the list (p, edge, ranks) = heapq.heappop(nb.cands) nb.nbest.append((p, edge, ranks)) else: break return len(nb.nbest) def __getitem__(self, i): self.compute_nbest(self.graph.root, i + 1) return Graph(self._getitem_helper(self.graph.root, i)) def _getitem_helper(self, node, i): nb = self.nbinfos[node] p, edge, ranks = nb.nbest[i] newtails = [] for tail, rank in itertools.izip(edge.tails, ranks): newtails.append(self._getitem_helper(tail, rank)) newedge = Edge(edge.label, tails=newtails, weight=edge.weight) newnode = Node(node.label, outedges=[newedge]) newnode.original = node return newnode
1f014e718e7b15d05fbb0c55f2b1819f825bc0d8
gl59789/python_study
/example001.py
22,756
3.921875
4
def print_monthly_expense(month, hours): monthly_expense = hours * 0.65 print("In " + month + " we spent: " + str(monthly_expense)) print_monthly_expense("June", 243) print_monthly_expense("July", 325) print_monthly_expense("August", 298) def rectangle_area(base, height): area = base * height # the area is base*height print("The area is " + str(area)) rectangle_area(5, 6) def convert_distance(miles): km = miles * 1.6 # approximately 1.6 km in 1 mile return km distance_in_km = convert_distance( 55 ) round_trip_in_km = distance_in_km * 2 print("The distance in kilometer is " + str(distance_in_km)) print("The round-trip in kilometer is " + str(round_trip_in_km)) def order_numbers(number1, number2): if number2 > number1: return number1, number2 else: return number2, number1 smaller, bigger = order_numbers(100, 99) print(smaller, bigger) def number_group(number): if (number > 0 ): return "Positive" elif (number < 0): return "Negative" else: return "Zero" print(number_group(10)) #Should be Positive print(number_group(0)) #Should be Zero print(number_group(-5)) #Should be Negative def greeting(name): if name == "Taylor": return "Welcome back Taylor!" else: return "Hello there, " + name print(greeting("Taylor")) print(greeting("John")) print("A dog" + "A mouse") print(9999+8888 + 100*100) def calculate_storage(filesize): block_size = 4096 # Use floor division to calculate how many blocks are fully occupied full_blocks = int(filesize / block_size) # Use the modulo operator to check whether there's any remainder partial_block = filesize % block_size # Depending on whether there's a remainder or not, return the right number. if partial_block > 0: return full_blocks + 1 return full_blocks print(calculate_storage(1)) # Should be 4096 print(calculate_storage(4096)) # Should be 4096 print(calculate_storage(4097)) # Should be 8192 def color_translator(color): if color == "red": hex_color = "#ff0000" elif color == "green": hex_color = "#00ff00" elif color == "blue": hex_color = "#0000ff" else: hex_color = "unknown" return hex_color print(color_translator("blue")) # Should be #0000ff print(color_translator("yellow")) # Should be unknown print(color_translator("red")) # Should be #ff0000 print(color_translator("black")) # Should be unknown print(color_translator("green")) # Should be #00ff00 print(color_translator("")) # Should be unknown print("big" > "small") def exam_grade(score): if score > 95: grade = "Top Score" elif score >= 60: grade = "Pass" else: grade = "Fail" return grade print(exam_grade(65)) # Should be Pass print(exam_grade(55)) # Should be Fail print(exam_grade(60)) # Should be Pass print(exam_grade(95)) # Should be Pass print(exam_grade(100)) # Should be Top Score print(exam_grade(0)) # Should be Fail def format_name(first_name, last_name): if first_name !="" and last_name != "":# code goes here return "Name: " + last_name + ", " + last_name elif first_name !="" and last_name =="": return "Name: " + first_name elif first_name =="" and last_name !="": return "Name: " + last_name return '""' print(format_name("Ernest", "Hemingway")) # Should be "Name: Hemingway, Ernest" print(format_name("", "Madonna")) # Should be "Name: Madonna" print(format_name("Voltaire", "")) # Should be "Name: Voltaire" print(format_name("", "")) # Should be "" def longest_word(word1, word2, word3): if len(word1) >= len(word2) and len(word1) >= len(word3): word = word1 elif len(word2) > len(word1) and len(word2) > len(word3): word = word2 else: word = word3 return(word) print(longest_word("chair", "couch", "table")) print(longest_word("bed", "bath", "beyond")) print(longest_word("laptop", "notebook", "desktop")) def fractional_part(numerator, denominator): if denominator != 0: remainder = numerator % denominator fraction = remainder / denominator return fraction # Operate with numerator and denominator to # keep just the fractional part of the quotient return 0 print(fractional_part(5, 5)) # Should be 0 print(fractional_part(5, 4)) # Should be 0.25 print(fractional_part(5, 3)) # Should be 0.66... print(fractional_part(5, 2)) # Should be 0.5 print(fractional_part(5, 0)) # Should be 0 print(fractional_part(0, 5)) # Should be 0 def count_down(start_number): current = start_number while (current > 0): print(current) current -= 1 print("Zero!") count_down(3) def smallest_prime_factor(x): """Returns the smallest prime number that is a divisor of x""" # Start checking with 2, then move up one by one n = 2 while n <= x: if x % n == 0: return n n += 1 print(smallest_prime_factor(12)) # should be 2 print(smallest_prime_factor(15)) # should be 3 def print_prime_factors(number): # Start with two, which is the first prime factor = 2 # Keep going until the factor is larger than the number while factor <= number: # Check if factor is a divisor of number if number % factor == 0: # If it is, print it and divide the original number print(factor) number = number / factor else: factor += 1# If it's not, increment the factor by one return "Done" print_prime_factors(100) # Should print 2,2,5,5 def is_power_of_two(n): # Check if the number can be divided by two without a remainder while n % 2 == 0: n = n / 2 # If after dividing by two the number is 1, it's a power of two if n == 1: return True return False def sum_divisors(n): divisor = 1 sum = 0 while n > divisor: if n % divisor == 0: sum += divisor divisor += 1 # Return the sum of all divisors of n, not including n return sum print(sum_divisors(6)) # Should be 1+2+3=6 print(sum_divisors(12)) # Should be 1+2+3+4+6=16 def is_power_of_two(n): # Check if the number can be divided by two without a remainder while n % 2 == 0 and n != 0: n = n / 2 # If after dividing by two the number is 1, it's a power of two if n == 1: return True else: return False print(is_power_of_two(0)) def square(n): return n*n def sum_squares(x): sum = 0 for n in range(x): sum += square(n) return sum print(sum_squares(10)) # Should be 285 def factorial(n): result = 1 for i in range(1, n+1): result *= i return result print(factorial(4)) # should return 24 print(factorial(5)) # should return 120 def factorial(n): result = 1 for x in range(1, n+1): result = result * x return result for n in range(10): print(n, factorial(n)) #Write a script that prints the first 10 cube numbers (x**3), starting with x=1 and ending with x=10. for x in range(1, 11): print (x**3) for x in range(101): if (x % 7) == 0: print(x) def sum_positive_numbers(n): # The base case is n being smaller than 1 if n < 1: return 0 # The recursive case is adding this number to # the sum of the numbers smaller than this one. return n + sum_positive_numbers(n-1) print(sum_positive_numbers(3)) # Should be 6 print(sum_positive_numbers(5)) # Should be 15 number = 1 while number <= 7: print(number, end=" ") number += 1 def show_letters(word): for x in word: print(x) show_letters("Hello") # Should print one line per letter def digits(n): count = 0 if n == 0: return 1 while (int(n) > 0): count += 1 n /= 10 return count print(digits(25)) # Should print 2 print(digits(144)) # Should print 3 print(digits(1000)) # Should print 4 print(digits(0)) # Should print 1 def multiplication_table(start, stop): for x in range(start, stop+1): for y in (range(start, stop+1)): print(str(x*y), end=" ") print() multiplication_table(1, 3) # Should print the multiplication table shown above def counter(start, stop): x = start if start > stop: return_string = "Counting down: " while x >= stop: return_string += str(x) if x > stop: return_string += "," x-= 1 else: return_string = "Counting up: " while x <= stop: return_string += str(x) if x < stop: return_string += "," x+= 1 return return_string print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10" print(counter(2, 1)) # Should be "Counting down: 2,1" print(counter(5, 5)) # Should be "Counting up: 5" for x in range(1, 10, 3): print(x) for x in range(10): for y in range(x): print(y) def first_and_last(message): if message == "" or message[0] == message[-1]: return True else: return False print(first_and_last("else")) print(first_and_last("tree")) print(first_and_last("")) def initials(phrase): words = phrase.split() result = "" for word in words: result += word[0].upper() return result print(initials("Universal Serial Bus")) # Should be: USB print(initials("local area network")) # Should be: LAN print(initials("Operating system")) # Should be: OS def student_grade(name, grade): return "{} received {}% on the exam".format(name, grade) print(student_grade("Reed", 80)) print(student_grade("Paige", 92)) print(student_grade("Jesse", 85)) def is_palindrome(input_string): # We'll create two strings, to compare them new_string = "" reverse_string = "" # Traverse through each letter of the input string for x in input_string: # Add any non-blank letters to the # end of one string, and to the front # of the other string. if x != " ": new_string += x.lower() reverse_string = "".join(reversed(new_string)) # Compare the strings print(new_string, reverse_string) if new_string == reverse_string: return True return False print(is_palindrome("Never Odd or Even")) # Should be True print(is_palindrome("abc")) # Should be False print(is_palindrome("kayak")) # Should be True def convert_distance(miles): km = miles * 1.6 result = "{} miles equals {:.1f} km".format(miles, km) return result print(convert_distance(12)) # Should be: 12 miles equals 19.2 km print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km print(convert_distance(11)) # Should be: 11 miles equals 17.6 km def group_list(group, users): members = ", ".join(users) return '"' + group + ": " + str(members) + '"' print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha" print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom" print(group_list("Users", "")) # Should be "Users:" def skip_elements(elements): # code goes here index = 0 return elements[::2] print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] print(skip_elements([])) # Should be [] def guest_list(guests): for guest in guests: name, age, profession = guest print("{} is {} years old and works as {}".format(name, age, profession)) guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")]) def skip_elements(elements): # code goes here new_elements =[] for index, element in enumerate(elements): if index % 2 == 0: new_elements.append(element) return new_elements print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] def skip_elements(elements): return [ element for element in elements if elements.index(element) % 2 == 0] print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"] newfilenames = [] for filename in filenames: old_name = filename if filename.endswith(".hpp"): new_name = filename.replace(".hpp", ".h") else: new_name = old_name newfilename = (old_name, new_name) newfilenames.append(newfilename) print (newfilenames) # Should be [('program.c', 'program.c'), ('stdio.hpp', 'stdio.h'), ('sample.hpp', 'sample.h'), ('a.out', 'a.out'), ('math.hpp', 'math.h'), ('hpp.out', 'hpp.out')] def octal_to_string(octal): result = "" value_letters = [(4,"r"),(2,"w"),(1,"x")] # Iterate over each of the digits in octal for x in [int(n) for n in str(octal)]: # Check for each of the permissions values for value, letter in value_letters: if x >= value: result += letter x -= value else: result += "-" return result print(octal_to_string(755)) # Should be rwxr-xr-x print(octal_to_string(644)) # Should be rw-r--r-- print(octal_to_string(750)) # Should be rwxr-x--- print(octal_to_string(600)) # Should be rw------- def pig_latin(text): say = "" # Separate the text into words words = text.split(" ") for word in words: # Create the pig latin word and add it to the list new_word = word[1:] + word[0] + "ay" say = say + new_word + " " # Turn the list back into a phrase return say print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay" print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay" toc = {"Introduction":1, "Chapter 1":4, "Chapter 2":11, "Chapter 3":25, "Chapter 4":30} toc["Epilogue"] = 39 # Epilogue starts on page 39 toc["Chapter 3"] = 24 # Chapter 3 now starts on page 24 print(toc) # What are the current contents? print("Chapter 5" in toc) # Is there a Chapter 5? cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"} for beast, thing in cool_beasts.items(): print("{} have {}".format(beast, thing)) wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]} for k, v in wardrobe.items(): for color in v: print("{} {}".format(color, k)) def email_list(domains): emails = [] for domain, users in domains.items(): for user in users: emails.append("{}@{}".format(user, domain)) return(emails) print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]})) def groups_per_user(group_dictionary): user_groups = {} # Go through group_dictionary for group, users in group_dictionary.items(): # Now go through the users in the group for user in users: if user in user_groups: user_groups[user].append(group) else: user_groups[user] = [group] # Now add the group to the the list of # groups for this user, creating the entry # in the dictionary if necessary return(user_groups) print(groups_per_user({"local": ["admin", "userA"], "public": ["admin", "userB"], "administrator": ["admin"] })) def format_address(address_string): # Declare variables addresses = [] house_number = 0 street_name = "" # Separate the address string into parts addresses = address_string.split(" ") # Traverse through the address parts for address in addresses: # Determine if the address part is the # house number or part of the street name if address.isnumeric(): house_number = int(address) else: street_name = street_name + address + " " # Does anything else need to be done # before returning the result? # Return the formatted string return "house number {} on street named {}".format(house_number, street_name) print(format_address("123 Main Street")) # Should print: "house number 123 on street named Main Street" print(format_address("1001 1st Ave")) # Should print: "house number 1001 on street named 1st Ave" print(format_address("55 North Center Drive")) # Should print "house number 55 on street named North Center Drive" def highlight_word(sentence, word): return sentence.replace(word, word.upper()) print(highlight_word("Have a nice day", "nice")) print(highlight_word("Shhh, don't be so loud!", "loud")) print(highlight_word("Automating with Python is fun", "fun")) def combine_lists(list1, list2): # Generate a new list containing the elements of list2 # Followed by the elements of list1 in reverse order new_list1 = list1[::-1] for item in new_list1: list2.append(item) return list2 Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"] Drews_list = ["Mike", "Carol", "Greg", "Marcia"] print(combine_lists(Jamies_list, Drews_list)) def squares(start, end): return [ x**2 for x in range(start, end+1) ] print(squares(2, 3)) # Should be [4, 9] print(squares(1, 5)) # Should be [1, 4, 9, 16, 25] print(squares(0, 10)) # Should be [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] def car_listing(car_prices): result = "" for k, v in car_prices.items(): result += "{} costs {} dollars".format(k, v) + "\n" return result print(car_listing({"Kia Soul":19000, "Lamborghini Diablo":55000, "Ford Fiesta":13000, "Toyota Prius":24000})) def combine_guests(guests1, guests2): # Combine both dictionaries into one, with each key listed # only once, and the value from guests1 taking precedence for k, v in guests2.items(): if k not in guests1.keys(): guests1[k] = v return guests1 Rorys_guests = { "Adam":2, "Brenda":3, "David":1, "Jose":3, "Charlotte":2, "Terry":1, "Robert":4} Taylors_guests = { "David":4, "Nancy":1, "Robert":2, "Adam":1, "Samantha":3, "Chris":5} print(combine_guests(Rorys_guests, Taylors_guests)) def count_letters(text): result = {} # Go through each letter in the text for letter in text: # Check if the letter needs to be counted or not if letter.isalpha(): if not letter.lower() in result: result[letter.lower()] = 1 else: result[letter.lower()] += 1 # Add or increment the value in the dictionary return result print(count_letters("AaBbCc")) # Should be {'a': 2, 'b': 2, 'c': 2} print(count_letters("Math is fun! 2+2=4")) # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1} print(count_letters("This is a sentence.")) # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1} animal = "Hippopotamus" print(animal[3:6]) print(animal[-5]) print(animal[10:]) colors = ["red", "white", "blue"] colors.insert(2, "yellow") print(colors) host_addresses = {"router": "192.168.1.1", "localhost": "127.0.0.1", "google": "8.8.8.8"} print(host_addresses.keys()) class Flower: color = 'unknown' rose = Flower() rose.color = "red" violet = Flower() violet.color = "violet" this_pun_is_for_you = Flower() print("Roses are {},".format(rose.color)) print("violets are {},".format(violet.color)) print(this_pun_is_for_you) # “If you have an apple and I have an apple and we exchange these apples, then # you and I will still each have one apple. But if you have an idea and I have # an idea and we exchange these ideas, then each of us will have two ideas.” # George Bernard Shaw class Person: apples = 0 ideas = 0 johanna = Person() johanna.apples = 1 johanna.ideas = 1 martin = Person() martin.apples = 2 martin.ideas = 1 def exchange_apples(you, me): #"you" and "me" will exchange ALL our apples with one another you.apples, me.apples = me.apples, you.apples return you.apples, me.apples def exchange_ideas(you, me): #"you" and "me" will share our ideas with one another you.ideas += me.ideas me.ideas += you.ideas return you.ideas, me.ideas exchange_apples(johanna, martin) print("Johanna has {} apples and Martin has {} apples".format(johanna.apples, martin.apples)) exchange_ideas(johanna, martin) print("Johanna has {} ideas and Martin has {} ideas".format(johanna.ideas, martin.ideas)) class Dog: years = 0 def dog_years(self): return self.years * 7 fido=Dog() fido.years=3 print(fido.dog_years()) class Person: def __init__(self, name): self.name = name def greeting(self): # Should return "hi, my name is " followed by the name set. return "hi, my name is {}".format(self.name) # Create a new instance with a name of your choice some_person = Person("Kevin") # Call the greeting method print(some_person.greeting()) class Person: def __init__(self, name): self.name = name def greeting(self): """Outputs a message with the name of the person""" print("Hello! My name is {name}.".format(name=self.name)) class Clothing: material = "" def __init__(self,name): self.name = name def checkmaterial(self): print("This {} is made of {}".format(self.name, self.material)) class Shirt(Clothing): material="Cotton" polo = Shirt("Polo") polo.checkmaterial() class Clothing: stock={ 'name': [],'material' :[], 'amount':[]} def __init__(self,name): material = "" self.name = name def add_item(self, name, material, amount): Clothing.stock['name'].append(self.name) Clothing.stock['material'].append(self.material) Clothing.stock['amount'].append(amount) def Stock_by_Material(self, material): count=0 n=0 for item in Clothing.stock['material']: if item == material: count += Clothing.stock['amount'][n] n+=1 return count class shirt(Clothing): material="Cotton" class pants(Clothing): material="Cotton" polo = shirt("Polo") sweatpants = pants("Sweatpants") polo.add_item(polo.name, polo.material, 4) sweatpants.add_item(sweatpants.name, sweatpants.material, 6) current_stock = polo.Stock_by_Material("Cotton") print(current_stock)
6f6873cf62a86040fb752a52e0107a03e87819cf
gl59789/python_study
/test.py
1,743
4.03125
4
#!/usr/bin/env python3 import csv import datetime import requests FILE_URL="http://marga.com.ar/employees-with-date.csv" def get_start_date(): """Interactively get the start date to query for.""" print() print('Getting the first start date to query for.') print() print('The date must be greater than Jan 1st, 2018') year = int(input('Enter a value for the year: ')) month = int(input('Enter a value for the month: ')) day = int(input('Enter a value for the day: ')) print() return datetime.datetime(year, month, day) def get_file_sorted_contents(url, start_date): """Returns the lines contained in the file at the given URL""" # Download the file over the internet response = requests.get(url, stream=True) # Decode all lines into strings lines = [] for line in response.iter_lines(): lines.append(line.decode("UTF-8")) reader = csv.reader(lines[1:]) list_row = [] for row in reader: list_row.append(row) new_list = sorted(list_row, key=lambda x: x[3]) index = 0 for item in new_list: item_date = datetime.datetime.strptime(item[3], '%Y-%m-%d') if item_date <= start_date: index = index + 1 if item_date > start_date: break return new_list[index:] def list_newer(final_list): for item in final_list: start_date, employees_firstname, employees_lastname = item[3], item[1], item[0] print("Started on {}: {} {}".format(start_date, employees_firstname, employees_lastname)) def main(): start_date = get_start_date() sorted_list = get_file_sorted_contents(FILE_URL, start_date) list_newer(sorted_list) if __name__ == "__main__": main()
7484545ad36c3a3f69a2e4ba23d0d560341ea08d
PseudoMera/Universal_Translator
/test_translator.py
1,876
3.5
4
import unittest import universal_translator class UniversalTranslatorTest(unittest.TestCase): '''Raises file not found error if the given file route is empty''' def test_empty_file_route(self): universe = universal_translator.UnitsTranslator('') with self.assertRaises(FileNotFoundError): universe.read_file() '''Raises file not found error if the user is tries to use a file that does not exist''' def test_file_does_not_exist(self): universe = universal_translator.UnitsTranslator('File examples/test22345.txt') with self.assertRaises(FileNotFoundError): universe.read_file() '''Raises key error exception if unit is not valid''' def test_unit_not_valid(self): universe = universal_translator.UnitsTranslator('File examples/test.txt') with self.assertRaises(KeyError): universe.convert_unit(25, 'm', 'c') '''Raises is a directory error if the route does not point to a file but to a directory''' def test_is_a_directory(self): universe = universal_translator.UnitsTranslator('File examples') with self.assertRaises(IsADirectoryError): universe.read_file() '''Raises type error if the given value is not a number but another type''' def test_not_a_number(self): universe = universal_translator.UnitsTranslator('File examples/test.txt') with self.assertRaises(TypeError): universe.convert_unit('this is a test', 'm', 'cm') '''Raises a value error if we try to convert the given value but it's not possible''' def test_not_a_number2(self): universe = universal_translator.UnitsTranslator('File examples/test.txt') with self.assertRaises(ValueError): universe.convert_unit(float('this is a test'), 'm', 'cm') if __name__ == '__main__': unittest.main()
aa82a8532d95a78f041a29fdc44b655f056674a7
yanni-kim/python-
/Ex 06_27.py
4,150
3.859375
4
# x=10 # for i in range(x):#10번만큼 #횟수반복? # print(x)#10 # while x>10:#조건반복문 # # 주석 ctrl + / # # 전체주석 - 범위 설정 '''''' # for index in range(8): # #range(start=0,stop,step=1) # 1 2 3 # print(list(range(6))) #[0, 1, 2, 3, 4, 5] # # print(list(range(1,6))) #[1, 2, 3, 4, 5] # print(list(range(1,10))) #[1, 2, 3, 4, 5, 6, 7, 8, 9] # print(list(range(1,10,2))) #[1, 3, 5, 7, 9] # for i in range(1,8,2):#0~7 # print(10) ''' #5장 본문 #난수를 이용하여 간단한 축구 게임을 작성. 사용자가 컴퓨터를 상대로 페널티 킥을 하고 3개의 영역중 하나를 수비 #1. 난수설정 #2. 어디를 수비할것인지 결정 #3. 컴퓨터 랜덤 선택과 나의 수비지역이 맞으면 성공 #4. 그렇지 않으면 패널티킥이 성공 import random options=["왼쪽","중앙","오른쪽","왼쪽 상단","왼쪽하단","오른쪽상단","오른쪽 하단"] computer_choice = random.choice(options) #옵션을 랜덤으로 하여 변수로 설정 user_choice = input("어디를 수비하시겠어요?(왼쪽, 오른쪽, 중앙, 왼쪽상단, 외쪽하단, 오른쪽상단, 오른쪽 하단)") if computer_choice == user_choice: print("수비에 성공하셨습니다.") else: print("패널티킥이 성공하였습니다.") ''' ''' #연습문제 #4. 시험점수를 물어보고 90점이상이면 A, 80점이상 B, 70점 이상 C, 60점 이상 D, 그외 F의 프로그램 score=int(input("시험점수는 몇점입니까?")) if score >= 90 : print("성적은 A학점입니다.") elif score >= 80 : print("성적은 B학점입니다.") elif score >= 70 : print("성적은 c학점입니다.") elif score >= 60: print("성적은 D학점입니다.") else: print("성적은 F학점입니다.") ''' ''' #5. 난수를 사용, 1~100의 숫자를 생성, 뺄셈문제를 생성하고 사용자에게 답이 맞는지 검사하는 프로그램 import random x = random.randint(1, 100) y = random.randint(1, 100) cal = x - y print(int(cal)) ans = int(input("답은 무엇인가요?")) if ans == cal : print("맞습니다.") else : print("틀립니다.") ''' ''' #6. 정수를 받아 2와 3으로 나누어 떨어질 수 있는지를 출력 n=int(input("정수를 입력하시오:")) if n % 2 ==0 and n%3 ==0: print("2와 3으로 나누어 떨어집니다.") ''' # #????7번. 사용자가 가지고 있는 복권번호가 2자리 모두 일치하면 100만원, 하나만 일치하면 50만원, 하나도 일치하지 않으면 상금없음. 복권번호 난수, 상금출력 # #1. 사용자 2자리 복권번호 받기 # #2. 복권번호 난수로 생성 # #3. 두자리중 맞는 수에 따른 상금 제시 (상금은 00원입니다) # lotto=int(input("2자리 복권번호 digit1과 digit2를 입력하시오:"))#64 # lotto_digit1 = lotto // 10 #0~9,몫 , 십의자리,앞자리,6 # lotto_digit2 = lotto % 10 #0~9,나머지, 1의자리,4 # import random # n = random.randint(1,99) #랜덤값 # # n = 98 # n_digit1 = n // 10 #0~9,몫 , 십의자리 #9 # n_digit2 = n % 10 #0~9,나머지, 1의자리 #8 # if lotto==n: # # print("상금은"+100+"만원입니다") # print(f"상금은 {100}만원입니다")#f-string # elif lotto_digit1==n_digit1 or lotto_digit2 == n_digit2: # print(f"상금은 {50}만원입니다") # else: # print("상금은 없습니다") # a, b = map(int,input("두 정수 a,b를 입력하시오:").split()) # print(a*b) print("a") ''' a,b=input("두 정수 a,b를 입력하시오:").split() a=int(a) b=int(b) print(a+b) a,b,c=input("세 정수 a,b,c를 입력하시오:").split() a=int(a) b=int(b) c=int(c) print((a+b)%c) print(((a%c)+(b%c))%c) print((a*b)%c) print(((a%c)*(b%c))%c) ''' ''' # 백준:사분면 구하기 x=int(input("x좌표의 정수를 입력하시오:")) y=int(input("y좌표의 정수를 일별하시오:")) if x>0 and y>0: print(1) elif x<0 and y>0: print(2) elif x<0 and y<0: print(3) else: print(4) ''' ''' #알람일찍설정하기 H,M = input("시와 분을 입력하시오:").split() print(H,"시",M,"분") if (M-45)<=0: '''
7970208b9889a001dbb9fecceaf5a765ceb8b46f
jdurbin/sandbox
/python/basics/scripts/dictionary.py
177
3.53125
4
#!/usr/bin/env python m = {'foo':40,'bar':9000,'killroy':100000} print m['bar'] s = set() s.add('foo') s.add('foo') s.add('bar') print s print 'foo' in s print 'mary' in s
e3c8b5241b67c829edc0b1ff4da04dd6e764a89a
jdurbin/sandbox
/python/basics/scripts/lists.py
738
4.15625
4
#!/usr/bin/env python import numpy as np a = [1,2,3,4] print a print a[2:5] # omitted in a slice assumed to have extreme value print a[:3] # a[:] is just a, the entire list print "a[:-1]",a[:-1] print "a[:-2]",a[:-2] #numpy matrix: # Note that [,] are lists, but (,) are tuples. # Lists are mutable, tuples are not. # tuple is a hashtable so you can use it as a dictionary(??) mat = np.zeros((3,3)) print "MAT:\n",mat # slices are always views, not copies. mat2=np.array([[1,2,3],[4,5,6],[7,8,9]]) print "MAT2:\n",mat2 print "MAT2[0:2]\n",mat2[0:2] print "MAT2[,0:2]\n",mat2[:,0:2] print "MAT2[0:1,0:2]:\n",mat2[0:1,0:2] print "mat sqrt:\n",np.sqrt(mat2) mat3 = np.array([2,2,2]) print "mat2 dot mat3:\n",mat2.dot(mat3)
9ade768d14ed30852d93b3394fae8d5b7a1ac68d
jdurbin/sandbox
/python/basics/scripts/classtest.py
685
3.890625
4
#!/usr/bin/env python #import SuperClass # OK.. I think there is not a 1-1 correspondence between modules (files) and classes. # So import SuperClass just means to import the file/module. # If you want to import the class SuperClass from the file SuperClass, you need something like: from SuperModule import SuperClass # I presume this also means that the file could have some unrelated name... yep! # OK, got it. sc = SuperClass() print sc.superAwesomeFunction(5) # Interrogate the class.. # Is this really the most succinct way to show this... #print 'The name of class for sc is: {}'.format(sc.__class__.__name__) print 'The name of class for sc is:',sc.__class__.__name__
90fe75d8eb2eb8f8b2b4e105013c7f32baed9c3f
rowaishanna/DS-Unit-3-Sprint-2-SQL-and-Databases
/northwind.py
2,055
3.78125
4
import os import sqlite3 # construct a path to wherever your database exists DB_FILEPATH = os.path.join(os.path.dirname(__file__), "northwind_small.sqlite3") connection = sqlite3.connect(DB_FILEPATH) #connection.row_factory = sqlite3.Row # allow us to reference rows as dicts #print("CONNECTION:", connection) cursor = connection.cursor() #print("CURSOR", cursor) # 10 most expensive items per unit price Query: query = """ SELECT ProductName, UnitPrice FROM Product ORDER by UnitPrice DESC LIMIT 10; """ result = cursor.execute(query).fetchall() print ("10 most expensive items per unit price", result[0:][0:]) connection.commit() # Employees' Average Age at time of hiring: query2 = """ SELECT avg("Age at time of hire") as "Avg Age at time of hire" FROM (SELECT Id, BirthDate, HireDate , datetime(HireDate) - datetime(BirthDate) AS "Age at time of hire" from Employee) subq; """ cursor = connection.cursor() result2 = cursor.execute(query2).fetchall() print("Employees' Average Age at time of hiring", result2[0:][0:]) connection.commit() ############################################ # 10 most expensive items per unit price and their suppliers: query3 = """ SELECT Product.ProductName, Product.SupplierID, Product.UnitPrice FROM Product JOIN Supplier on Product.SupplierId = Supplier.ID ORDER by UnitPrice DESC LIMIT 10; """ cursor = connection.cursor() result3 = cursor.execute(query3).fetchall() print("10 most expensive items per unit price and their suppliers", result3[0:][0:]) connection.commit() ############### # largest category number of unique products: query4 = """ SELECT max("Products_per_Category") as 'largest_category' FROM ( SELECT Product.CategoryId, COUNT (DISTINCT Product.Id) as Products_per_Category FROM Product JOIN Category on PRODUCT.CategoryId = Category.Id GROUP BY CategoryId) subq; """ cursor = connection.cursor() result4 = cursor.execute(query4).fetchall() print("largest category by number of unique products", result4[0:][0:]) connection.commit() # close cursor.close() connection.close()
1094b25304b97de57e1e9c940b56afc5945a181d
smileykaur/Travel-Insight
/Travel_Insights-master/src/data_preprocessing.py
5,102
3.546875
4
""" Step 2 : Data aggregation: aggregate data to generate text corpus: This will clean the raw data that was gathered from Reddit - - convert data to format that can be directly consumed by Dataframes, """ import pandas as pd import os from .config import ( AGG_BY_SUB, COMMENTS_COLS, REPLIES_COLS, ) class DataPreprocessing: def __init__(self): self.RAW_SUBMISSIONS = "../data/submission.tsv" self.RAW_COMMENTS = "../data/comments.tsv" self.RAW_REPLIES = "../data/replies.tsv" def generate_clean_source_files(self): # load data after handling exceptions self.df_submissions = pd.read_csv(self.RAW_SUBMISSIONS, sep='\t') self.df_comments = pd.DataFrame(self.generate_dataframe(self.RAW_COMMENTS, COMMENTS_COLS)) self.df_replies = pd.DataFrame(self.generate_dataframe(self.RAW_REPLIES, REPLIES_COLS)) # TODO: Load this data to Database (serve as main data source) # write df to csv #self.load_df_to_csv() def load_df_to_csv(self): # writing df to csv- source_data_dir = "../data/" + "source_data/" if not os.path.exists(source_data_dir): os.mkdir(source_data_dir) self.df_submissions.to_csv("{0}submission.csv".format(source_data_dir)) self.df_comments.to_csv("{0}comments.csv".format(source_data_dir)) self.df_replies.to_csv("{0}replies.csv".format(source_data_dir)) def generate_dataframe(self, input_file, columns_list): """ Generate a dataframe for given set of inputs :param columns_list: List of column names :return: Dictionary for Dataframe """ data_dict = dict([(key, []) for key in columns_list]) # read file with open(input_file, "r") as filereader: filereader.readline() for line in filereader: try: data = line.strip().split("\t") if len(data) == len(columns_list): for _col_ind, _col_name in enumerate(columns_list): data_dict[_col_name].append(data[_col_ind]) except Exception as ex: # logging.warning("trouble reading the record due to {}".format(ex)) # TODO: Set up a logger print("trouble reading the record due to {}".format(ex)) return data_dict def aggregate_replies_to_comments(self,): """ 1. Roll up Replies at comment level for each 'submission_id', 'comment_id' ['submission_id', 'submission_topic', 'comment_id', 'text] Group replies and roll up to comments_id Output: Generate .csv file :return: None """ # group replies by comment_id grouped_replies = self.df_replies.groupby(['comments_id'])['reply']\ .apply(lambda x: "%s" % ','.join(x)).reset_index() # merging grouped replies with comments grouped_comments = pd.merge(self.df_comments[['comments_id', 'comment_date', 'submission_id', 'comment']], grouped_replies, on='comments_id') grouped_comments['comment'] = grouped_comments['comment'] + grouped_comments['reply'] # Output aggregated comments output_loc = "../data/aggregated_data/" if not os.path.exists(output_loc): os.mkdir(output_loc) df_grouped_comments = grouped_comments[['comments_id', 'comment_date', 'submission_id', 'comment']] df_grouped_comments.to_csv(output_loc+"group_by_comments.csv", index=False) # Aggregate aggregated comments by submission_id self.aggregate_comments_to_submission(df_grouped_comments, output_loc) return def aggregate_comments_to_submission(self, df_grouped_comments, output_loc): """ Roll up replies and comments for each 'submission_id' that generate all text for a submission ['submission_id', 'submission_topic', 'text'] Output: Generate .csv file :return: None """ # group comments by submission_id grouped_comments = df_grouped_comments.groupby(['submission_id'])['comment']\ .apply(lambda x: "%s" % ','.join(x)).reset_index() # merging grouped comments with submission grouped_submissions = pd.merge(self.df_submissions[['submission_id', 'submission_date', 'title']], grouped_comments, on='submission_id') df_grouped_submissions = grouped_submissions[['submission_id', 'submission_date', 'title', 'comment']] df_grouped_submissions.to_csv(output_loc + "group_by_submissions.csv", index=False) return def aggregate_by_month(self): """ aggregate by month and year for each of DF and then aggregate :return: """ # TODO: aggregate by month # aggregate replies by month , year # aggregate comments by month , year # generate the counter - This will be substituted by SQL # return
20d2c16838f90918e89bfcf67d7c1f9210d6d39a
vaishu8747/Practise-Ass1
/1.py
231
4.34375
4
def longestWordLength(string): length=0 for word in string.split(): if(len(word)>length): length=len(word) return length string="I am an intern at geeksforgeeks" print(longestWordLength(string))
24000008f2143fa725a07820e546aa038aee31dd
streetracer48/python-sandbox
/variables.py
702
3.84375
4
# A variable is a container for a value , which can be of various types ''' this is a multiline comment ordocstring (used to define a function purpose) can be single or double quotes ''' """ Variable Rules: - Variable names are case sensitive (name and name are different variables) - Must start with a letter or an underscore -can have number but can not start with one """ ''' Variables types ''' # x= 1 #int # y = 2.5 #float # name= 'Miraz' #string # is_cool = True #bool #Multiple Assigment x,y, name, is_cool = (1, 2.5, 'Miraz', True) print (x,y,name, is_cool) #Basic math a=x+y print (a) #Casting x= str(y) print(x) y= init(y) #Check Type print (type(is_cool)) print (type(y))
4d232316edef7a8dbf7ca88c1ffbb53efc179b3d
vineetdcunha/Python
/Ellipse_Area_Circumference.py
1,381
4
4
#Name: Vineet Dcunha #"I have not given or received any unauthorized assistance on this assignment." import math class ellipse_default: 'Creates a default ellipse class to set default parameters, find area and circumference' def __init__ (self,xcoord = 0,ycoord = 0, a = 0, b = 0): 'Creates an ellipse with default parameters of (x,y) = (0,0) and (a,b) = (0,0)' self.x = (xcoord) # Sets value of x coordinate self.y = (ycoord) # Sets value of y coordinate self.major_axis = (a) # Sets value of major axis self.minor_axis = (b) # Sets value of minor axis def get_area(self): 'Returns area of an ellipse' print (ellipse_default.get_area.__doc__) area = 0.0 print('This function will return the area of an ellipse.') area = math.pi * self.major_axis * self.minor_axis # calculates area print('Area of an ellipse: ',area,'\n') def get_circumference(self): 'Returns circumference of an ellipse' print (ellipse_default.get_circumference.__doc__) circum = 0.0 print('This function will return the circumference of an ellipse.') circum = 2 * math.pi * math.sqrt ((self.major_axis**2 + self.minor_axis**2)/2) # calculates circumference print('Circumference of an ellipse: ',circum,'\n')
c1fa87a3dd6e8f1393793502b206754432756c01
jueqingsizhe66/pyqt
/boobooexam.py
685
3.84375
4
#date :2013-1-18 #author :zhaoliang #function: the way to define class and constructor import sys import os class test(): def _init_(self,name1='test',age1=0): self.name=name1 self.age=age1 def setfun(self,new_name,new_age): self.name=new_name self.age=new_age def getfun(self): return self.name,self.age def show(self): print "my name is: %s,and the age is :%d"%(self.name,self.age) if __name__ == "name": title = raw_input("please enter of name :") print "the enter of string is:",title tt = test() tt.show() tt.setfun("tester",22) tt.show() print tt.getfun() print os.path
4b19a8766b1202f65463b878b588b7396ec6830d
Ali1422/Working-Calculator
/calculator.py
2,261
4.09375
4
import time print("Welcome to Kala's calculator") while True: print("\nHere are the options") options = input("please enter 1 for addition, 2 for subtraction, 3 for division and 4 for multiplacation") if options == "1" : time.sleep(2) print("\n you have chosen addition") num1 = int(input("please enter a number")) num2 = int(input("please enter another number")) addition = num1 + num2 print ("The answer to your sum is", addition) time.sleep(2) print("Thank you for feeding me summs daddy uwu, please run me again to give me your cummie wummies") elif options == "2": time.sleep(2) print("\n you have chosen subtraction") num1 = int(input("please enter a number to subtract from")) num2 = int(input("please enter a number to take away")) subtraction = num1 - num2 print("The answer to your sum is",subtraction) time.sleep(2) print("Thank you for feeding me summs daddy uwu, pleased run me again to give me your cummie wummies") elif options == "3": time.sleep(2) print("\n you have chosen division") num1 = int(input("please enter a number to divide by")) num2 = int(input("please enter the number you would like it divided by")) division = num1/num2 print("the answer to your sum is",division) time.sleep(2) print("Thank you for feeding me summs daddy uwuw, please run me again to give me your cummie wummies") elif options == "4": time.sleep(2) print("\n you have chosen multiplacation") num1 = int(input("please enter a number")) num2 = int(input("please enter another number")) multiplacation = num1 * num2 print("the answer to your sum is",multiplacation) time.sleep(2) print("Thank you for feeding me summs daddy uwuw, please run me again to give me your cummie wummies") else: print("YOU DARE OPPOSE ME MORTAL! YOU BUFFON, YOU FOOL, YOU ABSOLUTE PEASENT! DO YOU NOT KNOW OF YOUR GODS") time.sleep(5) print("there are some things that are scarier then God")
9c401c9d072f0c164ec7b397102b7c30bffdf507
st3fan/exercism
/python/list-ops/list_ops.py
779
3.765625
4
from functools import reduce def append(list1, list2): return list1+list2 def concat(lists): result = [] for list in lists: result += list return result def filter(function, list): return [v for v in list if function(v)] def length(list): n = 0 for _ in list: n += 1 return n def map(function, list): return [function(v) for v in list] def foldl(function, list, initial): result = initial for v in list: result = function(result, v) return result def foldr(function, list, initial): result = initial for v in reversed(list): result = function(v, result) return result def reverse(list): result = [] for i in list: result = [i] + result return result
e0567b807de8d9de78b5b6446648a1738bde2c10
zhl2013/dba_syncer
/sync_mongo2mysql/test.py
1,211
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/3/16 14:15 # @Author : 马飞 # @File : file_upload.py # @Software: PyCharm # import sys # def is_number(s): # try: # int(s) # return True # except ValueError: # return False # # for line in sys.stdin: # a= line.split() # if is_number(a[0]): # print('YES') # else: # print('NO') # # def is_number(s): # try: # int(s) # return True # except ValueError: # return False # # a= input() # if is_number(a): # print('YES') # else: # print('NO') def is_number(s): try: int(s) return True except ValueError: return False def isperfectNumber(n): a = 1 b = n s = 0 while a < b: if n % a ==0: s += a + b a += 1 b = n/a if a ==b and a*b == n: s +=a return s - n == n a= input() if is_number(a): if isperfectNumber(int(a)): print(int(a)) print('YES') else: print('NO') else: print('NO') print('2-1000之间的完全数') print('---------------------------') for k in range(2,1000): if isperfectNumber(k): print(k)
e4682fe7b4cd8451783216fefea81cd111674f90
nadiia-tokareva/skillup
/lesson 3-9/3.py
1,314
3.9375
4
class Money: def __init__(self, name= None, symbol= None ): self.kind = '' self.name = name self.symbol = symbol def __str__(self) -> str: return f'The {self.name} is {self.kind} money and has symbol {self.symbol}' def money_type(self): return self.kind def get_dollars(self): ask = input('Do you want change some euros? yes/no ') if ask == 'yes': change= float(input('How much euro? ')) return f'The {change} euros equals {change *1.17} dollars' class Paper(Money): def __init__(self, **kwargs): super().__init__(**kwargs) self.kind = 'paper' class Coin(Money): def __init__(self, **kwargs): super().__init__(**kwargs) self.kind = 'metal' def coin_to_banknote(self): x= float(input('How many coins do you want to change? ')) return f'The {x} equals {x * 0.01} paper money' euro = Paper(name= 'Euro', symbol= '€' ) euro_cent = Coin(name= 'Euro cent', symbol= '€') dollar = Paper(name= 'Dollar', symbol= '$' ) cent = Coin(name= 'Cent', symbol= '$' ) print(euro) print(euro_cent) print(dollar) print(cent) print(euro.money_type()) print(euro_cent.money_type()) print(Paper.get_dollars(euro)) print(Coin.coin_to_banknote(euro_cent))
2a2cecc407c7a7437dd75c7e154d18bdfa620ccd
kishorebiyyapu/Guvi-practice2
/prog122.py
432
3.59375
4
a,b,c=input().split('-') if b=='01': print("January") elif b=='02': print("Febrary") elif b=='03': print("March") elif b=='04': print("April") elif b=='05': print("May") elif b=='06': print("June") elif b=='07': print("July") elif b=='08': print("August") elif b=='09': print("September") elif b=='10': print("October") elif b=='11': print("November") elif b=='12': print("December")
09add573ddc4e808dcd768f8172487cb8acd36aa
josevictor1/CC
/Parte_1/codigos/micro04.py
299
3.65625
4
def micro04(): x = 0 num = 0 intervalo = 0 for x in range(5): print("Digite o numero: ", end = "") num = int(input()) if num >= 10: if num <= 150: intervalo = intervalo +1 print("Ao total, foram digitados "+str(intervalo)+" numeros no intervalo entre 10 e 150") micro04()
7462b7bb66c8da8ec90645eb00a654c316707b28
matheus-hoy/jogoForca
/jogo_da_forca.py
1,154
4.1875
4
print('Bem Vindo ao JOGO DA FORCA XD') print('Você tem 6 chances') print() palavra_secreta = 'perfume' digitado = [] chances = 6 while True: if chances <= 0: print('YOU LOSE') break letra = input('Digite uma letra: ') if len(letra) > 1: print('Digite apenas uma letra Malandro') continue digitado.append(letra) if letra in palavra_secreta: print(f'Boa, a letra "{letra}" faz parte da Palavra secreta.') else: print(f'Putz, a letra "{letra}" não faz parte da Palavra secreta.') digitado.pop() secreto_temporario = '' for letra_secreta in palavra_secreta: if letra_secreta in digitado: secreto_temporario += letra_secreta else: secreto_temporario+= '*' if secreto_temporario == palavra_secreta: print('PARABÉNS, VOCÊ CONSEGUIU... IHAAAAA') break else: print(f'A palavra secreta está assim: {secreto_temporario}') if letra not in palavra_secreta: chances -= 1 print(f' Voce ainda pode tentar: {chances}x') print()
d68850ca68e9d5d44b73956a58639a0a8ea8495e
samh99474/Python-Class
/pythone_classPractice/week3/Week3_Quiz_106360101謝尚泓/quiz4.py
885
3.796875
4
def main(): global grid_size global row_sign global col_sign row_sign = "-" col_sign = "|" print("Quiz 4") row_num = int(input("Numbers of rows:")) col_num = int(input("Numbers of colum:")) grid_size = int(input("Grid size:")) row_sign = row_sign*grid_size for i in range(0, row_num+1): print(string_row(col_num)) if i != row_num: for j in range(0, grid_size): print(string_row2(col_num)) def string_row(col_num): for i in range(0, col_num): if i == 0: row = "+" + row_sign + "+" else: row = row + row_sign + "+" return row def string_row2(col_num): for i in range(0, col_num): if i == 0: col = col_sign + " "*grid_size + col_sign else: col = col + " "*grid_size + col_sign return col
16943c73ad58d206b2f4f13467ab0cc48f95596d
samh99474/Python-Class
/pythone_classPractice/week6(object)/download/Week6_Quiz_106360101謝尚泓/AddStu.py
1,978
3.875
4
class AddStu(): def __init__(self, student_dict): self.student_dict = student_dict def execute(self): try: print("新增學生姓名和分數") name = str(input(" Please input a student's name: ")) subject = "" score = 0 while subject != "exit": try: subject = str(input(" Please input a subject or exit for ending: ")) if(subject == "exit"): # subject == "exit" exit for ending if(self.student_dict[name] == {}): del self.student_dict[name] # 清空學生 完全沒subject的字典 success = False break while score >= 0: try: score = int(input(" Please input {}'s {} score or < 0 for discarding the subject: ".format(name, subject))) #盡量用format轉換格式 if(score < 0): score = 0 # initailize score break self.student_dict[name][subject] = score # 都成功即可寫入進去student_dict success = True break except: pass except: pass except Exception as e: #若try有錯誤,則執行except print("The exception {} occurs.".format(e)) success = False finally: #不管try有沒有錯誤,最後一定會執行final if(success == True): print(self.student_dict) print("新增成功") else: print("新增失敗") print("Execution result is {}".format(success)) return self.student_dict
c3d5f8a11f3eab94634fa09ff7a04d5eea1ff3fd
samh99474/Python-Class
/pythone_classPractice/week13_14(pyqt5_switch_widget_moreWidget)/Week13_Quiz_106360101謝尚泓/Server/DB/StudentInfoTable.py
1,640
3.53125
4
from DB.DBConnection import DBConnection class StudentInfoTable: def insert_a_student(self, name): command = "INSERT INTO student_info (name) VALUES ('{}');".format(name) with DBConnection() as connection: cursor = connection.cursor() cursor.execute(command) connection.commit() def select_a_student_id(self, name): command = "SELECT * FROM student_info WHERE name='{}';".format(name) with DBConnection() as connection: cursor = connection.cursor() cursor.execute(command) record_from_db = cursor.fetchall() return [row['stu_id'] for row in record_from_db] def select_all_student_id(self): command = "SELECT * FROM student_info;" with DBConnection() as connection: cursor = connection.cursor() cursor.execute(command) record_from_db = cursor.fetchall() return [row['stu_id'] for row in record_from_db], [row['name'] for row in record_from_db] def delete_a_student(self, stu_id): command = "DELETE FROM student_info WHERE stu_id='{}';".format(stu_id) with DBConnection() as connection: cursor = connection.cursor() cursor.execute(command) connection.commit() def update_a_student_name(self, stu_id, new_name): command = "UPDATE student_info SET name='{}' WHERE stu_id='{}';".format(new_name, stu_id) with DBConnection() as connection: cursor = connection.cursor() cursor.execute(command) connection.commit()
3759b8b6d79be99ad7f3c65377f3424e3ba5d723
minjekang/Python_Study
/Python/Set.py
591
3.53125
4
# 집합 (set) # 중복 안됨, 순서 없음 my_set = {1,2,3,3,3} print(my_set) java = {"강민제", "나", "너"} python = set(["강민제", "유시온"]) # 교집합 (java와 python 모두 가능) print(java & python) print(java.intersection(python)) # 합집합 (java도 할 수 있거나 python 을 할수있는) print(java | python) print(java.union(python)) # 차집합 (java는 할 수 있거나 python 은 못하는) print(java - python) print(java.difference(python)) # python 추가 python.add("박명균") print(python) # java 삭제 java.remove("강민제") print(java)
d606dea2a9da437609814862b06990ff4aa5e293
minjekang/Python_Study
/Python/Practice.py
2,561
3.671875
4
# # 자료형 # print(5) # print(-10) # print(3.14) # print(1000) # print (5+3) # print(2*8) # print(3*(3+1)) # # 문자열 # print('풍선') # print("나비") # print("ㅋㅋㅋㅋㅋㅋ") # print("ㅋ"*9) # # 참 / 거짓 # print(5>10) # print(5<10) # print(True) # print(False) # print(not True) # print(not False) # print(not(5 > 10)) # # 변수 # # 애완동물 소개 # animal = "강아지" # name = "연탄이" # age = 4 # hobby = "산책" # is_abult = age >= 3 # print("우리집 강아지 이름은 연탄이") # print("연탄이는 4살, 산책을 좋아함.") # print("연탄이는 어른일까? True") # print("우리집 " + animal +" 이름은 "+name) # print(name+"는 "+str(age)+"살, "+hobby+"을 좋아함.") # print(name+"는 어른일까? "+str(is_abult)+"") # # '+' = ',' # # ',' 쓸때는 str 필요없음 # # ',' 쓰면 띄어쓰기 1칸 # # 연산자 # print(1+1) # print(3-2) # print(5*2) # print(10/2) # print(2**3) # print(5%3) # print(10%3) # print(5//3) # print(10//3) # print(10 > 3) #True # print(4 >= 7) #False # print(10 < 3) # print (5 <= 5) #True # print(3 == 3) # print(1 != 3) # print((3>0) and (3<5)) # print((3>0) & (3<5)) # print((3>0) or (3<5)) # print((3>0) | (3<5)) # print(2 + 3 * 4) # print((2+3)*4) # # 숫자 처리 함수 # print(abs(-5)) #절댓값 # print(pow(4,2)) #4^2 # print(max(5,12)) # print(min(5,12)) # print(round(3.14)) #반올림 # from math import * # print(floor(3.14)) #내림 3 # print(ceil(3.14)) #올림 4 # print(sqrt(16)) #제곱근 4 # #String # sentence = '나는 민제' # print(sentence) # sentence2 = "나는 민제" # print(sentence2) # sentence3 = """ # 나는 민제 # """ # print(sentence3) # #Slicing # j = "051023-3234567" # print("성별 : "+j[7]) # print("연 : "+j[0:2]) # 0~2번째 전까지 # print("월 : "+j[2:4]) # 2~4번째 전까지 # print("일 : "+j[4:6]) # 4~6번째 전까지 # print("생년월일 : "+j[:6]) #처음부터 6전까지 # print("뒤 7자리 : "+j[7:]) #7부터 끝까지 # print("뒤 7자리 : "+j[-7:]) #7부터 끝까지 # 표준 입출력 # import sys # print("Python", "Java", file=sys.stdout) # print("Python", "Java", file=sys.stderr) # 시험성적 # scores = {"수학":0,"영어":50,"코딩":100} # for sub,score in scores.items(): # #print(sub, score) # print(sub.ljust(8), str(score).rjust(4), sep=":") #은행 대기순번표 # 001, 002, 003, ... # for n in range(1, 21): # print("대기번호 : "+str(n).zfill(3)) #answer = input("아무거나 입력 : ") answer = 10 print(type(answer)) print(answer)
894abe59b869794b4a35903f04a750b1f9ee5788
brianbrake/Python
/ComputePay.py
834
4.3125
4
# Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay # Award time-and-a-half for the hourly rate for all hours worked above 40 hours # Put the logic to do the computation of time-and-a-half in a function called computepay() # Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75) def computepay (hrs,rate): try: hrs=float(raw_input("Enter Hours: ")) rate=float(raw_input("Enter Rate: ")) if hrs <= 40: gross = hrs * rate else: overtime = float (hrs-40) gross = (rate*40)+(overtime*1.5*rate) return gross except: print "Please type numerical data only. Restart & try again: " quit() print computepay('hrs', 'rate')
4d1563e0ddbaa33a256eccac986f55d6e8cf265c
Ryuodan/Network-Routering-Simulation
/main.py
1,036
3.59375
4
import pygame from program import Program WIDTH=1024 HEIGHT=768 GREY=(210, 210 ,210) FPS=60 BACKGROUND_COLOR=GREY #GREY TITLE='ROUTING NETWORK SOFTWARE' pygame.init() def main(): #window information font = pygame.font.Font(None, 32) pygame.display.set_caption(TITLE) screen = pygame.display.set_mode((WIDTH,HEIGHT)) done = False clock=pygame.time.Clock() #creating main sprites my_program=Program(screen=screen,bkcolor=GREY,font=font) #starting the game loop while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True my_program.update_event(event) # paint to screen # screen.fill(BACKGROUND_COLOR) my_program.update() pygame.display.flip() #set the FPS clock.tick(FPS) #routing if __name__ == "__main__": main()
3a3ee184db496396981388e6ca1c285d23c3a9b8
Bill-Fujimoto/Intro-to-Python-Course
/4.3.4 CodingExercise3.py
3,440
4.40625
4
#Last exercise, you wrote a function called #one_dimensional_booleans that performed some reasoning #over a one-dimensional list of boolean values. Now, #let's extend that. # #Imagine you have a two-dimensional list of booleans, #like this one: #[[True, True, True], [True, False, True], [False, False, False]] # #Notice the two sets of brackets: this is a list of lists. #We'll call the big list the superlist and each smaller #list a sublist. # #Write a function called two_dimensional_booleans that #does the same thing as one_dimensonal_booleans. It should #look at each sublist in the superlist, test it for the #given operator, and then return a list of the results. # #For example, if the list above was called a_superlist, #then we'd see these results: # # two_dimensional_booleans(a_superlist, True) -> [True, False, False] # two_dimensional_booleans(a_superlist, False) -> [True, True, False] # #When use_and is True, then only the first sublist gets #a value of True. When use_and is False, then the first #and second sublists get values of True in the final #list. # #Hint: This problem can be extremely difficult or #extremely simple. Try to use your answer or our #code from the sample answer in the previous problem -- #it can make your work a lot easier! You may even want #to use multiple functions. #Write your function here! def two_dimensional_booleans(super_list, use_and): results=[] for a_list in super_list: if not use_and: results.append(True in a_list) else: results.append(not False in a_list) return results #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: #[True, False, False] #[True, True, False] bool_superlist = [[True, True, True], [True, False, True], [False, False, False]] print(two_dimensional_booleans(bool_superlist, True)) print(two_dimensional_booleans(bool_superlist, False)) ################### def one_dimensional_booleans(bool_list, use_and): #There are a lot of different ways you could do this. #You could, for example, loop over each item in the #list and update a running result based on the new #value. # #Let's try it a simpler way, though. If use_and was #False, then our logic is pretty simple: we just #return whether 'True' is anywhere in the list: if not use_and: return True in bool_list #If use_and was True, our logic is just a little bit #more complicated. First, we want to find our whether #False is in the list. If it is, then we want to #return False; if it's not (meaning all the values #are True), then we want to return True. So, we want #to return the *opposite* of False in bool_list. We #can do that with the not operator: else: return not False in bool_list #Note that we could actually compress these four lines #down into only one, but it makes the logic a little #harder to follow: # #return (use_and and True in bool_list) or (not use_and and not False in bool_list) print(one_dimensional_booleans([True, True, True], True)) print(one_dimensional_booleans([True, False, True], True)) print(one_dimensional_booleans([True, False, True], False)) print(one_dimensional_booleans([False, False, False], False))
10bc6efce944ab2eb5480caa0f8a9c8f53041e5d
Bill-Fujimoto/Intro-to-Python-Course
/Coding Problem 4.5.6.py
3,342
4.28125
4
#This is a challenging one! The output will be very long as #you'll be working on some pretty big dictionaries. We don't #expect everyone to be able to do it, but it's a good chance #to test how far you've come! # #Write a function called stars that takes in two #dictionaries: # # - movies: a dictionary where the keys are movie titles and # the values are lists of major performers in the movie. For # example: movies["The Dark Knight"] = ["Christian Bale", # "Heath Ledger", "Maggie Gyllenhall", "Aaron Eckhart"] # - tvshows: a dictionary where the keys are TV show titles # and the values lists of major performers in the show. # For example: tvshows["Community"] = ["Joel McHale", "Alison # Brie", "Danny Pudi", "Donald Glover", "Yvette Brown"] # #The function stars should return a new dictionary. The keys #of the new dictionary should be the performers' names, and #the values for each key should be the list of shows and #movies in which that performer has appeared. Sort the shows #and movies alphabetically. #Write your function here! def stars(movies, tvshows): newdict={} for tupl in movies.items(): (movie_name, actor_list)=tupl for actor in actor_list: if actor not in newdict: newdict[actor]=[] newdict[actor].append(movie_name) for tupl in tvshows.items(): (tvshow_name, actor_list)=tupl for actor in actor_list: if actor not in newdict: newdict[actor]=[] newdict[actor].append(tvshow_name) for item in newdict: newdict[item].sort() return newdict #### My own different way by combining dictionaries#### #def stars(movies, tvshows): #newdict={} ##Combine both dictionaries into tvshows dictionary: #for key in movies: #if key not in tvshows: #tvshows[key]=movies[key] #for tupl in tvshows.items(): #(tvshow_name, actor_list)=tupl #for actor in actor_list: #if actor not in newdict: #newdict[actor]=[] #newdict[actor].append(tvshow_name) #for item in newdict: #newdict[item].sort() #return newdict ######################################################## #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print (although the order of the keys may vary): # #{'Portia de Rossi': ['Arrested Development'], 'Will Ferrell': ['The Lego Movie'], 'Yvette Brown': ['Community'], 'Rebel Wilson': ['How to Be Single'], 'Danny Pudi': ['Community'], 'Elizabeth Banks': ['30 Rock', 'The Lego Movie'], 'Alec Baldwin': ['30 Rock'], 'Alison Brie': ['Community', 'How to Be Single', 'The Lego Movie'], 'Tina Fey': ['30 Rock'], 'Dakota Johnson': ['How to Be Single'], 'Joel McHale': ['Community'], 'Jack McBrayer': ['30 Rock'], 'Tracy Morgan': ['30 Rock'], 'Donald Glover': ['Community'], 'Will Arnett': ['Arrested Development', 'The Lego Movie'], 'Jason Bateman': ['Arrested Development']} movies = {"How to Be Single": ["Alison Brie", "Dakota Johnson", "Rebel Wilson"], "The Lego Movie": ["Will Arnett", "Elizabeth Banks", "Alison Brie", "Will Ferrell"]} tvshows = {"Community": ["Alison Brie", "Joel McHale", "Danny Pudi", "Yvette Brown", "Donald Glover"], "30 Rock": ["Tina Fey", "Tracy Morgan", "Jack McBrayer", "Alec Baldwin", "Elizabeth Banks"], "Arrested Development": ["Jason Bateman", "Will Arnett", "Portia de Rossi"]} print(stars(movies, tvshows))
26a172a959b18ab2384ff72573c464652f6cfb26
Bill-Fujimoto/Intro-to-Python-Course
/5.2.3 Worked Example2_Fibonacci.py
3,668
4.5625
5
#Let's implement the Fibonacci function we saw in the #previous video in Python! # #Like our Factorial function, our Fibonacci function #should take as input one parameter, n, an integer. It #should calculate the nth Fibonacci number. For example, #fib(7) should give 13 since the 7th number in #Fibonacci's sequence is 13. #So, our function definition will basically be the same: def fib(n): #What do we want to do inside the function? Once again, #there are really only two cases: either we're looking #for the first two Fibonacci numbers, or we're not. #What happens if we're looking for the first two? Well, #we already know that the 1st and 2nd Fibonacci numbers #are both 1, so if n == 1 or n == 2, we can go ahead #and return 1. if n == 1 or n == 2: return 1 #What if n doesn't equal 1? For any value for n greater #than 2, the result should be the sum of the previous #two numbers. The previous Fibonacci number could then #be calculated with the same kind of function call, #decrementing n by 1 or 2. else: return fib(n - 1) + fib(n - 2) #If n is greater than 2, then it returns the sum of the #previous two fibonacci numbers, as calculated by the #same function. #Now let's test it out! Run this file to see the results. print("fib(5) is", fib(3)) print("fib(10) is", fib(10)) print() #Want to see more about how this works? Select the other #file, FibonacciwithPrints.py, from the drop-down in the #top left to see a version of this that traces the output. ############################################################### #As before, our core function below hasn't changed. What #has changed is that we've added print statements so we can #see a bit about how the program is running. def fib(n): if n == 1 or n == 2: print("Found fib(", n, "): returning 1!", sep = "") return 1 #As with the factorial function, we want to print every #time we're about to create a new call to Fibonacci, #and every time such a call is completed. else: print("Finding fib(", n, "): fib(", n - 1, ") + fib(", n-2, ")", sep = "") result = fib(n - 1) + fib(n - 2) print("Found fib(", n, "): ", result, sep = "") return result #Now if we run this, we'll see a lot more output. Feel free #to change this line to visualize different Fibonacci #numbers. print("fib(6) is", fib(6)) #The output here is more complex; you may want to copy it #into another window to read it. # #When fib(5) is first called, it wants to calculate fib(4) #and fib(3). So, it calls fib(4) first, which demands fib(3) #and fib(2). So, it calls fib(3), which demands fib(2) and #fib(1). Those are both the base case, so both return 1. #So, in the execution order, we see fib(5), then fib(4), #then fib(3), then fib(2), then fib(1). # #Once fib(2) and fib(1) have run, then fib(3) can finish, #and so the next statement printed is the result of fib(3). #Once fib(3) is finished, then we can finish fib(4) by #finding fib(2). fib(2) is again 1, so the next line is #fib(2). # #Once fib(3) and fib(2) have finished, we can finish #fib(4), so the next statement printed is the result of #fib(4). # #Now that fib(4) is finished, we're all the way back to the #first call, which wanted fib(4) + fib(3). Now, the rest of #the execution is evaluating fib(3), which immediately #demands fib(2) and fib(1). So, the next two lines are the #results of fib(2) and fib(1). Once those are done, fib(3) #is finished again. # #Now fib(4) and fib(3) are both finished, so the very first #line can end: fib(4) + fib(3) = 3 + 2 = 5.
22ceb4fdbf728776340db36a64e54be289bef089
Bill-Fujimoto/Intro-to-Python-Course
/Coding Problem 4.4.5.py
3,630
4.1875
4
#Write a function called get_grade that will read a #given .cs1301 file and return the student's grade. #To do this, we would recommend you first pass the #filename to your previously-written reader() function, #then use the list that it returns to do your #calculations. You may assume the file is well-formed. # #A student's grade should be 100 times the sum of each #individual assignment's grade divided by its total, #multiplied by its weight. So, if the .cs1301 just had #these two lines: # # 1 exam_1 80 100 0.6 # 2 exam_2 30 50 0.4 # #Then the result would be 72: # # (80 / 100) * 0.6 + (30 / 50) * 0.4 = 0.72 * 100 = 72 #Write your function here! def reader(filename): input_file=open(filename, "r") result=[] for line in input_file.readlines(): #"input_file.readlines()" is equivalent to simply "input_file"; #which returns a list of strings, one string for each line in the file. #print(line) list_of_fields = line.strip().split(" ") #int() and float() strip off line feed and spaces. No need for .strip() in line 5. number=int(list_of_fields[0]) assignment=str(list_of_fields[1]) score=int(list_of_fields[2]) total=int(list_of_fields[3]) weight=float(list_of_fields[4]) result.append((number,assignment,score,total,weight)) input_file.close() return result def get_grade(filename): list_of_scores = reader(filename) grade=0 for item in list_of_scores: score=item[2] total=item[3] weight=item[4] grade += (score/total)*weight*100 return grade #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: 91.55 print(get_grade("sample_1.cs1301")) ##### Solution ###### #As recommended, we're going to want to re-use our code from #4.4.3. So, here it is: def reader(filename): file_reader = open(filename) results = [] for line in file_reader: parts = line.split(" ") line_tuple = (int(parts[0]), parts[1], int(parts[2]), int(parts[3]), float(parts[4])) results.append(line_tuple) file_reader.close() return results #The benefit of this is that it takes care of all of our file- #handling for us! Now when we start to write our get_grade #function, we can just call reader() and then do all our #work on the list, which is easier to use: def get_grade(filename): #First, we call reader(), and save the result to a list #called gradebook_items: gradebook_items = reader(filename) #Next, the total grade is the sum of each individual grade #divided by its max and multiplied by its weight. So, we #first create our total_grade variable and set it to 0: total_grade = 0 #Now, we iterate through each gradebook item... for gradebook_item in gradebook_items: #To keep things easier to read, we'll first unpack #the tuple: number, name, grade, max_grade, weight = gradebook_item #Now, we'll add this grade's contribution to #total_grade: total_grade += (grade / max_grade) * weight #Then at the end, we'll return total_grade times 100: return total_grade * 100 #Note that none of the new code written here had anything #to do with files: once we loaded our data from a file, #we did all our work with the data stored in memory. print(get_grade("sample_1.cs1301"))
74c1a177115b9dd2e3b519e0581e1605814ef499
oschre7741/my-first-python-programs
/geometry.py
1,285
4.1875
4
# This program contains functions that evaluate formulas used in geometry. # # Olivia Schreiner # August 30, 2017 import math def triangle_area(b,h): a = (1/2) * b * h return a def circle_area(r): a = math.pi * r**2 return a def parallelogram_area(b,h): a = b * h return a def trapezoid_area(c,b,h): a = ((c + b) / 2) * h return a def rect_prism_volume(w,h,l): v = w * h * l return v def cone_volume(r,h): v = math.pi * r**2 * (h / 3) return v def sphere_volume(r): v = (4/3) * math.pi * r**3 return v def rect_prism_sa(w,h,l): a = 2 * (w * l + h * l + h * w) return a def sphere_sa(r): a = 4 * math.pi * r**2 return a def hypotenuse(w,x,y,z): d = math.sqrt(((y - w)**2) + ((z - x)**2)) return d def herons_formula(b,c,d): s = (b + c + d)/2 a = math.sqrt(s * (s - b) * (s - c) * (s- d)) return a #function calls print(triangle_area(4,9)) print(circle_area(5)) print(circle_area(12)) print(parallelogram_area(2,2)) print(trapezoid_area(1,2,3)) print(rect_prism_volume(1,2,3)) print(cone_volume(2,3)) print(sphere_volume(2)) print(rect_prism_sa(2,2,2)) print(sphere_sa(2)) print(hypotenuse(1,2,3,4)) print(herons_formula(3,5,7))
f58316ee96300c1b5e2dbd551a40c34131dac1de
PMardjonovic/InvoiceGUI
/views/calendar_view/main_header.py
1,020
3.640625
4
import tkinter as tk import calendar as cl class MainHeader(tk.Frame): def __init__(self, parent, controller, month, year, *args, **kwargs): # Call parent init tk.Frame.__init__(self, parent, *args, **kwargs) # Header displays month,year being currently displayed header_font = ("Helvetica", 20, "bold") self.header_lbl = tk.Label( self, text=f"{cl.month_name[month]}, {year}", font=header_font, width=100) self.header_lbl.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) # Displays previous month self.prev_month_btn = tk.Button( self, text="<", width=5) self.prev_month_btn.pack(side=tk.LEFT, fill=tk.BOTH) self.prev_month_btn.bind("<Button-1>", controller.prev_month) # Displays next month self.next_month_btn = tk.Button( self, text=">", width=5) self.next_month_btn.pack(side=tk.LEFT, fill=tk.BOTH) self.next_month_btn.bind("<Button-1>", controller.next_month)
153fbbfa4fd67c9cf4da273780fdd730aa6dd2d9
xystar2012/vsCodes
/PyCodes/PyQt5/basicdataType/queueOp.py
1,493
3.765625
4
#--*-- coding:utf-8 --*-- from random import randint from time import ctime from time import sleep import queue import threading class MyTask(object): def __init__(self, name): self.name = name self._work_time = randint(1, 5) def work(self): print("Task %s is start : %s, sleep time= %d" % (self.name, ctime(), self._work_time)) sleep(self._work_time) print("Task %s is end : %s" % (self.name, ctime())) class MyThread(threading.Thread): def __init__(self, my_queue): self.my_queue = my_queue super(MyThread, self).__init__() def run(self): while True: if self.my_queue.qsize() > 0: self.my_queue.get().work() else: break def print_split_line(num=30): print("*" * num) if __name__ == "__main__": print_split_line() queue_length = 6 my__queue = queue.LifoQueue(queue_length * 3) threads = [] print('Before:',my__queue.qsize()) for i in range(queue_length * 3): mt = MyTask("tk_" + str(i)) my__queue.put_nowait(mt) print('After:',my__queue.qsize()) for i in range(queue_length): mtd = MyThread(my__queue) threads.append(mtd) for i in range(queue_length): threads[i].start() for i in range(queue_length): threads[i].join() print_split_line()
cf918de06e0226a8d1d63f2ed10843aa572be889
xircon/Scripts-dots
/appjar/turt.py
310
3.625
4
# get the library import turtle import os wind = turtle.Screen() t = turtle.Turtle() # draw a square for loop in range(4): t.forward(100) t.right(90) t.home() yy = 10 for loop in range(100): t.dot ( yy,"cyan") yy=yy+5 t.home() t.write("Finished - click window to close") wind.exitonclick ( )
21302bc9e0310c4ea221a03de8847cd285f4d532
Adrian-Bravo/TallerBD
/Clase02/ejercicio3.py
250
3.5625
4
from library.modulos import num_perfecto def principal(): numero = int(input("Digite un numero: ")) if num_perfecto(numero): print("Es perfecto") else: print("No es perfecto") if __name__ == "__main__": principal()
6168ffa995d236e3882954d9057582a5c130763a
ghinks/epl-py-data-wrangler
/src/parsers/reader/reader.py
2,129
4.15625
4
import re import datetime class Reader: fileName = "" def __init__(self, fileName): self.fileName = fileName def convertTeamName(self, name): """convert string to upper case and strip spaces Take the given team name remove whitespace and convert to uppercase """ try: upper = name.upper() converted = re.sub(r"\s+", "", upper) return converted except Exception as e: print(f"an exception when trying to convert ${name} to upper case has taken place ${e}") raise def convertStrDate(self, strDate): """given dd/mm/yyyy or yyyy-mm-dd create a python Date Take the string format of 'dd/mm/yyyy' or 'yyyyy-mm-dd' and convert that into a form that may be used to create a python date """ if not isinstance(strDate, str): return strDate try: compiled = re.compile(r"(\d\d)\/(\d\d)\/(\d{2,4})") match = compiled.match(strDate) if match: day = match.groups()[0] month = match.groups()[1] year = match.groups()[2] # there are two types of year format that can be given # the first is a 2 digit year. If this year is > 80 # then it was before year 2000 # if it is < 80 it is after year 2000 if len(year) == 2 and 80 < (int(year)) < 100: year = (int(year)) + 1900 elif len(year) == 2 and (int(year)) < 80: year = 2000 + int(year) return datetime.date(int(year), int(month), int(day)) compiled = re.compile(r"(\d\d\d\d)\-(\d\d)\-(\d\d)(.*)") match = compiled.match(strDate) year = match.groups()[0] month = match.groups()[1] day = match.groups()[2] return datetime.date(int(year), int(month), int(day)) except (ValueError, AttributeError, TypeError): print("error handling date ", strDate) raise
f58c6f1c77b620906ebf67b72ca4c0e51139c689
jeffreymoon/MLearning
/PolynomialRegression.py
1,293
3.546875
4
# %% import numpy as np import matplotlib.pyplot as plt m = 100 X = 6 * np.random.rand(m, 1) - 3 y = 2 + X + 0.5 * X**2 + np.random.randn(m, 1) plt.plot(X, y, 'r.') plt.show() # %% from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression poly_features = PolynomialFeatures(degree=2, include_bias=False) X_poly = poly_features.fit_transform(X) lin_reg = LinearRegression() lin_reg.fit(X_poly, y) print(lin_reg.intercept_, lin_reg.coef_) # %% from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split def plot_learning_curves(model, X, y): X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2) train_errors, val_errors = [], [] for m in range(1, len(X_train)): model.fit(X_train[:m], y_train[:m]) y_train_predict = model.predict(X_train[:m]) y_val_predict = model.predict(X_val) train_errors.append(mean_squared_error(y_train[:m], y_train_predict)) val_errors.append(mean_squared_error(y_val, y_val_predict)) plt.plot(np.sqrt(train_errors), "r-+", linewidth=2, label="Train set") plt.plot(np.sqrt(val_errors), "b-", linewidth=3, label="Validation set") # %% lin_reg = LinearRegression() plot_learning_curves(lin_reg, X, y)
a3f22bb6a8225ca7ad16589b0fe0a01d37c8d616
sh92/Online-Judge-Code
/leetcode/L874.py
3,271
4.0625
4
class MyCircularQueue: def __init__(self, k): """ Initialize your data structure here. Set the size of the queue to be k. :type k: int """ self.mylist = [0 for i in range(k)] self.maxSize = k self.size = 0 self.front = 0 self.rear = 0 def enQueue(self, value): """ Insert an element into the circular queue. Return true if the operation is successful. :type value: int :rtype: bool """ if self.isFull(): return False self.mylist[self.rear] = value self.size = self.size + 1 self.rear = (self.rear + 1) % (self.maxSize) return True def deQueue(self): """ Delete an element from the circular queue. Return true if the operation is successful. :rtype: bool """ if self.isEmpty(): return False self.front = (self.front + 1) % self.maxSize self.size -= 1 return True def Front(self): """ Get the front item from the queue. :rtype: int """ if self.isEmpty(): return -1 return self.mylist[self.front] def Rear(self): """ Get the last item from the queue. :rtype: int """ if self.isEmpty(): return -1 return self.mylist[self.rear-1] def isEmpty(self): """ Checks whether the circular queue is empty or not. :rtype: bool """ return (self.size == 0) def isFull(self): """ Checks whether the circular queue is full or not. :rtype: bool """ return (self.size == self.maxSize) def excute_code( obj, methods, params): for idx in range(0,len(methods)): print(locals()[methods[idx]](params[idx][0])) # Your MyCircularQueue object will be instantiated and called as such method = ["enQueue", "Rear","Front","deQueue","Front","deQueue","Front","enQueue","enQueue","enQueue","enQueue"] param = [[2],[],[],[],[],[],[],[4],[2],[2],[3]] obj = MyCircularQueue(3) print("rear",obj.Rear()) print("enque ",obj.enQueue(1)) print("rear",obj.Rear()) print("enque ",obj.enQueue(2)) print("rear",obj.Rear()) print("enque ",obj.enQueue(3)) print("rear",obj.Rear()) print("enque ",obj.enQueue(4)) print("rear",obj.Rear()) print("isFull",obj.isFull()) print("rear",obj.Rear()) print("deQueue",obj.deQueue()) print("rear",obj.Rear()) print("enQueue",obj.enQueue(4)) print("rear",obj.Rear()) ''' k = 3 obj = MyCircularQueue(k) print("enque ",obj.enQueue(1)) print("enque 2 ",obj.enQueue(2)) print("enque 3 ",obj.enQueue(3)) print("enque 4 ",obj.enQueue(4)) print("deque ",obj.deQueue()) print("enque 5 ",obj.enQueue(5)) print("Front : ", obj.Front()) print("Rear : ",obj.Rear()) print("enque 6 ",obj.enQueue(6)) print("Empty : ",obj.isEmpty()) print("Full : " , obj.isFull()) print("deque ",obj.deQueue()) print("Empty : ",obj.isEmpty()) print("Full : " , obj.isFull()) print("deque ",obj.deQueue()) print("Empty : ",obj.isEmpty()) print("Full : " , obj.isFull()) print("deque ",obj.deQueue()) print("Empty : ",obj.isEmpty()) print("Full : " , obj.isFull()) '''
1e5c8ec60b8902f8d0769d91a11ce208bdf1f447
EaglesRoboticsTeam/ReceitaV1
/touch.py
2,271
3.5
4
import time # import the time library for the sleep function import brickpi3 # import the BrickPi3 drivers BP = brickpi3.BrickPi3() # Create an instance of the BrickPi3 class. BP will be the BrickPi3 object. BP.set_sensor_type(BP.PORT_1, BP.SENSOR_TYPE.TOUCH) # Configure for a touch sensor. If an EV3 touch sensor is connected, it will be configured for EV3 touch, otherwise it'll configured for NXT touch. try: print("Press touch sensor on port 1 to run motors") value = 0 while not value: try: value = BP.get_sensor(BP.PORT_1) except brickpi3.SensorError: pass speed = 0 adder = 1 while True: # BP.get_sensor retrieves a sensor value. # BP.PORT_1 specifies that we are looking for the value of sensor port 1. # BP.get_sensor returns the sensor value. try: value = BP.get_sensor(BP.PORT_1) except brickpi3.SensorError as error: print(error) value = 0 if value: # if the touch sensor is pressed if speed <= -100 or speed >= 100: # if speed reached 100, start ramping down. If speed reached -100, start ramping up. adder = -adder speed += adder else: # else the touch sensor is not pressed or not configured, so set the speed to 0 speed = 0 adder = 1 # Set the motor speed for all four motors BP.set_motor_power(BP.PORT_A + BP.PORT_B + BP.PORT_C + BP.PORT_D, speed) try: # Each of the following BP.get_motor_encoder functions returns the encoder value (what we want to display). print("Encoder A: %6d B: %6d C: %6d D: %6d" % (BP.get_motor_encoder(BP.PORT_A), BP.get_motor_encoder(BP.PORT_B), BP.get_motor_encoder(BP.PORT_C), BP.get_motor_encoder(BP.PORT_D))) except IOError as error: print(error) time.sleep(0.02) # delay for 0.02 seconds (20ms) to reduce the Raspberry Pi CPU load. except KeyboardInterrupt: # except the program gets interrupted by Ctrl+C on the keyboard. BP.reset_all() # Unconfigure the sensors, disable the motors, and restore t
2062c1161c2a14fcb99176f6d701f698d7940a5f
cheriezhang/LCode
/TowardOffer/22-verifySquenceOfBST.py
1,577
3.59375
4
# -*- coding:utf-8 -*- # 题目描述 # 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。 # 如果是则输出Yes,否则输出No。 # 假设输入的数组的任意两个数字都互不相同。 # 后序遍历: 左右根? # 二叉搜索树: 空树或者 # 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; # 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; # 测试用例: 5,7,6,9,10,11,8 # 最后一个是根节点 比根节点大的是右子树,比根节点小的是左子树 def VerifySquenceOfBST(sequence): if len(sequence) == 0: return False if len(sequence) == 1: return True i = 0 while sequence[i] < sequence[-1]: # 看在哪里分界的,找到第一个大于根节点的值 i = i + 1 k = i # 保存分界值 for j in range(i, len(sequence) - 1): # 不包括根节点的节点和根节点比较 if sequence[j] < sequence[-1]: # 右子树中有小于根节点的值 return False left_tree = sequence[:k] # 能够保证都小于根节点 right_tree = sequence[k:len(sequence) - 1] # 没有return False 能够保证都大于根节点 left = True right = True if len(left_tree) > 0: left = VerifySquenceOfBST(left_tree) if len(right_tree) > 0: right = VerifySquenceOfBST(right_tree) return left and right sequence = [4, 6, 7, 5] print VerifySquenceOfBST(sequence) # 运行时间:45ms # 占用内存:5888k
c6b5a92838a6826922be0740bdc360b0792d9c04
cheriezhang/LCode
/TowardOffer/24-Clone.py
2,250
3.671875
4
# -*- coding:utf-8 -*- # 题目描述 # 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点, # 另一个特殊指针指向任意一个节点), # 返回结果为复制后复杂链表的head。 # (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # 返回 RandomListNode def Clone(self, pHead): self.cloneNodes(pHead) self.connectRandomNodes(pHead) self.reConnectNodes(pHead) def cloneNodes(self,pHead): # 将每一个节点都复制一个变成A->A'->B->B'..... pNode = pHead while pNode is not None: pClone = RandomListNode(pNode.label) # A复制到A' 除了random pClone.next = pNode.next # 把A'指向B pNode.next = pClone # 把A和A'链接起来 pNode = pClone.next # 重新指定pHead->B def connectRandomNodes(self,pHead): pNode = pHead while pNode is not None : # A,B,C.... pClone = pNode.next # A',B',C'.... if pNode.random is not None: # 如果A有random,将其复制到A' pClone.random = pNode.random.next pNode = pClone.next def reConnectNodes(self,pHead): pNode = pHead pCloneHead = None pCloneNode = None if pNode != None: # 如果有原头结点 A pCloneHead = pCloneNode = pNode.next # 设置新的克隆头结点和中间节点,初始化新的链表 A' pNode.next = pCloneNode.next # 将A指向B A->next = A'->next pNode = pNode.next # 新的pNode为B pNode = A->next = B while pNode != None: # 从B开始循环 pCloneNode.next = pNode.next # 将A'指向B' pCloneNode = pCloneNode.next # 新的pCloneNode为B' pNode.next = pCloneNode.next # B->next = B'->next = C pNode = pNode.next # pNode = C return pCloneHead # 运行时间:28ms # 占用内存:5760k
d9a7aa1391d393fa00c33b1c3dc1ceb19a97d5bb
rokitka007/PytPoz03-doUsuniecia
/obiektowosc/Car.py
976
3.78125
4
class Car(): def __init__(self, brand, model, year=2000): self.brand = brand self.model = model self.year = year self.velocity = 0 def presentCar(self): message = "{} {} created in {}".format(self.brand, self.model, self.year) if 2019-self.year >= 20: message += "\nWaiting for destruction" print(message) return message def accelerate(self, velocity): self.velocity += velocity def brake(self, velocity): if self.velocity == 0: print("You're not already driving") elif self.velocity - velocity < 0: self.velocity = 0 else: self.velocity -= velocity #Wbudowane funkcje zawsze sa otoczone dwoma podkreslnikami # Mozna je nadpisywac - przyklad ponizej # Sluza one do interpretowania przez funkcje wbudowane w pythona, takie jak str(), sorted() def __str__(self): return self.presentCar()
9347651ce97a9a8deebf1d438ff7a753774fbeb9
4nu81/examen
/Quellcode/Log.py~
1,078
3.609375
4
class Log: """ logt die einzelnen Simulationsschritte in LogSpiel """ def __init__(self): """ Constructor """ self.LogSpiel = [] def LogZug(self, spieler, before, after): """ logt sich einen Spielzug. Die Anzahl der Spielzüge ist gleich der Anzahl an Logeinträgen. Daher reichen die Informationen Spieler, before und after aus. Aus denen wird eine Logzeile zusammengesetzt und gespeichert. """ msg = "Zug%s , %s : %s -> %s" % (str( len(self.LogSpiel) + 1 ), spieler.name, str(before), str(after), ) # Collections in Strings umgewandelt, enthalten eckige Klammern. # In der Beispielausgabe wurden runde Klammern verwendet, # weshalb ich diese hier ersetze. msg = msg.replace("[", "(").replace("]", ")") self.LogSpiel.append(msg)
64029fb960b2cf5985cf2c2a8d7cc7fdd48a0f3c
biam05/FPRO_MIEIC
/pe's/pe1-2/question5.py
223
3.8125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 3 22:23:25 2019 @author: biam05 """ dec = int(input('Decimal number (base 10):')) final = '' while dec > 0: final += str(dec % 2) dec = dec // 2 print(final[::-1])
d5748848d4bba68f90e4fe2e78eeb8b1e7ca9651
biam05/FPRO_MIEIC
/exercicios/RE04 Conditionals and Iteration/triangle(2).py
525
3.75
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 26 14:42:58 2018 @author: biam05 """ n1 = int(input("Size 1: ")) n2 = int(input("Size 2: ")) n3 = int(input("Size 3: ")) if n1 <= (n2 + n3) or n2 <= (n1 + n3) or n3 <= (n1 + n2) or n1 < 0 or n2 < 0 or n3 < 0: result = str("Not a triangle") else: if n1 == n2 and n2 == n3: result = str("Equilateral") else: if n1 == n2 or n2 == n3 or n1 == n3: result = str("Isosceles") else: result = str("Scalene") print(result)
ce8eafa856f062c4a15f773cd07cd837eaf4a177
biam05/FPRO_MIEIC
/pe's/pe1-1/question4.py
474
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 3 21:46:03 2019 @author: biam05 """ tS = float(input('Swimming time:')) tC = float(input('Cycling time:')) tR = float(input('Running time:')) if tS + tC + tR >= 4: print('Time') else: if 1.5 / tS < 2: print('Swimming') else: if 40/tC < 20: print('Cycling') else: if 10/tR < 8: print('Running') else: print(tS + tC + tR)
d8d328d0cc735abb7671d74ea4440e4467646b55
biam05/FPRO_MIEIC
/exercicios/RE12/parse.py
442
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 23 16:26:15 2018 @author: biam05 """ def parse(filename): from ast import literal_eval as l_eval file = open(filename, 'r') content = file.read() content = content.split() contstr = '' for i in range(len(content)): if content[i][0] != '(': content[i] += ',' for i in range(len(content)): contstr += content[i] return l_eval(contstr)
8f178542befde45bd673362d8dc469a19016bd18
biam05/FPRO_MIEIC
/exercicios/RE04 Conditionals and Iteration/triangle.py
1,203
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 17 21:46:12 2018 @author: biam05 """ # # DESCRIPTION of exercise 4: # # Write a program that checks if a triangle is equilateral, isosceles or scalene, # with the 3 sides provided by the user, each one in different an input() statement. # See Google Docs for implementation details. # # Do NOT alter the function prototype given # # PASTE your code inside the function block below, paying atention to the right indentation # # Don't forget that your program should use the return keyword in the last instruction # to return the appropriate value def triangle_form(): result = "Not yet implemented" #### MY CODE STARTS HERE ############################ x = int(input(" ")) y = int(input(" ")) z = int(input(" ")) if ((x + y) <= z) or ((x + z) <= y) or ((y + z) <= x): result = "Not a triangle" else: if (x == y) and (y == z): result = "Equilateral" else: if (x == z) or (y == z) or (x == y): result = "Isosceles" else: result = "Scalene" #### MY CODE ENDS HERE ############################## return result
ce63daf21fdbd6dff7784d83eb6ccfc3b3d54d32
biam05/FPRO_MIEIC
/exercicios/RE02 Simple data/cast.py
235
3.734375
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 25 17:12:31 2018 @author: biam05 """ n = int(input("n = ")) nn = str(n) + str(n) nnn = str(n) + str(n) + str(n) expression = n + int(nn) + int(nnn) print("n + nn + nnn =", expression)
3e0567d81aa20bf04a43d2959ae3fff8b71501ec
biam05/FPRO_MIEIC
/exercicios/RE05 Functions/sumNumbers.py
955
4.34375
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 24 11:47:09 2018 @author: biam05 """ # # DESCRIPTION of exercise 2: # # Write a Python function sum_numbers(n) that returns the sum of all positive # integers up to and including n. # # For example: sum_numbers(10) returns the value 55 (1+2+3+. . . +10) # # Do NOT alter the function prototype given # # PASTE your code inside the function block below, paying atention to the right indentation # # Don't forget that your program should use the return keyword in the last instruction # to return the appropriate value # def sum_numbers(n): """ returns the sum of all positive integers up to and including n """ #### MY CODE STARTS HERE ###################################### if n >= 0: result = n for i in range(n): result += i else: result = 0 return result #### MY CODE ENDS HERE ########################################
efec0a1054842d2fc586b9d5606784ad1009327b
biam05/FPRO_MIEIC
/exercicios/RE11/override.py
474
3.8125
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 11 10:44:03 2018 @author: biam05 """ def override(l1, l2): # new_list = [] # first_l2 = [l2[k][0] for k in range(len(l2))] # for i in range(len(l1)): # if l1[i][0] not in first_l2: # new_list.append(l1[i]) # return sorted(l2 + new_list, key = lambda x: x[0]) return sorted(l2 + [l1[i] for i in range(len(l1)) if l1[i][0] not in [l2[k][0] for k in range(len(l2))]], key = lambda x: x[0])
47f6f18ce5244de5980f05a07aaddfe28ef2e020
biam05/FPRO_MIEIC
/pe's/pe1-1/question5.py
233
3.8125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 3 21:52:38 2019 @author: biam05 """ dec = int(input('Decimal number (base 10):')) result = '' while dec > 0: result += str(dec%8) dec = dec//8 print(result[::-1])
5e0efb6d9833e39945641587a362f1a25a880b1b
biam05/FPRO_MIEIC
/exercicios/RE04 Conditionals and Iteration/concatenate(2).py
415
3.53125
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 26 14:52:15 2018 @author: biam05 """ n1 = int(input("Number 1: ")) n2 = int(input("Number 2: ")) x = n1 y = n2 i = 0 result = 0 while y > 0: y = y % 10 result += (y*(10**(i))) y = n2 - result y = y / (10**(i)) i += 1 while x > 0: x = x % 10 result += (x*(10**(i))) x = (n1*(10**i)) - result x = x / (10**i) i += 1 print(result)
879343e31343bffa2623c9b72008dfcec0cedbcf
biam05/FPRO_MIEIC
/exercicios/RE04 Conditionals and Iteration/prime(2).py
309
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 26 08:35:26 2018 @author: biam05 """ n = int(input("Integer: ")) divisor_list = [] for i in range (1, n+1): if (n % i) == 0: divisor_list.append(i) if len(divisor_list) == 2: result = True else: result = False print(result)
e5bd2a104b7653dfdbdbea151f76197a2c191919
biam05/FPRO_MIEIC
/pe's/pe3/evaluate.py
155
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 4 14:35:30 2019 @author: biam05 """ def evaluate(a, x): return sum(ai*x**e for e, ai in enumerate(a))
7e500b566439384504736f7ea2b7193119ac8080
mewhite/SwingCopters
/player.py
1,329
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 01 18:04:22 2015 @author: Nolan """ import pygame from pygame import transform import math class Player: height = 80 width = 80 image = transform.scale(pygame.image.load("orange_square.png"), (width, height)) def __init__(self, starting_position, acceleration, velocity): self.x = starting_position[0] self.y = starting_position[1] self.acceleration = acceleration self.velocity = velocity self.image = Player.image self.player_rect = self.image.get_rect(center=starting_position) def update_position(self): self.velocity += self.acceleration # self.x += math.floor(self.velocity) speed = [self.velocity, 0] self.player_rect = self.player_rect.move(speed) self.x = self.player_rect.x def set_acceleration(self, acceleration): self.acceleration = acceleration def change_acceleration(self): self.acceleration = -self.acceleration def draw_player(self, surface): surface.blit(self.image, self.player_rect) def print_info(self): print "Position: " + str(self.x) + "," + str(self.y) + " Velocity: " + str(self.velocity) + " Acceleration: " + str(self.acceleration)
bc6927f7570592cb9fa8313ab91bf9381d7b49f1
Gavinee/Leetcode
/055 跳跃游戏.py
938
4
4
""" 给定一个非负整数数组,你最初位于数组的第一个位置。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个位置。 示例 1: 输入: [2,3,1,1,4] 输出: true 解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。 示例 2: 输入: [3,2,1,0,4] 输出: false 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。 """ __author__ = 'Qiufeng' class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ position = 0 for i in range(len(nums)): if i >position: return False position = max(position,i+nums[i]) if(position >= len(nums)): return True return True
6e01d7745ab0f7d407b8716aed703579878abdcf
Gavinee/Leetcode
/006 Z字形变换.py
3,195
3.890625
4
""" 将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数: P A H N A P L S I I G Y I R 之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR" 实现一个将字符串进行指定行数变换的函数: string convert(string s, int numRows); 示例 1: 输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR" 示例 2: 输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I """ __author__ = 'Qiufeng' """ 方法一: 找z子形与横行读取之间的映射关系,通过list存储之间的映射关系 此方法可行,但在拼接成字符串时,无法删除已经使用的元素,造成 程序在运行时可能会超时。 """ class Solution: def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ tt = "" Col = [] if len(s)<=numRows: return s if numRows <2: return s for i in range(0,len(s),1): position = numRows - 1 row = i//position#列 temp = i%(2*position) col = position - abs(temp-position) #行 Col.append(col) position = 0 k = 0 for j in range(0,numRows,1): p = 0 for p in range(0,len(Col),1): if Col[p] == k: tt+=s[p] p+=1 k+=1 j+=1 return tt """ j = 0 k = 0 while j < numRows: p = 0 while p<len(Col): if Col[p] == k: tt+=s[p] p+=1 if p == len(Col): k+=1 j+=1 return tt """ """ 方法二: 通过对方法一的优化,利用dict来储存二者之间的映射关系。 并在遍历dict时,可以删除已经使用的元素,使程序效率大大 增加,方法一运行时间是1740ms,而方法而运行时间缩短到 1170ms. Python -- 遍历字典时删除元素技巧 d = {'a':1, 'b':0, 'c':1, 'd':0} keys = list(d.keys()) for key in keys: del(d[key]) """ class Solution: def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ tt = "" #Col = [] dict1 = {} if len(s)<=numRows: return s if numRows <2: return s for i in range(0,len(s),1): position = numRows - 1 row = i//position#列 temp = i%(2*position) col = position - abs(temp-position) #行 dict1[i] = col #Col.append(col) position = 0 k = 0 for j in range(0,numRows,1): keys = list(dict1.keys()) for key in keys: if dict1[key] == k: tt+=s[key] del(dict1[key]) k+=1 j+=1 return tt
8a89be31e992269795d379cf5fff80c55b2ff78e
Gavinee/Leetcode
/070 爬楼梯.py
1,754
3.875
4
""" 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数。 示例 1: 输入: 2 输出: 2 解释: 有两种方法可以爬到楼顶。 1. 1 阶 + 1 阶 2. 2 阶 示例 2: 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶 """ __author__ = 'Qiufeng' # 超时程序(递归形式) class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ count = [0] #有count[0]种方案 step = 0 #记录已经走完的步数 self.dynamicProgramming(count,n,step) return count[0] def dynamicProgramming(self,count,n,step): if step == n: count[0] +=1 return if step<n: step+=1 self.dynamicProgramming(count,n,step) step-=1 if step<=n-2: step+=2 self.dynamicProgramming(count,n,step) step-=2 # 通过的程序 class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ dp = [] for i in range(0,n+1,1): dp.append(0) dp[1] = 1 if n ==1: return dp[1] dp[2] = 2 if n==2: return dp[2] for i in range(3,n+1,1): dp[i] = dp[i-1]+dp[i-2] return dp[n]
ad3bea526fb841fdbbaa4dc1d541f38fc85fad22
Gavinee/Leetcode
/617 合并二叉树.py
1,396
3.984375
4
""" 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。 示例 1: 输入: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 输出: 合并后的树: 3 / \ 4 5 / \ \ 5 4 7 注意: 合并必须从两个树的根节点开始。 """ __author__ = 'Qiufeng' class Solution: def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if t1 == None and t2 == None: return elif t1 == None: return t2 elif t2 == None: return t1 else: t1.val +=t2.val t1.left = self.mergeTrees(t1.left,t2.left) t1.right = self.mergeTrees(t1.right,t2.right) return t1
73219c63946768b4458c9c4c9f30639a83829d19
AndyLaneOlson/LearnPython
/Ch3TurtleShapes.py
863
4.28125
4
import turtle #Set up my turtle and screen wn = turtle.Screen() myTurtle = turtle.Turtle() myTurtle.shape("turtle") myTurtle.speed(1) myTurtle.pensize(8) myTurtle.color("blue") myTurtle.penup() myTurtle.backward(400) myTurtle.pendown() #Make the turtle do a triangle for i in range(3): myTurtle.forward(100) myTurtle.left(120) #Move the turtle to a new spot myTurtle.penup() myTurtle.forward(200) myTurtle.pendown() #Make the turtle create a square for i in range(4): myTurtle.forward(100) myTurtle.left(90) myTurtle.penup() myTurtle.forward(200) myTurtle.pendown() #Make the turtle create a hexagon for i in range(6): myTurtle.forward(60) myTurtle.left(60) myTurtle.penup() myTurtle.forward(200) myTurtle.pendown() #Make the turtle create an octagon for i in range(8): myTurtle.forward(50) myTurtle.left(45) wn.mainloop()
1064355cabd4ecae5a0dcc2bef35f13179a16f56
pallavasija/inboxspammer
/inboxspammer.py
901
3.59375
4
#InboxSpammer (Python) #Importing SMTP library import time import smtplib #Specifying the From and To addresses toadd = raw_input("Enter email address of the recipient [to]: ") #Login credentials uname = raw_input ('Enter your GMAIL username: ') pwd = raw_input ('Enter your GMAIL password: ') #Asking the user for the contents of the email(s) message = raw_input ('Enter the message you want to send [body]: ') #Connecting to GMAIL print "Running for the first time? Check your email. Make sure to enable authentication for less secure apps" time.sleep(3) server =smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(uname,pwd) #Specifying number of emails num = int(raw_input("Enter the number of emails you want to send to the target: ")) for num in range (0,num): server.sendmail(uname,toadd,message) print "mail %d sent" %(num+1) #closing the connection server.quit()
c0994074084e337bba081ca44c37d2d4d8553f8f
xtom0369/python-learning
/task/Learn Python The Hard Way/task33/ex33_py3.py
368
4.15625
4
space_number = int(input("Input a space number : ")) max_number = int(input("Input a max number : ")) i = 0 numbers = [] while i < max_number: print(f"At the top i is {i}") numbers.append(i) i = i + space_number print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num)
e8551cb6543a8640c548e40d1206dd987c7635ad
ashutoshpandey1710/PythonFun
/deepestodd.py
563
3.609375
4
from tree import readTreeFromFile def deepestOdd(tree, level=1): if (not tree[1]) and (not tree[2]): if level % 2 == 1: return level, tree[0] else: return -1, None leftmax, leftnode = -1, None if tree[1]: leftmax, leftnode = deepestOdd(tree[1], level + 1) rightmax, rightnode = -1, None if tree[2]: rightmax, rightnode = deepestOdd(tree[2], level + 1) if leftmax >= rightmax: return leftmax, leftnode else: return rightmax, rightnode if __name__ == '__main__': tree = readTreeFromFile('unbalanced.txt') print deepestOdd(tree)