blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ab98e0e4d90fbceb5658021fc1d8057789b738ba
emilianoNM/Tecnicas3
/Reposiciones/reposicionesIsraelFP/reposicion7Ago18IsraelFP/tresEnterosIsraelFP.py
537
3.734375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Sep 14 22:04:29 2018 @author: israel """ data=[] def operaciones(data): #suma=0 #for i in range(0,len(data)): suma=suma+data[i] print "\nSuma: ",sum(data) print "Promedio: ", sum(data) / float(len(data)) print "Producto: ", reduce((lambda x, y: x*y),data) print "Menor valor: ",min(data) print "Mayor valor: ",max(data) for i in range(1,4): print("Dame el valor {}: ".format(i)) tmp = input() data.append(tmp) operaciones(data)
8ec249e715d5a21e500a9372aec0cc11f7ab26f6
westgate458/LeetCode
/P0347.py
579
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 30 17:59:24 2019 @author: Tianqi Guo """ from collections import defaultdict class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ # dictionary for the occurances of each number d = defaultdict(int) # update dictionary for each number for num in nums: d[num] += 1 # return the top k keys based on their values return sorted(d, key=d.get, reverse=True)[:k]
4ebc1fd17998a8e082ea94f1ad8b79ef47a36324
emaxwell711/mdn-project
/utilities/SplitBits.py
354
3.71875
4
def SplitBits(bits): if len(bits) == 32: five = bits[:5] four = bits[5:9] rest = bits[9:] return five , four , rest else: raise ValueError('length of bits must be 32 characters') sample = '01010101010010101010101011010101' five , four , rest = SplitBits(sample) print(five , four, rest)
0daa43bc84580d93dc7d332c13fa2b77bda32318
jayshreevashistha/forskml
/Coding Challenge/Day_3/generator.py
584
4.3125
4
# -*- coding: utf-8 -*- """ Created on Thu May 9 10:19:30 2019 @author: computer """ sample=input("Enter the numbers").split(",") print("list:",list(sample)) print("tuple:",tuple(sample)) """""""""""""""""""""""""""""""""""""""""""""""" # Enter comma separated numbers user_list = input("Enter comma seperated numbers :").split(",") new_list = [] for i in user_list: new_list.append(int(i)) # list to tuple conversion user_tuple = tuple(user_list) print ("List : "+str(user_list)) print ("Tuple : "+str(user_tuple)) """"""""""""""""""""""""""""""""""""""""""""""""""
0a479aeb4b613a6241f7c82124dd7e946f84b8be
wagnerwar/4linux-lessons
/animais.py
355
3.71875
4
# !/usr/bin/python animais = ["gato","cachorro", "passarinho"] print(animais) animais.append("boi") print(animais) animais.insert(2,"lagarto") print(animais) animais.remove("gato") print(animais) animais.pop() print(animais) animais.pop(1) print(animais) print(animais.count("ppp")) print(animais.index("passarinho")) animais.reverse() print(animais)
736447ca94854b573fc7ea9573d8677ca3f9697f
QiTai/python
/processManage/fig18_10.py
1,184
3.515625
4
#using os.pipe to communicate with a child process import os import sys #open parent and child read/write pipes fromParent, toChild = os.pipe() fromChild, toParent = os.pipe() #parent about to fork child process try: pid = os.fork() #create child process except OSError: sys.exit("Unable to create child process") if pid!=0: #am I parent process? #close unnecessary pipe ends os.close( toParent ) os.close(fromParent) #write values from 1-10 to parent's write pipe and read 10 values from child's read pipe for i in range(1,11): os.write(toChild, str(i)) print "Parent: %d" % i print "child: %s" %\ os.read(fromChild, 64) #close pipes os.close(toChild) os.close(fromChild) elif pid == 0: #am I child process? #close unnecessary pipe ends os.close(toChild) os.close(fromChild) #read value from parent pipe currentNumber = os.read(fromParent, 64) #if we receive number from parent, write number to child write pipe' while currentNumber: newNumber = int(currentNumber)*20 os.write(toParent,str(newNumber)) currentNumber = os.read(fromParent, 64) #close pipes os.close(toParent) os.close(fromParent) os._exit(0) #terminate child process
5e312df873e2f8b225e0b83b903ffd9fd92753b1
sparsh-m/30days
/d2_2.py
824
3.609375
4
#https://leetcode.com/problems/pascals-triangle/ """ 1)If num_rows == 0 return 0 2)If num_rows is 1 or 2 return hardcoded solution. 3)If num_rows is greater than zero, for ith row, arr[i][0] = 1 or arr[i][i] = 1 4)arr[i][j] = arr[i-1][j-1] + arr[i-1][j+1] Time Complexity: O(num_rows^2/2)=O(n^2) Space Complexity: o(num_rows^2) """ def sol(A): sol = [] if(A==0): return [] elif (A == 1): sol.append([1]) elif(A == 2): sol = [[1],[1,1]] else: sol = [[1],[1,1]] for i in range(2, A): solLine = [] for j in range(i+1): if(j == 0 or j == i): solLine.append(1) else: solLine.append(sol[i-1][j-1] + sol[i-1][j]) sol.append(solLine) return sol print(sol(5))
73f94e8417923e45b6dc13b9a56fa9021c6224ac
Aasthaengg/IBMdataset
/Python_codes/p00007/s152050164.py
170
3.59375
4
n = int(raw_input()) debt=100000 for i in range(n): debt*=1.05 if debt % 1000 != 0: debt = (int(debt / 1000)+1) * 1000 else: debt = int(debt) print debt
0606514c7a5bbf6f8205fa3cc41441229ed24d88
SagnikAdusumilli/csc148
/exercises/ex6/ex6_test.py
1,909
3.8125
4
"""CSC148 Exercise 6: Binary Search Trees === CSC148 Fall 2016 === Diane Horton and David Liu Department of Computer Science, University of Toronto === Module description === This module contains sample tests for Exercise 6. Warning: This is an extremely incomplete set of tests! Add your own to practice writing tests and to be confident your code is correct. For more information on hypothesis (one of the testing libraries we're using), please see <http://www.teach.cs.toronto.edu/~csc148h/fall/software/hypothesis.html>. Note: this file is for support purposes only, and is not part of your submission. """ import unittest from ex6 import BinarySearchTree class BSTNumLessThanTest(unittest.TestCase): def test_one(self): bst = BinarySearchTree(1) self.assertEqual(bst.num_less_than(10), 1) self.assertEqual(bst.num_less_than(0), 0) def test_bigger(self): bst = BinarySearchTree(1) bst._left = BinarySearchTree(-10) bst._right = BinarySearchTree(100) self.assertEqual(bst.num_less_than(5), 2) self.assertEqual(bst.num_less_than(-100), 0) self.assertEqual(bst.num_less_than(1000), 3) class BSTItemsTest(unittest.TestCase): def test_one(self): bst = BinarySearchTree(1) self.assertEqual(bst.items_at_depth(1), [1]) def test_empty(self): bst = BinarySearchTree(None) self.assertEqual(bst.items_at_depth(1), []) class BSTLevelsTest(unittest.TestCase): def test_one(self): bst = BinarySearchTree(1) self.assertEqual(bst.levels(), [(1, [1])]) def test_compex(self): bst = BinarySearchTree(5) bst._right = BinarySearchTree(6) bst._left = BinarySearchTree(2) bst._left._right = BinarySearchTree(3) self.assertEqual(bst.levels(), [(1, [5]), (2, [2, 6]), (3, [3])]) if __name__ == '__main__': unittest.main(exit=False)
cebf0c832c23c3588d3a63382b3eb826214e47d8
rickhaffey/python-per
/chapter03.py
24,149
4.40625
4
# ## 3. Types and Objects # every piece of data stored in a py program is an Objects # each object has a # - identity (pointer to a loc. in memory) # - type (class) # - value # identity and type can't be changed after instantiation # if value can be changed, object is mutable, otherwise, it's immutable # object that contains refs to other objects: container or collection # attribute: value associated with an object # method: function associated with an object # both accessed using dot (.) notation # ## object identity and type # `id()` function returns identity of object as integer # - usually the mem location, but implementation specific x = 42 print("id of x: {}".format(id(x))) # `is` compares identity of two objects class Foo: def __eq__(self, other): # treat all Foo's as value-equal return True a = Foo() b = Foo() print("id of a: {}".format(id(a))) print("id of b: {}".format(id(b))) print("a == b: {}".format(a == b)) print("a is b: {}".format(a is b)) # `type()` returns the type of an object print("type(x): {}".format(type(x))) print("type(a): {}".format(type(a))) # type of an object is _itself_ an object: the object's class # - uniquely defined # - always the same for all instances of a given type # - can be compared using the `is` operator # - assigned names can be used for type checking print("type(a) is type(b): {}".format(type(a) is type(b))) print("type([]) is list: {}".format(type([]) is list)) # a better way to check is to use `isinstance` # - inheritance aware print("isinstance([], list): {}".format(isinstance([], list))) # arguments against heavily using type checking: # - can negatively affect performance # - could miss interfaces of objects that don't match hierarchy but support # protocol # - heavy usage can be a sign that design needs to be reconsidered # ## reference counting and garbage collection # - all objects are reference-counted # - ref count is increased whenever an object is assigned to a new name or # placed in a container a = 37 # < ref count for object with value 37 = 1 b = a # < ref count = 2 c = [] c.append(b) # < ref count = 3 # - ref count is decreased by # - `del` statement # - reference goes out of scope # - name is re-assigned del a # < ref count for value 37 = 2 b = 42 # < ref count = 1 c[0] = 2.0 # < ref count = 0 # current reference count can be obtained with `sys.getrefcount`: import sys # noqa : E402 def print_a_refs(): print("sys.getrefcount(a): {}".format(sys.getrefcount(a))) a = 37 print_a_refs() b = a print_a_refs() del b print_a_refs() # note: value might be higher than expected: # - interpreter shares immutable objects across project to conserve memory # - etc. # when an object's ref count reaches 0, it is garbage-collected # circular dependencies: # in example below, ref count for q and r won't drop to 0 even after `del` # statements, resulting in a memory leak # interpreter periodically searches for such inaccessible objects and deletes # them q = {} r = {} q['r'] = r r['q'] = q del q del r # ## references and copies a = [1, 2, 3, 4] b = a # b now points to the same object that a points to b[2] = 42 # this changes the same underlying object behind both 'a' and 'b' print(a[2]) # 42 # two types of copy operations # - shallow copy: new object, but populates it with references to the same # items contained in the original objects a = [1, 2, [3, 4]] b = list(a) # creates a shallow copy print("b is a: {}".format(b is a)) # appending/removing to a shallow copy doesn't affect original b.append(42) print("a: {}".format(a)) print("b: {}".format(b)) # modify a (mutable) object contained by the copy will change the object in the # original, too b[2][1] = 99 print("a: {}".format(a)) print("b: {}".format(b)) # - deep copy: creates a new object, and recursively copies all the objects # it contains # - no built-in operation # - use `copy` module in standard library: `copy.deepcopy` import copy # noqa : E402 a = [1, 2, [3, 4]] b = copy.deepcopy(a) b[2][1] = 43 print("a: {}".format(a)) print("b: {}".format(b)) # ## first-class objects # - all objects that can be named by an identifier have equal status # - all objects that can be named can be treated as data data = {} # basic data["number"] = 42 # int data["text"] = "hello" # string # more complex data["func"] = abs # builtin function data["mod"] = sys # module data["error"] = ValueError # type data["append"] = a.append # function of another object # this allow for compact, flexible code line = "GOOG,100,490.10" types = [str, int, float] fields = [ty(val) for ty, val in zip(types, line.split(","))] print(fields) # ## built-in types for representing data: # ### The `None` Type # `type(None)` - The null object `None` # - denotes a null object # - exactly 1 # - often used to indicate when default params aren't overridden in function # call # - has no attributes # - evaluates to False in Boolean expressions # ### Numeric Types # `int` - integer # - whole numbers # - range: unlimited (except by available memory) # - acts like py2 `long` type # `float` - floating point # - represented using native double-precision (64-bit) rep of machine # - typically this is IEEE 754 # - approximately 17 digits of precision # - exponent in the range –308 to 308 # - same as `double` type in C # - for more precise space / precision control, look to using numpy # `complex` - complex number # - represented as pair of floating-point numbers # - `z.real` : real portion # - `z.imag` : imaginary part # `bool` - Boolean # - two values: (`True` => 1 or `False` => 0) # - all immutable # - all (except Boolean) are signed # - to support a common interface / mixed arithmetic, some shared attributes: # - x.numerator (int) # - x.denominator (int) # - x.real (int + float) # - x.imag (int + float) # - x.conjugate (int + float) # - x.as_integer_ratio (float) # - x.is_integer (float) # - additional numeric types in library modules (e.g. `decimal`, `fractions`, # etc.) # ### Sequences # - ordered sets of objects indexed by integers # - support iteration # `str` - character string # - sequence of characters # - immutable # `list` - list # - sequence of arbitrary python objects # - allow insertion, deletion, substitution # `tuple` - tuple # - sequence of arbitrary python objects # - immutable # `range` - a range of integers # operations available on all sequences: a = [1, 2, 3, 4, 5] a[3] a[2:4] a[1:5:2] len(a) min(a) max(a) sum(a) all(a) # checks whether all are true any(a) # checks whether any are true # operations available on mutable sequences (e.g. lists) a[3] = 42 a[2:4] = [99] * 2 a[1:5:2] = [1001] * 2 del a[3] del a[2:4] del a[1:5:2] # ### lists # convert an iterable to a list with `list()` # - if iterable is already a list, creates a shallow copy i = range(3) a = list(i) a.append(42) a.extend([43, 44, 45]) a.count(42) # counts occurrences of 42 in a a.index(42) # returns index of first instance of 42 found in a a.insert(3, 99) # insert 99 at index 3 a.pop() a.remove(99) a.reverse() # reverse (in place) def strange_sort(x): if(x <= 3): return x else: return -x a.sort(key=strange_sort, reverse=True) print(a) # see chapter03.strings.py for details about string sequences # ## range for x in range(10): print(x, end='') # 0123456789 for x in range(1, 10, 2): print(x) # 13579 # ### Mapping # - represents a collection of objects referenced by a collection of keys # - unordered # - can be indexed ('keyed') by numbers, strings, and other objects # - mutable # ##`dict` - dictionary # - only built in mapping type # - Python's version of a hash table / associative array # - can use any immutable object as a key # - can't use lists, dictionaries, or tuples containing immutable objects d = { "a": 1, "b": "two", "c": [3], "d": 4 } len(d) d["a"] d["b"] = "TWO" del d["d"] "c" in d # => True d2 = d.copy() d2.clear() d3 = dict.fromkeys(["foo", "bar", "baz", "bat"], 42) # {'bar': 42, 'bat': 42, 'baz': 42, 'foo': 42} d.get("b") # => "two" d.get("foo") # => None d.get("foo", "bar") # => "bar" {"a": 1, "b": 2, "c": 3}.items() # => [('c', 3), ('b', 2), ('a', 1)] # note: type is `dict_items` {"a": 1, "b": 2, "c": 3}.keys() # => ['c', 'b', 'a'] # note: type is `dict_keys` {"a": 1, "b": 2, "c": 3}.values() # => [3, 2, 1]) # note: type is `dict_values` # ## pop d = {"a": 1, "b": 2, "c": 3} d.pop("b") # => 2, d = {"a": 1, "c": 3} d = {"a": 1, "b": 2, "c": 3} d.pop("d", 42) # => 42, d = {"a": 1, "b": 2, "c": 3} d = {"a": 1, "b": 2, "c": 3} d.pop("d") # raises KeyError, d = {"a": 1, "b": 2, "c": 3} d = {"a": 1, "b": 2, "c": 3} d.popitem() # equivalent to calling pop with a randomly selected key value # if d is empty, raises a KeyError d = {"a": 1, "b": 2, "c": 3} d.setdefault("d", 4) # => 4; d = {"a": 1, "b": 2, "c": 3, "d": 4} d.setdefault("d", 99) # => 4; d = {"a": 1, "b": 2, "c": 3, "d": 4} d1 = {"a": 1, "b": 2, "c": 3} d2 = {"a": 11, "c": 33, "d": 44} d1.update(d2) # d1 = {'a': 11, 'b': 2, 'c': 33, 'd': 44} # ### Sets # `set` - mutable set # `frozenset` - immutable set # - unordered collection of unique items # - no indexing # - no slicing # - no key values # - item place in set must be immutable # ## methods on all sets s = set("abcdefg") len(s) s.copy() s.difference(set("abc")) # => {'d','e','f','g'} s.intersection(set("abc")) # => {'a','b','c'} s.isdisjoint(set("qrs")) # => True s.issubset(set("abcdefgh")) # => True s.issuperset(set("ab")) # => True s.symmetric_difference(set("defghij")) # => {'a', 'b', 'c', 'h', 'i', 'j'} set("abc").union(set("123")) # => {'a','b','c','1','2','3'} # ## NOTE - parameter to all of these can be any iterable of immutable objects set("abc").union([1, 2, 3, 4]) # => {1, 2, 'b', 3, 4, 'a', 'c'} # ## methods on mutable sets # - all modify set in-place s = set("abc") s.add("X") # => {'X', 'a', 'b', 'c'} s.difference_update("az") # => {'X', 'b', 'c'} s.intersection_update("aXdb") # => {'X', 'b'} s.symmetric_difference_update("bY") # => {'X', 'Y'} s = set("abcX") s.discard("X") # => {'a', 'b', 'c'} s.discard("X") # => no change s = set("abcX") s.remove("X") # => {'a', 'b', 'c'} s.remove("X") # => raises KeyError s.update("aceg") # => {'a','b','c','e','g'} s.clear() # ## Built-In Types for Representing Program Structure # - Callable # - types.BuiltinFunctionType # - type # - object # - types.FunctionType # - types.MethodType # - Modules # - types.ModuleType # - Classes # - object # - Types # - type # ## callable types # - support function call operation # ### user defined functions # - via `def` or `lambda` def f(x, y=0): """return the sum of the two input values""" return x + y lambda x, y: x + y f.__doc__ # => 'return the sum of the two input values' f.__name__ # => 'f' f.__dict__ # => {} f.__code__ # => <code object f at 0x106162420, file "<ipython-input-38-f361d85c9fb4>", line 1> # noqa f.__defaults__ # => (0,) f.__globals__ # => returns a dictionary defining the global namespace f.__closure__ # => Tuple containing data related to nested scopes # ## Methods # - functions defined inside class definition # - three common types: # - instance # - class # - static class Foo: def instance_method(self, arg): """ - operates on an instance of the class - first argument ('self' in this case) is the instance - represented by object of type `types.MethodType` """ pass @classmethod def class_method(cls, arg): """ - operates on the class itself as an object - first argument ('cls' in this case) is the class itself - represented by object of type `types.MethodType` """ pass @staticmethod def static_method(arg): """ - a function that happens to be packaged inside a class - it doesn't receive an instance or class as its first argument """ pass # invoking instance or class method is a two step process f = Foo() meth = f.instance_method # => 1) look up the method as an attribute # - meth above is a "bound method" # - a callable object # - wraps both a function and the associated instance # - when called, the instance is passed as the first parameter meth(42) # => 2) invoke the method type(meth) # => method # some available attributes on method type: meth.__doc__ # doc string meth.__name__ # name of the method meth.__class__ # => method meth.__func__ # function object implementing the method meth.__self__ # the bound instance # method lookup can occur on the class itself umeth = Foo.instance_method # - umeth above is an "unbound method" # - a callable object # - wraps the function # - implicitly expect an instance of the proper type to be passed # as the first parameter, but in P3, that isn't enforced umeth(f, 99) type(umeth) # => function # functions have some of the same attributes as method, # except __func__ and __self__ are not defined # ## Built-in Functions and Methods # - represent functions and methods implemented in C and C++ # - available attributes: len.__doc__ len.__name__ len.__self__ # => <module 'builtins' (built-in)> [].append.__self__ # => [] # ## Classes and Instances as Callables # - class object called as a function to create new instances # - arguments are passed through to the `__init__()` method of the class f2 = Foo() # - instances can emulate a function by definining a `__call__()` method class Bar: def __call__(self, arg): print(arg) b = Bar() b("test of the __call__ function") # => test of the __call__ function # ## Classes, Types, and Instances # - class definition produces an object of type `type` type(Bar) # => type # - attributes of type Bar.__doc__ Bar.__name__ Bar.__bases__ # => tuple of base classes, (object,) Bar.__dict__ # => dictionary holding class methods and variables Bar.__module__ # => module name in which class is defined # for an instance of a class, it's type is the class that defined it type(b) # => __main__.Bar # instances have the following special attributes b.__class__ # => class to which instance belongs b.__dict__ # => dict holding instance data # ## Module Type # - container that holds objects loaded with the `import` statement # - `import foo` => name "foo" assigned to the imported module # - namespace defined that's a dictionary named `__dict__` # - referencing a module attribute with dot notation translates to dict lookup: # - foo.bar => foo.__dict__["bar"] # - sim. for assignment to attributes import chapter01 as foo # noqa foo.__dict__ sys.__doc__ sys.__name__ sys.__file__ # sys.__path__ # => only for packages # ## Builtin Types for Interpreter Internals # - exposed internals of the interpreter # - can be useful in tooling and framework development # ### Code Objects # - represent raw byte-compiled executable code: bytecode # - typically returned by built-in `compile` function source = """ for x in range(10): print("value: {}".format(x)) """ codeObj = compile(source, "<string>", "exec") codeObj.co_code # => b"x'\x00e\x00\x00d\x00\x00\x83\x01\x00D]\x19..." # (string representing raw bytecode) codeObj.co_consts # => (10, 'value: {}', None) codeObj.co_names # => ('range', 'x', 'print', 'format') # ## Frame & Traceback Objects # ## Frame: # - represent execution frames # ## Traceback: # - created when an exception occurs; provide stack trace info def bottom(): return 1 / 0 def middle(): return bottom() def top(): return middle() try: top() except ZeroDivisionError: _, _, t = sys.exc_info() print(dir(t)) while(t): f = t.tb_frame print("{} in {}".format(f.f_code.co_filename, f.f_code.co_name)) t = t.tb_next # ==> # <ipython-input-103-6390464d02b0> in <module> # <ipython-input-84-1a5d4b7eb2f4> in top # <ipython-input-84-1a5d4b7eb2f4> in middle # <ipython-input-84-1a5d4b7eb2f4> in bottom # ## Generator objects # - defined when a function makes use of the `yield` keyword # - generator obj serves as both an iterator and container for info about the # gen function itself def my_gen(): x = 0 while x < 10: yield x x += 1 g = my_gen() g.gi_code # => code object for the generator g.gi_frame # => execution frame g.__next__() # => execute until next `yield` statement g.send(123) g.close() # => closes a generator by raising `GeneratorExit` in gen fx g.throw(NameError) # => raise an exception in the generator # ## Slice Objects # - used to represent slices s = slice(10, 20) s.start # => 10 s.stop # => 20 s.step # => None s.indices(15) # => (10, 15, 1) represents how slice would be applied: # my_list[10:15:1] # ## Ellipsis Object # - used to represent the presence of an ellipsis in an index lookup # - singleton # - no attributes; evaluates to True class CustomCollection(): def __getitem__(self, index): print(index) cc = CustomCollection() cc["a", ..., "z"] # => ('a', Ellipsis, 'z') # ## Object Behavior and Special Methods # - all basic interpreter operations are implemented through special object # methods # - names are preceded and follwed by double underscore: (__foo__) # - automatically triggered by interpreter as program executes # - e.g # - `x + y` is mapped to `x.__add__(y)` # - `x[y]` is mapped to `x.__getitem__(y)` # ## Object Creation and Destruction class Foo: def __new__(cls): print("in Foo.__new__") x = Foo.__new__(Foo) class Bar: def __init(self, value): self.value = value print("in Bar.__init__") b = Bar(42) # - note: it's rare to define __new__ or __del__ in user defined objects # ## Object String Representation # - `__repr__` : returns a string representation that can be evaluated to re- # create the object # - `__str__` : can be a more concise, printable string for the user # - `__format__` : called by `format` function class Foo: def __repr__(self): return "Foo()" def __str__(self): return "<Foo>" def __format__(self, _spec): return "(Formatted Foo)" f = Foo() repr(f) # => "Foo()" str(f) # => "<Foo>" "my foo is {}".format(f) # => 'my foo is (Formatted Foo)' # ## Object Comparison and Ordering # - __bool__ # => used for truth-value testing (falls back to __len__ if # not defined) # - __hash__ # => computes hash; don't define this on immutable types # - __lt__ # => supports '<' # - __le__ # => supports '<=' # - __gt__ # => supports '>' # - __ge__ # => supports '>=' # - __eq__ # => supports '==' # - __ne__ # => supports '!=' class Foo: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value def __lt__(self, other): # reverse the ordering return self.value.__gt__(other.value) def __str__(self): return "<Foo({})".format(self.value) def __repr__(self): return "Foo({})".format(self.value) foos = [Foo(i) for i in range(10)] min_foo = min(foos) # => Foo(9) sorted(foos) # => [Foo(9), Foo(8), Foo(7), ..., Foo(0)] # ## Type Checking # __instancecheck__(cls, object) # => redefine `isinstance(object, cls)` # __subclasscheck__(cls, sub) # => redefine `issublcass(sub, cls)` # NOTE that these methods are looked up on the type (metaclass) of a class. # They cannot be defined as class methods in the actual class. This is # consistent with the lookup of special methods that are called on instances, # only in this case the instance is itself a class. # ## Attribute Access # __getattribute__ # => returns the attribute # __getattr__ # => returns the attribute, or raises AttributeError if not # found # ## Attribute Wrapping and Descriptors # - associated with descriptor objects # - optional, and rarely need to be defined # __get__ # __set__ # __delete__ # ## Sequence and Mapping Methods # - methods used by objects that want to emulate sequence and mapping objects # __len__ # called by `len()` # __getitem__ # supports [] retrieval # __setitem__ # supports [] assignment # __delitem__ # supports `del` # __contains__ # supports `in` operator # note that __getitem__, __setitem__, and __delitem__ can also accept slice # objects as the key class MyCollection: def __init__(self, values): self.values = values def __len__(self): return len(self.values) def __getitem__(self, key): return self.values.__getitem__(key) def __contains__(self, key): return self.values.__contains__(key) # etc... c = MyCollection("ABCDEF") len(c) # => 6 c[3] # => 'D' c[:4] # => 'ABCD' "Z" in c # => False # etc... # ## Iteration # __iter__ # => returns an iterator object # # (iterator must implement __next__) # # supports `for` statement and other iteration operations # ## mathematical operations -> (also see chapter03.math.py) # - evaluated from left to right # - methods beginning with 'r' support reversed operands; # - called if the left operand doesn't implement the operation # - e.g.: if `x + y` doesn't support `x.__add__(y)` then iterpreter # tries `y.__radd__(x)` # - methods beginning with 'i' support in-place operations # - e.g. x += 1, etc. # - __int__, __long__, __float__, and __complex__ convert object to that type class SpecialString: def __init__(self, value): self.value = value def __int__(self): # note: very fragile example return { 'one': 1, 'two': 2, 'three': 3 }.get(self.value, -1) two = SpecialString("two") print("int(two) = {}".format(int(two))) # => 'int(two) = 2' # ## Callable Interface # -- __call__ => allow invoking object like a function class MyCallable: def __call__(self, foo, bar): print("You called me with '{}' and '{}'".format(foo, bar)) mc = MyCallable() mc("foo", "bar") # => "You called me with 'foo' and 'bar'" # ## Context Management Protocol # __enter__ # => called when `with` statement executes; return value assigned # to value in `as var` # __exit__ # => called when leaving `with` block class MyContextMgr: def __init__(self, value): self.value = value def __enter__(self): print("entering context ...") return self def __exit__(self, type, value, tb): if(type): print("\ttype: {}\n\tvalue: {}\n\ttb: {}".format(type, value, tb)) print("exiting context ...") with MyContextMgr("foo") as m: print("context value: {}".format(m.value)) raise Exception("fubar") # entering context ... # context value: foo # type: <class 'Exception'> # value: fubar # tb: <traceback object at 0x10376e148> # exiting context ... # --------------------------------------------------------------------------- # Exception Traceback (most recent call last) # <ipython-input-28-7e5c0f705b42> in <module>() # 1 with MyContextMgr("foo") as m: # 2 print("context value: {}".format(m.value)) # ----> 3 raise Exception("fubar") # # Exception: fubar # ## Object Inspection and `dir()` # __dir__ # => return an overridden list of names to return with `dir` call class Regular: pass class Irregular: def __dir__(self): return ['nothing'] r = Regular() dir(r) # ['__class__', # '__delattr__', # '__dict__', # '__dir__', # '__doc__', # '__eq__', # '__format__', # '__ge__', # '__getattribute__', # '__gt__', # '__hash__', # '__init__', # '__le__', # '__lt__', # '__module__', # '__ne__', # '__new__', # '__reduce__', # '__reduce_ex__', # '__repr__', # '__setattr__', # '__sizeof__', # '__str__', # '__subclasshook__', # '__weakref__'] i = Irregular() dir(i) # ['nothing']
a0e5e7e76ed2b3b3b2e4b1b751d809dd2e1e3e3d
munagekar/cp
/leetcode/00001.py
723
3.546875
4
''' https://leetcode.com/problems/two-sum/ Approach one : nlogn + nlogn For every number binary search sorted array Approach two Used: nlogn + n Two Pointer first,last in sorted array Approach three: Linear Use Map, Check if number complement is present else insert number Eg: If on 2 and target is 7, check for 5. ''' class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: first = 0 last = len(nums) - 1 nums.sort() while True: check = nums[first] + nums[last] if check == target: return [first,last] elif check > target: last-=1 else: first+=1
a96fd5b24b5dbcfcb1db831f8655511a20fa6ea2
AlbaGV/Python
/Python/String/string1.py
327
3.953125
4
# Se dice una fruta y luego se pide un numero (desde 1), este numero corresponde a una letra de fruta escrita fruta=raw_input("Dime una fruta: ") num1=int(raw_input("Dime un numero:")) num2=num1-1 long=len(fruta) if num1>long: print "Lo siento, la fruta no tiene tantas letras" elif num1<=long: print fruta[num2]
04e3bc6388d48c047244e90e7d7365db95bf6522
savadev/interviewbit
/Arrays/maximum-consecutive-gap.py
1,647
3.78125
4
''' Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Example : Input : [1, 10, 5] Output : 5 Return 0 if the array contains less than 2 elements. You may assume that all the elements in the array are non-negative integers and fit in the 32-bit signed integer range. You may also assume that the difference will not overflow. ''' ''' Find min and max in the input. And then divide the gap between min and max into length - 1 of groups. For each group, record the min and max of the number falling in the range. The maximum gap must appear accross groups -- why? Pigeon hole theory. ''' import math class Solution: # @param A : tuple of integers # @return an integer def maximumGap(self, A): n = len(A) if n < 2: return 0 Min = min(A) Max = max(A) gap = (Max-Min) / float(n-1) if gap==0: return 0 MIN = Min-1 MAX = Max+1 elems = [[MIN, MAX] for i in range(n)] # stores (min, max) for every gap range for num in A: pos = int((num - Min) / gap) elems[pos][0] = max(elems[pos][0], num) elems[pos][1] = min(elems[pos][1], num) ans = 0 prev = elems[0][1] # Which would ofcourse be Min for i in range(n): if elems[i][0]==MIN and elems[i][1]==MAX: continue # These gap range doesn't have any elements ans = max(ans, elems[i][1]-prev) # (min of this range) - (max of prev) prev = elems[i][0] # Max for this gap range return ans
856ac59798d7d146a2a8250554009189e6cdc4cb
dpezzin/dpezzin.github.io
/test/Python/dataquest/matrices_and_numpy/index_data.py
923
4.3125
4
#!/usr/bin/env python # The columns are Year, Region, Country, Beverage type, and Number of liters of pure alcohol drunk per person # The print function below prints the number of liters of pure alcohol vietnamese drank in wine in 1986. print(world_alcohol[0,4]) # The Beverage type can take the values "Beer", "Wine", "Spirits", and "Other" # If we want to grab a whole row, we replace the column number with a colon, which means "get all of the columns" print(world_alcohol[0,:]) # If we want to grab a whole column, we do the same thing with the row number. countries = world_alcohol[:,2] # Assign the amount of alcohol Uruguayans drank in other beverages per capita in 1986 to uruguay_other_1986. This is the second row in the data. # Assign the whole fourth row to row_four. # Assign the whole year column to years. uruguay_other_1986 = world_alcohol[1,4] row_four = world_alcohol[3,:] years = world_alcohol[:,0]
1cad548311a8896ebdc7c873daf2695bce5422f4
Nepta75/hi-python
/ex03_rps/main.py
1,330
3.515625
4
import random rpsValues = { 'pierre': 'papier', 'papier': 'ciseau', 'ciseau': 'pierre', } def isWin(rpsNamePlayer, rpsNameBot): win = 'perdu' if rpsNamePlayer == rpsNameBot: win = 'null' return win if rpsValues.get(rpsNamePlayer) != rpsNameBot: win = 'gagné' return win def game(): rpsNameBot = '' rpsNames = '' rpsNamePlayer = '' for rpsValue in list(rpsValues): rpsNames += (',' if len(rpsNames) > 0 else '') + rpsValue while ( (rpsNamePlayer != list(rpsValues)[0]) and (rpsNamePlayer != list(rpsValues)[1]) and (rpsNamePlayer != list(rpsValues)[2]) ): rpsNamePlayer = input("Taper une des trois options: " + rpsNames + ": ") rpsNameBot = random.choice(list(rpsValues)) print("Ordinateur a joué: " + rpsNameBot) print("Vous avez joué: " + rpsNamePlayer) if (isWin(rpsNamePlayer, rpsNameBot) == 'gagné'): print("Success: Vous avez gagné contre l'ordinateur !") elif (isWin(rpsNamePlayer, rpsNameBot) == 'null'): print("Dommage: Vous avez fait match null avec l'ordinateur !") elif (isWin(rpsNamePlayer, rpsNameBot) == 'perdu'): print("Sorry: Vous avez perdu contre l'ordinateur !") response = input("Voulez-vous rejouez ? (y/no): ") if response == 'y' or response == 'yes' or response == 'oui': return game() return game()
b8cf7ec765719e0136cd0dcc3377f592d6d06cf9
harshsinghs1058/python_hackerrank_solutions
/String_Formatting.py
423
3.578125
4
# This code is written by harsh. def print_formatted(n): l_bin = len(str(bin(n))[2:]) for i in range(1, n + 1): print(str(i).rjust(l_bin, " "), end=" ") print(str(oct(i))[2:].rjust(l_bin, " "), end=" ") print(str(hex(i))[2:].upper().rjust(l_bin, " "), end=" ") print(str(bin(i))[2:].upper().rjust(l_bin, " ")) if __name__ == "__main__": n = int(input()) print_formatted(n)
c44b64febe0112bf12beb1de369ec9735c9a1059
Asi4nn/Pygame-Graphing-Calculator
/analyze.py
12,349
4.15625
4
#-------------------------------------------------------------------------------- # Entering and Analyzing Equation # Julian and Leo # Analyses the equations and fingures out what they mean # Also calculates analyzed equations to graph with #-------------------------------------------------------------------------------- import math radOrDeg = "rad"#radians or degrees variable operators = ["+","-","*","/","^",".","sin","cos","tan","sqrt"]#possible operators allowed #possible variable options the user can use to create their own variable. possibleVars = ['a','b','c','d','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','z'] conversions = ["sin","cos","tan","sqrt"] isError = True customVars = {}#Stores the custom user variables and their value verticals = []#Stores vertical lines def RemoveExtraBrackets(n): #keeps removing extra sets of brackets within each other. 2*(((x+1))) will turn into 2*(x+1) if type(n) is list:#and maxRecur > 0 return RemoveExtraBrackets(n) #replaces a list with one element, with that one element. The list is technically pointless elif type(n) is float or type(n) is int or n == "x": return n return n def Setup_1(e,i): global customVars #Checking if the equation ends with any operator which doesn't make sense if e[0] in ["+","*","/","^","."] or e[-1] in operators: return None elif len(e) >= 3 and ''.join(e[-3:]) in operators: return None elif len(e) >= 4 and ''.join(e[-4:]) in operators: return None #Won't allow more than 1 = sign if len([n for n in e if n == "="]) > 1: return None while i < len(e): #initialize areas with brackets first if e[i] == "(": b = 1 #counting unfinished begin/end bracket pairs #once an equal amount of begin/end brackets are found, that area is intialized for n,j in enumerate(e[i+1:]): if j == "(": b += 1 elif j == ")": b -= 1 if b == 0: temp = e[i+1:i+n+1] #the area inside the set of brackets del e[i:i+n+1] e[i] = Initialize(temp) #initializes the bracketed area if e[i] != None: if len(e[i]) == 1: e[i] = RemoveExtraBrackets(e[i][0]) #If a list has one element, there's no need for the list else: return None break if b != 0: return None #sets all possible integers into an integer if type(e[i]) is str: try: int(e[i]) except ValueError: '''''' else: e[i] = int(e[i]) i += 1 while len(e) == 1 and type(e[0]) is list: e = e[0] #removes "y=" since it technically isn't needed if len(e) > 1 and e[0] == "y" and e[1] == "=": del e[0:2] return e def Setup_2(e,i): #combines consecutive integers into one [1,2] --> [12] while i < len(e): if type(e[i]) is int and type(e[i-1]) is int: #combines two and deletes the other e[i-1] = int("".join([str(c) for c in e[i-1:i+1]])) del e[i] else: i += 1 return e def Setup_3(e,i): #combines integers with a decimal between them into a float [1,'.',22] --> [1.22] while i < len(e): if type(e[i]) is int and e[i-1] == "." and type(e[i-2]) is int: #adds one plus other/10**len for it to be the correct decimal place e[i-2] = e[i-2]+(e[i]/10**len(str(e[i]))) del e[i-1:i+1] else: i += 1 return e def Setup_4(e,i): #combines letters for operations with lengths greater than one, like "sin" and "sqrt". while i < len(e): if type(e[i]) is list: e[i] = Setup_4(e[i],0) #repeats process in nested lists #If 3 consecutive letters equals an operation, merge them. ['s','q','r','t'] --> ['sqrt'] elif len(e)-i >= 4 and "".join([str(c).lower() for c in e[i:i+4]]) in operators: e[i] = "".join([str(c).lower() for c in e[i:i+4]]) del e[i+1:i+4] #If 3 consecutive letters equals an operation, merge them. ['s','i','n'] --> ['sin'] elif len(e)-i >= 3 and "".join([str(c).lower() for c in e[i:i+3]]) in operators: e[i] = "".join([str(c).lower() for c in e[i:i+3]]) del e[i+1:i+3] elif e[i] == " ": del e[i] i -= 1#counters the i+=1 below to stay on the same index next iteration i += 1 return e #[-,x,^,2,+,1] [-1,*,x,^,2,+,1] #[1,-,x,^,2,+,1] [1,+,-1,*,x,^,2,+,1] def Setup_5(e,i): global customVars,possibleVars #removes extra '+', changes subtracton to addition of a negative, and also changes 2 '-' to '+' while i < len(e)-1: #Changes subtrauction to addition of negative for numbers if e[i] == "-" and (type(e[i+1]) is int or type(e[i+1]) is float): e[i] = "+" e[i+1] = -e[i+1] #If there's no number, it multiplies by negative 1 elif e[i] == "-" and (e[i+1] == "x" or type(e[i+1]) is list or e[i+1] in conversions): if i > 0: e[i] = "+" e.insert(i+1,"*") e.insert(i+1,-1) i += 2 else: del e[i] e.insert(i,"*") e.insert(i,-1) i += 1 i += 1 #changes 2 consecutive subtraction into addition elif e[i] == "-" and e[i+1] == "-": e[i] = "+" del e[i+1] #deletes extra addition symbols if e[i] == "+" and e[i+1] == "+": del e[i+1] i += 1 #detects the user trying to create a custom variable and adds it to the dictionary customVars. "y" and "e" aren't included as they are used elsewhere if len(e) == 3: #Case 1, adding a positive number if e[1] == "=" and e[0] in possibleVars and (type(e[2]) is int or type(e[2]) is float or e[2] in possibleVars): if e[0].lower() == "x": verticals.append(e[2]) elif e[0] not in customVars: #doesn't allow two of the same variable customVars[e[0]] = e[2] else: return None elif len(e) == 4: #Case 2, adding negative number if e[1] == "=" and e[0] in possibleVars and e[2] == "+" and (type(e[3]) is int or type(e[3]) is float or e[3] in possibleVars): if e[0].lower() == "x": verticals.append(e[3]) elif e[0] not in customVars: #doesn't allow two of the same variable customVars[e[0]] = e[3] else: return None #If there is an unknown variable, don't do anything for n in range(len(e)): if type(e[n]) is str and e[n] not in operators and e[n] not in customVars and e[n] not in ['x','y','e','π']: return None return e #Prepares the inputted equation to calculate def Initialize(e): #Runs each setup step, more info in their corresponding functions above e = Setup_1(e,0) if e == None: return None e = Setup_2(e,1) e = Setup_3(e,2) e = Setup_4(e,0) e = Setup_5(e,0) if e == None: return None return e def Postfix(e,i,opstack,output): #Sorts the equation into a format easy to calculate with, more info in link below #https://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html priority = {"^":3,"*":2,"/":2,"-":1,"+":1} if e == None: return None while i < len(e): if type(e[i]) is list: temp = Postfix(e[i],0,[],[]) for t in temp: output.append(t) elif type(e[i]) is int or type(e[i]) is float: output.append(e[i]) elif e[i] in operators: if len(opstack) > 0 and priority[opstack[-1]] > priority[e[i]]: output.append(opstack[-1]) del opstack[-1] opstack.append(e[i]) #new stuff------------------------------------------------------------ if len(opstack) >= 2: if priority[opstack[-1]] < priority[opstack[-2]]: output.append(opstack[-2]) del opstack[-2] #new stuff-------------------------------------------------- i += 1 for op in reversed(opstack): output.append(op) return output #-------------------------------------------------- CALCULATIONS ------------------------------------------------------------ def PreCalc(e,i,radOrDeg,xVal=None): for n in range(len(e)): #If there is a list, repeat the process within it if type(e[n]) is list: e[n] = Calculate(e[n][:],[],0,xVal,radOrDeg)#Calculate inner lists #Change all x's to the current x value elif e[n] == "x" and (type(xVal) is int or type(xVal) is float): e[n] = xVal elif e[n] == "π": #Replaces π with pi e[n] = math.pi elif e[n] == "e": #Replaces e with Euler's number e[n] = 2.718281828459 while e[n] in customVars:#Allows for multiple 'layers' if a=1, 'a' is replaced with 1, if a=b and b=2, 'a' is replaced with 2 e[n] = customVars[e[n]] #Pre-calculates all "conversion" operations like sine leaving only basic ones like adding while i < len(e)-1: if e[i] in conversions: if type(e[i+1]) in [int,float]: #calculates sine if e[i].lower() == "sin": if radOrDeg == "deg": e[i] = round(math.sin(math.radians(e[i+1])),10) del e[i+1] elif radOrDeg == "rad": e[i] = round(math.sin(e[i+1]),10) del e[i+1] #calculates cosine elif e[i].lower() == "cos": if radOrDeg == "deg": e[i] = round(math.cos(math.radians(e[i+1])),10) del e[i+1] elif radOrDeg == "rad": e[i] = round(math.cos(e[i+1]),10) del e[i+1] #calculates tangent elif e[i].lower() == "tan": if radOrDeg == "deg": e[i] = round(math.tan(math.radians(e[i+1])),10) del e[i+1] elif radOrDeg == "rad": e[i] = round(math.tan(e[i+1]),10) del e[i+1] #calculates square root elif e[i].lower() == "sqrt": if type(e[i+1]) in [int,float] and e[i+1] >= 0: e[i] = math.sqrt(e[i+1]) del e[i+1] else: return None else: return None i += 1 return e #Deals with the basic operations between 2 numbers, called by Calculate def Calc(a,b,op): if op == "+": return (a + b) elif op == "-": return (a - b) elif op == "*": return (a * b) elif op == "^": try: (a ** b) except OverflowError: return None else: return (a ** b) elif op == "/": if b == 0: return None else: return (a / b) def Calculate(e,temp,i,x,radOrDeg): f = Postfix(PreCalc(e,0,radOrDeg,x),0,[],[]) #Uses a pre-sorted bedmas-friendly format to calculate with called "Postfix notation" if f == None: return None elif len(f) == 0: return None else: #Calculates every operation between 2 terms while i < len(f): if type(f[i]) is int or type(f[i]) is float: temp.append(f[i]) if f[i] in operators and len(temp) > 1: temp.append(Calc(temp[-2],temp[-1],f[i])) if temp[-1] == None: return None del temp[-3:-1] i += 1 return temp[0] return None
c47d6f651d3181107fedb40297d1083ce00b6081
dmahugh/weather-tracker
/updater.py
4,437
3.625
4
"""Gets weather forecasts from OpenWeatherMap API for tracked locations and stores them in the Cloud SQL database. Before running this code, open a command window and run this command to launch the Cloud SQL proxy: cloud_sql_proxy -instances=<database_instance_connection_string> """ import requests import defaults from dbfunctions import db_connection def get_forecast_api(owm_id): """Gets a forecast from the OpenWeatherMap API. Args: owm_id: a valid OpenWeatherMap location ID Returns: A tuple containing the JSON data returned for this forecast and the HTTP status code for the API call. """ response = requests.get( ( f"http://api.openweathermap.org/data/2.5" f"/forecast?id={owm_id}&APPID={defaults.API_KEY}" ) ) return response.json(), response.status_code def save_forecasts(connection, forecast_data): """Saves a forecast retrieved from OpenWeatherMap API. Args: connection: a pymysql connection object forecast_data: the JSON payload returned by the OpenWeatherMap API for a single location. Note that this payload contains 40 discrete forecasts, one every 3 hours for the next 5 days. Returns: none """ cursor = connection.cursor() location_id = forecast_data["city"]["id"] city = f"{forecast_data['city']['name']}, {forecast_data['city']['country']}" for forecast in forecast_data["list"]: # For each forecast, store it in the database. There should be # 40 forecasts total: one every 3 hours for the next 5 days. kelvin_temp = forecast["main"]["temp"] temp = int(1.8 * (kelvin_temp - 273) + 32) # convert to Farenheit wind = wind_format(forecast["wind"]["speed"], forecast["wind"]["deg"]) icon_url = ( f'http://openweathermap.org/img/w/{forecast["weather"][0]["icon"]}.png' ) columns = ( "Epoch, ForecastDT, City, LocationID, Conditions," " Temp, Humidity, Cloudy, Wind, IconURL" ) values = ( f'{forecast["dt"]}, "{forecast["dt_txt"]}", "{city}",' f' "{location_id}", "{forecast["weather"][0]["main"]}",' f' {temp}, {int(forecast["main"]["humidity"])},' f' {int(forecast["clouds"]["all"])}, "{wind}", "{icon_url}"' ) cursor.execute(f"INSERT INTO Forecast ({columns}) values ({values})") connection.commit() def main(): """Retrieves the latest forecasts from OpenWeatherMap for all tracked locations and stores them in the wtracker database. Args: none (looks to the Location.Tracked column to determine which locations are being tracked) Returns: none """ connection = db_connection() cursor = connection.cursor() cursor.execute("SELECT LocationID, City, Country FROM Location WHERE Tracked=TRUE") rows = cursor.fetchall() for owm_id, city, country in rows: print(f"Updating location {owm_id}: {city}, {country} ... ", end="") forecast_data, status_code = get_forecast_api(owm_id) if str(status_code).startswith("2"): save_forecasts(connection, forecast_data) else: print(f"REQUEST FAILED: status code {status_code}") cursor = connection.cursor() cursor.execute(f"SELECT COUNT(*) FROM Forecast WHERE LocationID={owm_id}") total_rows = cursor.fetchall()[0][0] print(f"{total_rows} total forecasts") print(f"{len(rows)} locations updated") connection.close() def wind_format(speed, direction): """Converts a wind speed and direction into a string formatted for user display. Args: speed: wind speed direction: window direction (in degrees: 0 is north, 90 is east, etc.) Returns: A string containing the speed and direction, such as "25 NW". """ wind = str(int(speed)) + " " if 22.5 < direction <= 67.5: wind += "NE" if 67.5 < direction <= 112.5: wind += "E" if 112.5 < direction <= 157.5: wind += "SE" if 157.5 < direction <= 202.5: wind += "S" if 202.5 < direction <= 247.5: wind += "SW" if 247.5 < direction <= 292.5: wind += "W" if 292.5 < direction <= 337.5: wind += "NW" else: wind += "N" return wind if __name__ == "__main__": main()
99dff7e2714dc096b6440f9dbf64ff56e90e5dcb
amymiao/connect-five
/connect_5.py
5,136
3.734375
4
''' AI Project: Connect 5 Rules: The game board will be a square board of length n where n is greater than or equal to 5 User will always start ''' from alphaBeta import * class Connect5(): game_board = [] game_board_size = 0 def __init__(self, game_board_size): self.game_board_size = game_board_size self.game_board = [[-1] * game_board_size for i in range(game_board_size)] ''' is_goal_state Parameter: last_move, game_board Returns True or False depending on whether last_move has connected five ''' def is_goal_state(self, last_move, game_board): row = 1 col = 1 right_dia = 1 left_dia = 1 value = game_board[last_move[0]][last_move[1]] i = last_move[0] + 1 #Check column win while i < (last_move[0]+5): if i>=self.game_board_size: break if game_board[i][last_move[1]]!= value: break col = col + 1 i = i + 1 i = last_move[0] - 1 while i > (last_move[0]-5): if i<=0: break if game_board[i][last_move[1]]!= value: break col = col + 1 i = i - 1 if col>=5: return True #Check row win i = last_move[1] + 1 while i < (last_move[1]+5): if i>=self.game_board_size: break if game_board[last_move[0]][i]!= value: break row = row + 1 i = i + 1 i = last_move[1] - 1 while i > (last_move[1]-5): if i<=0: break if game_board[last_move[0]][i]!= value: break row = row + 1 i = i - 1 if row>=5: return True #Check right diagonal win i = last_move[1] + 1 j = last_move[0] + 1 while i < (last_move[1]+5) and j < (last_move[0]+5): if i>=self.game_board_size or j>=self.game_board_size: break if game_board[j][i]!= value: break right_dia = right_dia + 1 i = i + 1 j = j + 1 i = last_move[1] - 1 j = last_move[0] - 1 while i > (last_move[1]-5) and j > (last_move[0]-5): if i<=0 or j<=0: break if game_board[j][i]!= value: break right_dia = right_dia + 1 i = i - 1 j = j - 1 if right_dia>=5: return True #Check left diagonal win i = last_move[1] + 1 j = last_move[0] - 1 while i < (last_move[1]+5) and j > (last_move[0]-5): if i>=self.game_board_size or j<=0: break if game_board[j][i]!= value: break left_dia = left_dia + 1 i = i + 1 j = j - 1 i = last_move[1] - 1 j = last_move[0] + 1 while i > (last_move[1]-5) and j < (last_move[0]+5): if i<=0 or j>=self.game_board_size: break if game_board[j][i]!= value: break left_dia = left_dia + 1 i = i - 1 j = j + 1 if left_dia>=5: return True return False def update_board(self, move_row, move_col, player): value = -1 if player == "user" or player == "player1": value = 1 else: value = 0 self.game_board[move_row][move_col] = value def is_valid(self, coor): if coor>=0 and coor<self.game_board_size: return True return False def is_valid_move(self, row, col): if self.is_valid(row) and self.is_valid(col): if self.game_board[row][col] == -1: return True return False def print_board(self): for row in self.game_board: print_row = "| " for r in row: if r == -1: print_row = print_row + "_" elif r == 0: print_row = print_row + "O" elif r == 1: print_row = print_row + "X" print_row = print_row + " | " print(print_row) print("") def print_user_board(self): n_row = 0 for row in self.game_board: print_row = "| " n_col = 0 for r in row: if r == -1: print_row = print_row + str(n_row) + "," + str(n_col) elif r == 0: print_row = print_row + " O " elif r == 1: print_row = print_row + " X " print_row = print_row + " | " n_col = n_col + 1 print(print_row) print("") n_row = n_row + 1
4bf30e0e13d2590adfdcbde3a9bf3f34d4bd6a7c
xiaohanghang/Nabu-MSSS
/nabu/neuralnetworks/models/linear.py
1,922
3.53125
4
'''@file linear.py contains the linear class''' import tensorflow as tf import model from nabu.neuralnetworks.components import layer class Linear(model.Model): '''A linear classifier''' def _get_outputs(self, inputs, input_seq_length, is_training): ''' Create the variables and do the forward computation Args: inputs: the inputs to the neural network, this is a list of [batch_size x time x ...] tensors input_seq_length: The sequence lengths of the input utterances, this is a [batch_size] vector is_training: whether or not the network is in training mode Returns: - output, which is a [batch_size x time x ...] tensors ''' #code not available for multiple inputs!! if len(inputs) > 1: raise 'The implementation of Linear expects 1 input and not %d' %len(inputs) else: inputs=inputs[0] with tf.variable_scope(self.scope): if is_training and float(self.conf['input_noise']) > 0: inputs = inputs + tf.random_normal( tf.shape(inputs), stddev=float(self.conf['input_noise'])) logits = inputs output = tf.contrib.layers.linear( inputs=logits, num_outputs=int(self.conf['output_dims'])) if 'activation_func' in self.conf and self.conf['activation_func']!='None': if self.conf['activation_func']=='tanh': output = tf.tanh(output) elif self.conf['activation_func']=='sigmoid': output = tf.sigmoid(output) else: raise 'Activation function %s not found' %(self.conf['activation_func']) #dropout is not recommended if is_training and float(self.conf['dropout']) < 1: output = tf.nn.dropout(output, float(self.conf['dropout'])) if 'last_only' in self.conf and self.conf['last_only']=='True': output = output[:,-1,:] output = tf.expand_dims(output,1) return output
9fc8e60744ef76905c0afc6c68c01654a0e557cb
BeatrizInGitHub/python-sci
/sesion_17/poo.4.py
592
3.5625
4
import math class Robot: def __init__(self): self.x = 0 self.y = 0 self.a = 0 def avanzar(self): d = 1 self.x += d * math.cos(self.a) self.y += d * math.sin(self.a) def girar_izq(self): da = 2 * math.pi / 36 self.a -= da def girar_der(self): da = 2 * math.pi / 36 self.a += da def __str__(self): return "%.2f %.2f (%.2f)" % (self.x, self.y, self.a) r = Robot() print r r.avanzar() print r r.girar_izq() r.avanzar() print r
110b05d0cf7cb14159818b9049fb5605e3eded50
fijila/PythonExperiments
/test/Closure1.py
965
4.0625
4
#!/bin/python3 import sys import os # Add the factory function implementation here def factory(n=0): def current(): return n def counter(): nonlocal n n+=1 return n return current,counter f_current,f_counter, = factory((2)) print(f_current()) print(f_counter()) #------------------- #def factory(n=0): #def current(): #return n #return current,counter #f_current, f_counter = factory(int(input())) #--------------------------------- if __name__ == "__main__": func_lst = [f_current, f_counter] res_lst = list() for func in func_lst: res_lst.append(func()) v = 'Hello' def f(): v = 'World' return v print(f()) print(v) def f(x): return 3*x def g(x): return 4*x print(f(g(2))) def outer(x, y): def inner1(): return x+y def inner2(z): return inner1() + z return inner2 f = outer(10, 25) print(f(15))
d3a159f9fee02a8da093a71c70ffc32fab228647
swarnanjali/lakshmi5
/begqu72.py
142
3.96875
4
ch=input() vowels={"a","e","i","o","u","A","E","I","O","U"} if any(char in vowels for char in ch): print("yes") else: print("no")
74669ef0faeb8ce659dd2e0bedde52d8b73bc24f
MartaSzuran/Python-for-the-Absolute-Beginner-M.Dawson
/Chapter 4/jumble_letters_2.py
2,351
4.09375
4
# program wymieszane litery # z krotki kilku słów losowo jest losowane jedno, a następnie miesza się jego litery # użytkownik zgaduje # może poprosić o podpowiedz # jeżeli rozwiąze z podpowiedzią ma mniejsza ilość punktów niz jak bez jej użycia import random # sekwencja słow do wyboru dużymi literami ponieważ ma być niezmienna WORDS = ("python", "babeczka", "ciastko", "bez", "gang") # wybor losowego slowa z krotki word = random.choice(WORDS) # tworzenie zmiennej w celu sprawdzenie poprawnosci zgadywania oraz ograniczenia warunku correct = word # tworze pusty lancuch w ktorej zapisze wymieszane litery jumble = "" # petla sie wykonuje az word nie bedzie puste while word: # generowanie losowej pozycji position = random.randrange(len(word)) # dodaje wylosowana litere do mojego wczesniej utworzonego pustego lancucha jumble += word[position] # print(jumble) # tworzenie nowego lancucha word bez tej jednej litery # wycinam do tej pozycji i po tej pozycji (aby wybierac z coraz mniejszej ilosci liter w slowie) word = word[:position] + word[(position + 1):] # print(word) # przywitanie gracza print(""" -------------------------- WYMIESZANE LITERY -------------------------- (Za każde słowo dobędziesz punkty równe podwojonej ilości liter) (Za wykorzystanie podpowiedzi zostanie odjęty jeden punkt) (Aby zakończyć zgadywanie naciśnij klawisz Enter) """) print("\nZgadnij jakie to słowo: ", jumble) # pobieranie odpowiedzi guess = input("Twoje odpowiedz: ") hints = 0 hints_used = 0 score = len(correct) * 2 # pytam do momentu aż nie będzie wlasciwej odp lub gracz nie nacisnie enter while guess != correct and guess != "": print("Niestety to nie to slowo.") hint = input("Chcesz podpowiedz? Naciśnij jakikolwiek klawisz lub wciśnij Enter\t") if hint and hints < len(correct): print("Litera", hints + 1, "w słowie to:", correct[hints]) hints += 1 hints_used += 1 if hints == len(correct): hints = 0 guess = input("Twoja odpowiedz: ") if guess == correct: print("Zgadza się!! Zgadłeś. Twój wynik to:\t", score - hints_used) print("Dziekuje za udział w grze.") input("\n\nAby zakończyc program, nacisnij klawisz Enter.")
0832aeacd4fdacfbd4925e90541e086e2e1e9add
danielwilstrop/pythonalgorithms
/radixsort.py
1,075
4.375
4
# Takes numbers in an input list. # Passes through each digit in those numbers, from least to most significant. # Looks at the values of those digits. # Buckets the input list according to those digits. # Renders the results from that bucketing. # Repeats this process until the list is sorted. def radix_sort(list): max_value = max(list) max_exponent = len(str(max_value)) being_sorted = list[:] for exponent in range(max_exponent): position = exponent + 1 index = -position digits = [[] for i in range(10)] for number in being_sorted: number_as_a_string = str(number) try: digit = number_as_a_string[index] except IndexError: digit = 0 digit = int(digit) digits[digit].append(number) being_sorted = [] for numeral in digits: being_sorted.extend(numeral) return being_sorted #Test list = [830, 921, 163, 373, 961, 559, 89, 199, 535, 959, 40, 641, 355, 689, 621, 183] print(radix_sort(list)) #Prints [40, 89, 163, 183, 199, 355, 373, 535, 559, 621, 641, 689, 830, 921, 959, 961]
03e6daba805291e8befc51a85ddc5d0018628a8c
homo-sapiens94/Bites_of_py
/86/rgb2hex.py
699
3.921875
4
def rgb_to_hex(rgb): """Receives (r, g, b) tuple, checks if each rgb int is within RGB boundaries (0, 255) and returns its converted hex, for example: Silver: input tuple = (192,192,192) -> output hex str = #C0C0C0""" code = '0123456789ABCDEF' lst = ['#'] error_string = f'Value not in range(0-255)' if any(value not in range(0, 256) for value in rgb): raise ValueError(error_string) else: for i in rgb: if i < 10: lst.extend(f'0{i}') else: first = i//16 second = int((i/16-first)*16) lst.extend(f'{code[first]}{code[second]}') return ''.join(lst)
bc73ae51b097a793d7f25b7fb62fa0eeddc24bf0
cgxabc/Online-Judge-Programming-Exercise
/Leetcode/ReverseLinkedList copy.py
661
4.21875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jan 1 22:04:35 2018 @author: apple """ """ Reverse a singly linked list. click to show more hints. Hint: A linked list can be reversed either iteratively or recursively. Could you implement both? """ #recursively(递归) def reverseList(head): new_head=None while head: p=head head=head.next p.next=new_head new_head=p return new_head #iteratively(迭代) def reverseList2(head): if not head or not head.next: return head p=head.next n=self.reverseList(p) head.next=None p.next=head return n
43cdbd05e1ef00d9426d2ba135e3ab19d3b09e8b
zhiyanfoo/courses-scripts
/rename.py
1,159
3.609375
4
import os # Copy and paste whatever prefix you want to remove to either di_prefix or fi_prefix. #If you want to remove directory prefix, UNCOMMENT THE LAST LINE. Then run the script. # File prefixes # 'MIT18_03S10_' # 'MIT18_02SC_' # 'MIT18_06SCF11_' # 'MIT6_041SCF13_' # 'MIT18_100BF10_' # 'MIT18_100CF12_' # Directory prefixes # 'session-' # Change the variables below to whatever prefix you want to remove fi_prefix = 'MIT24_241F09_' # di_prefix = "session-" def remove_prefix(prefix, typ="file"): if typ == "file": fi_or_dir = 2 elif typ == "directory": fi_or_dir = 1 else: print("invalid file type") exit() li = [i for i in os.walk(os.getcwd())] for di in li: root = di[0] print(root) for ele in di[fi_or_dir]: #print ele if ele[:len(prefix)] == prefix: new_name = os.path.join(root, ele[len(prefix):]) old_name = os.path.join(root, ele) print(old_name) print(new_name) os.rename(old_name, new_name) remove_prefix(fi_prefix) # remove_prefix(di_prefix, "directory")
ac236d52e1dd7fb9d8bad9342e9907ffbda5a6bc
PiJoules/Kalman-Filter
/test_voltmeter.py
2,227
3.84375
4
#!/usr/bin/env python # -*_ coding: utf-8 -*- import random import sys import numpy import matplotlib.pylab as pylab from kalman import KalmanFilterLinear class Voltmeter(object): """Measure voltage with a noisy voltmeter.""" def __init__(self, voltage, noise): self._voltage = voltage self._noise = noise @property def voltage(self): return self._voltage @property def noisy_voltage(self): return random.gauss(self.voltage, self._noise) def test(): """Test measuring a constant voltage from a voltmeter.""" pylab.clf() # Clear the plot steps = 60 # 1 b/c we are measuring a constant voltage source, so # the next expected voltage should be the exact same as the last. # Just multiply by 1. A = numpy.matrix([1]) # 1 b/c measuring voltage directly. # (The state is in the same units as the measurement.) H = numpy.matrix([1]) # 0 b/c no outside forces affect the state. B = numpy.matrix([0]) # Add some small random covariance. Q = numpy.matrix([0.00001]) # Random covariance from measurment. R = numpy.matrix([0.1]) # Initial state/covariance x_init = numpy.matrix([3]) P_init = numpy.matrix([1]) kf = KalmanFilterLinear(A, B, H, x_init, P_init, Q, R) # The voltage we expect is 1.25 V and we have given an initial guess # of 3 V. Let's see how good this filter is. voltmeter = Voltmeter(1.25, 0.25) measured_voltage = [] true_voltage = [] kalman_voltage = [] for i in xrange(steps): measured = voltmeter.noisy_voltage measured_voltage.append(measured) true_voltage.append(voltmeter.voltage) kalman_voltage.append(kf.state_estimate[0, 0]) kf.update(numpy.matrix([0]), numpy.matrix([measured])) pylab.plot(xrange(steps), measured_voltage, 'b', xrange(steps), true_voltage, 'r', xrange(steps), kalman_voltage, 'g') pylab.xlabel('Time') pylab.ylabel('Voltage') pylab.title('Voltage Measurement with Kalman Filter') pylab.legend(('measured', 'true voltage', 'kalman')) pylab.savefig('voltmeter.png') if __name__ == "__main__": sys.exit(test())
010fbdbecfffb9193e48cf6c9bce98c61fdd35a3
mychristopher/test
/pyfirstweek/第一课时/使用类实例化对象.py
991
4.125
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ 格式: 对象名 = 类名(参数列表) #对象名就是变量名 相当于函数,没有参数,小括号也不能省略 访问属性 格式:对象名.属性名 赋值:对象名.属性名 = 新值 访问方法 格式:对象名.方法名(参数列表) """ class Person(object): name = "" age = 0 height = 0 weight = 0 #方法的参数必须以self当第一个参数,self代表类的实例(某个对象) def run(self): print("run") def eat(self,food): print("eat" + food) #实例化一个对象 per = Person() print(per) per.name = "tom" per.age = 18 per.height = 180 per.weight = 55 print(per.name,per.age,per.height,per.weight) """ per.opendoor() per.fillEle() per.closeDoor() """ per.eat("apple") """ 构造函数:__init__() 在使用类创建对象的时候自动调用 如果不显示的写出构造函数,默认会自动添加一个空的构造函数 """
8345ded7120b46b7e534919ad5d1faa2fd2ac711
reincarne/python-codes
/xexpression_calculator.py
2,345
4.375
4
def calculate(expression): if isinstance(expression, int): return expression elif type(expression) is tuple or type(expression) is list: operator = expression[0] operands = expression[1:] if operator == 'add': return sum(calculate(operand) for operand in operands) elif operator == 'deduct': return calculate(operands[0]) - sum(calculate(operand) for operand in operands[1:]) elif operator == 'multiply': result = 1 for operand in operands: result *= calculate(operand) return result elif operator == 'divide': result = calculate(operands[0]) for operand in operands[1:]: try: result /= calculate(operand) except ZeroDivisionError: return 0 return result else: raise ValueError('Invalid operator: {}'.format(operator)) def main(): msg = """ Author: Alex Ledoskih --------------------- Enter your calculation based on operators available below: * and - add numbers. * deduct - subtract numbers. * multiply - multiply numbers. * divide - divide numbers. FORMAT: ['ACTION', #, #] Example: "['add',21,25]" Example: "['multiply',21,25]" Example: "['deduct',25,21]" Example: "['divide',20,10]" Example: "['multiply',2,3,['add',2,8]]" """ print(msg) user_input = input("Enter a variable: ") # we want to check the type of user input, as we need only integer, tuple or list try: # Check if the user input is an integer integer_input = int(user_input) print(calculate(integer_input)) except ValueError: # Check if the user input is a tuple try: tuple_input = tuple(eval(user_input)) print(calculate(tuple_input)) except: # Check if the user input is a list try: list_input = list(eval(user_input)) print(calculate(list_input)) except: # The input could not be converted to any of the expected types print("The user input is of unknown type.") if __name__ == '__main__': main()
ff6b6943210e3fd80e8f34562eecc42d8a7cd1a4
VithayaMoua/CSP1718
/DiceSim2.0.py
722
4.21875
4
import random def roll(sides=6): num_rolled = random.randint(1,sides) #generate random number between 1 and sides (default to 6) return num_rolled #return the random number def main(): sides = 6 #store the number 6 in a variable rolling = True #store True in a variable while rolling: roll_again = raw_input("Are you ready to roll? ENTER=Roll. Q=Quit. ") #generate message after a roll if roll_again.lower() !="q": # num_rolled = roll(sides) #generate number same as side print("You rolled a", num_rolled) #print random number rolled else: rolling = False #store False in a variable print("Thanks for playing.") main()
35b63d0054de47bff22fe06f8472cad99a49ea11
pedrolucas27/exercising-python
/list03/exer_13.py
397
3.859375
4
#Faça um programa que peça 10 números inteiros, calcule e mostre a quantidade de números pares # e a quantidade de números impares. pares = 0 impares = 0 for c in range(1,11): n = int(input("INFORME O NÚMERO {}:".format(c))) if n % 2 == 0: pares += 1 else: impares += 1 print("QUANTIDADE DE NÚMERO PARES:",pares) print("QUANTIDADE DE NÚMERO ÍMPARES:",impares)
4bf20b3025ea7b8fdfea6b27e9b0dc127e370675
smallwat3r/shhh
/tests/test_secret_encryption.py
965
3.53125
4
import unittest from cryptography.fernet import InvalidToken from shhh.api.encryption import Secret class TestSecretEncryption(unittest.TestCase): """Encryption testing.""" secret = "I'm a secret message." passphrase = "SuperSecret123" encrypted_text = ( b"nKir73XhgyXxjwYyCG-QHQABhqCAAAAAAF6rPvPYX7OYFZRTzy" b"PdIwvdo2SFwAN0VXrfosL54nGHr0MN1YtyoNjx4t5Y6058lFvDH" b"zsnv_Q1KaGFL6adJgLLVreOZ9kt5HpwnEe_Lod5Or85Ig==" ) def test_unique_encryption(self): encrypted = Secret(self.secret.encode(), self.passphrase).encrypt() self.assertNotEqual(encrypted, self.encrypted_text) def test_wrong_passphrase(self): with self.assertRaises(InvalidToken): Secret(self.encrypted_text, "wrongPassphrase").decrypt() def test_decryption(self): self.assertEqual(Secret(self.encrypted_text, self.passphrase).decrypt(), self.secret) if __name__ == "__main__": unittest.main()
2adf8c214ec522dd1e95c1896d4c1edcb740122a
jcravener/PythonWorkroom
/selDividingNumber.py
731
3.703125
4
def selfdividingnumbers(left: int, right: int): result = [] subresult = False for i in range(left, right+1): si = str(i) #--cast number to str if "0" not in si: #--ignore if there's a '0' in the number j = 0 while j < (len(si)): ij = int(si[j]) #--cast curent digit to int if i%ij !=0: #--if not divisable, bail to next number j = len(si) subresult = False else: subresult = True j += 1 if subresult == True: result.append(i) subresult = False return result print(selfdividingnumbers(0, 2222))
ba5a2e8068babbe0c00bf428394a1a8e72a15534
thamyresmfs/trabalho-extra
/facil.PY
180
3.734375
4
p = input("informe o preço") print(p) d = input("informe o desconto") print(d) vf = (float (p) * float(d))/100 print((p),"reais, com",(d),"%","de desconto, deu",(vf),"reais.")
08c8077c280217436812cc8ebabddeeb33c91d53
UltimoTG/Exercism
/python/pangram/pangram.py
183
3.640625
4
def is_pangram(sentence): alphabets = list(map(chr, range(97, 123))) for i in alphabets: if (i not in sentence.lower()): return False return True
b507265615760ff3a98ac50b944477359a46fde8
MifARION/Mif_project
/homework_two_mif.py
1,279
4.25
4
#Задание 1 number = float(input('Enter float number: ')) round_one = round(number, 0) round_two = round(number, 2) round_three = round(number, 5) print(f'{round_one} округление до 0, {round_two} округление до 2 цифр после запятой, {round_three} округление до 5 цифр после запятой') #Задание 2 list_one = [2, 4, 7, 9, 8, 5, 3] result = list_one.pop() print(result) #Задание 3 print(eval(input())) #Задание 4 my_list = [2, 4, 7, 9, 8, 5, 3] number_one = int(input()) number_two = int(input()) print(my_list[number_one:number_two]) #Задание 5 my_list = input() print(list(set(my_list))) #Задание 6 my_set_one = {1, 2, 5, 4, 7, 7, 21} my_set_two = {4, 4, 8, 5, 1, 1, 3} my_set_one.intersection(my_set_two) diff_set = my_set_one.difference(my_set_two) print(diff_set) #Задание 7 my_list_one = [1, 2, 5, 4, 7, 7, 21] my_list_two = [4, 4, 8, 5, 1, 1, 3] result = my_list_one + my_list_two print(list(set(result))) #Задание 8 my_list = [1, 2, 5, 4, 7, 7, 21] my_tuple = (4, 4, 8, 5, 1, 1, 3) my_list_two = list(my_tuple) my_list = set(my_list) my_list_two = set(my_list_two) result = my_list.intersection(my_list_two) print(result)
aedd01b1887a2f953d1036dc1e1a295d7e46c6a8
kylealbany/Pomodoro-Timer
/Pomodoro.py
3,650
3.734375
4
import time import Tkinter # Have to incorporate weekly tracker, load total pomodoros from file and reset weekly # Add in sounds for starting/completing work and breaks # Implement a pause function # Make executable GUI # In GUI include Start and pause/resume buttons, countdown timer, number of pomodoros, working/short/long break info # Make settings button/drop down where you can adjust the times # keybinds? # Maybe sleep every second and run if pause variable isn't true, button toggles variable between true and false # Keep track of completed pomodoros and goals completedpomodoros=0 totalpomodoros=0 pomodorogoal=30 # Working/break times for adjustment pomodorotime=25 shortbreaktime=5 longbreaktime=15 # Boolean variables for current state working=True shortbreak=False longbreak=False pause=False # Main method to run the program def run(): global completedpomodoros global totalpomodoros global pomodorogoal global pomodorotime global shortbreaktime global longbreaktime global working global shortbreak global longbreak global pause print "Starting work session..." print "So far, have completed " + str(completedpomodoros) + " of goal of " + str(pomodorogoal) + " pomodoros for the week" while 0==0: pomodorotimeleft=pomodorotime while working: print str(pomodorotimeleft) + " minutes left to work" time.sleep(15) pomodorotimeleft-=.25 if pomodorotimeleft==0: working=False completedpomodoros+=1 totalpomodoros+=1 pomodorosleft=pomodorogoal-totalpomodoros print "Pomodoro completed. " + str(completedpomodoros) + " pomodoros have been completed this session, for a total productive time of " + str((completedpomodoros*pomodorotime)) + " minutes" print str(totalpomodoros) + " pomodoros have been completed this week, for a total of " + str((totalpomodoros*pomodorotime)) + " productive minutes" print "Currently " + str((pomodorogoal-totalpomodoros)) + " pomodoros away from reaching this week's goal of " + str(pomodorogoal) + " pomodoros" if completedpomodoros%4==0: longbreak=True longbreaktimeleft=longbreaktime print "Taking a long break of " + str(longbreaktime) + " minutes" else: shortbreak=True shortbreaktimeleft=shortbreaktime print "Taking a short break of " + str(shortbreaktime) + " minutes" while shortbreak: print str(shortbreaktimeleft) + " minutes left on short break" time.sleep(15) shortbreaktimeleft-=.25 if shortbreaktimeleft==0: shortbreak=False working=True while longbreak: print str(longbreaktimeleft) + "minutes left on long break" time.sleep(15) longbreaktimeleft-=.25 if longbreaktimeleft==0: longbreak=False working=True run() ''' # Call this when pause=True to sleep until pause=False def pause(): global pause if pauseB["text"]=="Pause": pauseB.config(text="Resume") pause=False elif pauseB["text"]=="Resume": pauseB.config(text="Pause") pause=True # Making GUI window=Tkinter.Tk() window.title('Pomodoro Timer') startB = Tkinter.Button(window,text="Start", command = run) startB.pack() pauseB = Tkinter.Button(window,text="Pause", command = pause) pauseB.pack() window.mainloop() '''
88a7d1a1abffb3cf57b1884e154adcad1e234812
mridulrb/Basic-Python-Examples-for-Beginners
/Programs/MyPythonXII/Unit1/PyChap02/vowel.py
390
4.25
4
# File name: ...\\MyPythonXII\Unit1\PyChap02\vowel.py # Program to find total number of vowels in a string String = input("Enter a string: ") String = String.upper() Slen = len(String) VOWELS = "AEIOU" Ctr = 0 for ch in range(Slen): if String[ch] in VOWELS: Ctr += 1 if Ctr > 0: print("Total number of vowels are:", Ctr) else: print("No vowels in string")
bac11844ba0d34f1d3230ec4623550e7c2877818
florentinap/eGuv
/tema3/backend/domain.py
948
3.578125
4
from urllib.parse import urlparse def get_subdomain_name(url): """ Get the sub domain name (name.example.ro) :type url: str :rtype: str """ try: return urlparse(url).netloc except: return 'Cannot get sub domain name from %s. Make sure URL is correct.' % (url) def get_domain_name(url): """ Get the domain name (example.ro) :type url: str :rtype: str """ try: results = get_subdomain_name(url).split('.') return results[-2] + '.' + results[-1] except: return 'Cannot get domain name from %s. Make sure URL is correct.' % (url) def get_domain(url): """ Get domain (example) :type url: str :rtype: str """ try: result = get_subdomain_name(url).split('.') return result[-2] if result[-2] != 'gov' else result[-3] except: return 'Cannot get domain from %s. Make sure URL is correct.' % (url)
3dc0e8e2b15c3cf1a288e2f866ebc13c8635209f
EricMoura/Aprendendo-Python
/Exercícios de Introdução/Ex020.py
232
3.578125
4
import random a1 = input('Primeiro aluno: ') a2 = input('Segundo aluno: ') a3 = input('Terceiro aluno: ') a4 = input('Quarto aluno: ') lista = [a1,a2,a3,a4] random.shuffle(lista) print(f'Ordem da apresentação: {lista}')
7acece58b8cd043d9a83dce7bffd7196ade8f5c8
kampanella0o/python_basic
/lesson8/dict_methods.py
892
3.75
4
a = {'short': 'dict', 'long': 'dictionary'} #clear - clears the dictionary # a.clear() # print(a) #copy - copies dictionary # b = a.copy() # print(b) # b = dict(a) # print(b) #get - get value by key. First parameter is key, the second is default value ("None" by default) # print(a['long']) # print(a.get('long')) # print(a.get('longasdasdafsa')) # print(a.get('longasdasdafsa', "DEFAULT VALUe")) #pop - deletes item by key, returns value # var = a.pop("short") # print(var) # print(a) #popitem - deletes last item, returns pair key:value # var = a.popitem() # print(var, type(var)) #update - appends pairs key:value to dictionary b = {'new key': 'new value', 'asd': 'agads2dwa'} a.update(b) print(a) #items() keys() values() - to iterate the dictionary for item in a.keys(): print(item) for item in a.values(): print(item) for key, value in a.items(): print(key, value)
2c1364d4d5c247f80112598ed4006ba6fd32d0f2
iliachigogidze/Python
/Cormen/Chapter2/day6/take3/with_imports_sum_of_two_numbers.py
578
3.984375
4
from Chapter2.day4.binary_search import main as binary_search from Chapter2.day3.merge_sort import main as merge_sort def main(numbers:list, target_value:int) -> bool: print(f'Find {target_value} in {numbers}') sorted_numbers = merge_sort(numbers) for i in range(2, len(numbers)+1): indices = sorted_numbers[:i] number_to_search = target_value - indices[-1] list_for_search = indices[:-1] if binary_search(list_for_search, number_to_search): return True return False print('Answer is: ', main([1,5,1,2,3,6,-2],0))
54a05c194227dfa49720fce153ace4502f3f6537
Gokul58/python-program
/armstrong.py
192
3.828125
4
n = int(input("enter the number")) t = n r = 0 while(n>0) : a = n % 10 r = r+a*a*a n = n//10 if(r==t): print("armstrong number") else: print("not a armstrong number")
c07e37ea841d7acd62fee3246b9e967fbe15437f
sdcoffey/leetcode-solutions
/valid_number/tests/valid_number_test.py
864
3.59375
4
import unittest from valid_number import Solution class TestValidNumber(unittest.TestCase): def testValidNumber(self): table = { '0': True, ' 0.1 ': True, 'abc': False, '1 a': False, '2e10': True, '.1': True, '-1': True, '3.': True, '2e0': True, '-1.': True, '': False, ' ': False, '46.e3': True, '.2e81': True, 'e9': False, ' 005047e+6': True, } s = Solution() for input, expected in table.iteritems(): output = s.isNumber(input) self.assertEquals(expected, output, 'Input: {}, expected: {}, got: {}'.format(input, expected, output))
0067e653cc27c666a7a611ad1916f5582ad717b7
green-fox-academy/andrasnyarai
/week-02/d01/odd_even.py
236
4.34375
4
# Write a program that reads a number form the standard input, # Than prints "Odd" if the number is odd, or "Even" it it is even. a = input("Insert number here: ") if int(a) % 2 == 0: print("Even") if int(a) % 2 > 0: print("Odd")
ad4944a08f1b9253332a5ed10911b1876352bd47
axd8911/Leetcode
/mianshi_prep/tracyAMZ/1SearchIn2D_Optimized.py
499
3.625
4
class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False d1 = len(matrix)-1 d2 = 0 while d1>=0 and d2<len(matrix[0]): if matrix[d1][d2] == target: return True if matrix[d1][d2] < target: d2 += 1 else: d1 -= 1 return False
336609775f6d6d74bbb995eabcefba1d9e1b4aaf
tbjohnston/itila
/Hamming Encode 7 4 v3.py
6,240
3.71875
4
# Implement Hamming code algorithms in Python using NumPy # # Begun 29 Dec 2012 # Modified 16 Jan 2013 # Modified 17 Jan 2013 - add syndec, better output # Modified 18 Jan 2013 - use boolean operators # Modified 20 Jan 2013 - clean up m2mult # # This version does right multiplication -> t = G(T)s, where # G is the generator matrix of the code import numpy as np import operator def m2mult(a,b): """ modulo-2 multiplication of two boolean arrays """ return np.mod(np.dot(a.astype('u1'), b), 2).astype(bool) def syndec(h, r): """ syndrome decoding of message r using parity check matrix H """ # Syndrome to bit flip matrix synbitflip = np.array([[0],[6],[5],[3],[4],[0],[1],[2]]) w = r z = m2mult(h,r) # Determine syndrome zval = z[0,0]*2**2 + z[1,0]*2**1 + z[2,0]*2**0 if zval > 0: # there is an error bitf = synbitflip[zval,0] # find the bit to flip w[bitf,0] = w[bitf,0] ^ 1 # flip the appropriate bit return w # Our array G is [I4 P] where P is the parity matrix i4 = np.identity(4, dtype=bool) p = np.array([[1,0,1], [1,1,0], [1,1,1], [0,1,1]], dtype=bool) g = np.hstack((i4, p)) gt = g.transpose() # s is column vectors of all possible codewords s = np.array([[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1], [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1], [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]], dtype=bool) print "Matrix s - all the possible sources" print s.view(np.int8), "\n" t = m2mult(gt, s) print "Matrix t - all the codewords" print t.view(np.int8), "\n" qz = np.zeros([4,3]) q = np.hstack((i4,qz)) # Our array H = [-P I3], but -P = P in binary, so H = [P I3] # Need to transpose p h = np.hstack((p.transpose(), np.identity(3, dtype=bool))) sbz = m2mult(h,gt) print "Evaluation of the 3 x 4 matrix H G^T" print sbz.view(np.int8), "\n" # let y be the codeword received # if Hy = 0, then what we received is a valid code word, no changes # if Hy != 0, then Hy is the syndrome of the vector y, and has values # 001, 010, ... 111 (1, 2, ..., 7). Based on this number, we know which # bit to flip # Exercise 1.5 rt = np.array([[1,1,0,1,0,1,1], [0,1,1,0,1,1,0], [0,1,0,0,1,1,1], [1,1,1,1,1,1,1]], dtype=bool) r = rt.transpose() for l in range(0, r.shape[1]): m = r[:,l] # get a slice of r print "Received message r \n", "", m.view(np.int8) m = m[:,np.newaxis] # convert to columnar form w = syndec(h,m) # remove the noise from the transmission z = m2mult(q,w) # decode w = w.transpose() z = z.transpose() print "After noise removed \n", w.view(np.int8) print "Message \n", z.view(np.int8), "\n" # Exercise 1.8 show that whenever two or more bits are flipped in a single # block, there is a block decoding error - in other words, that any # corruption is not confined to the parity bits. # Not feeling clever today, so will brute force it. # But note with 2+ errors in r1, ... , r4 then there is a block error # So consider cases with 0 or 1 errors in r1, ..., r4 # and 1 to 3 errors (minimum total 2) in r5, r6, r7 # two errors in parity bits n = np.array([[0],[0],[0],[0],[1],[1],[0]], dtype=bool) n = np.hstack((n,np.array([[0],[0],[0],[0],[1],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[0],[0],[0],[1],[1]], dtype=bool))) # one error in message, one in parity n = np.hstack((n,np.array([[1],[0],[0],[0],[1],[0],[0]], dtype=bool))) n = np.hstack((n,np.array([[1],[0],[0],[0],[0],[1],[0]], dtype=bool))) n = np.hstack((n,np.array([[1],[0],[0],[0],[0],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[1],[0],[0],[1],[0],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[1],[0],[0],[0],[1],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[1],[0],[0],[0],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[1],[0],[1],[0],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[1],[0],[0],[1],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[1],[0],[0],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[0],[1],[1],[0],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[0],[1],[0],[1],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[0],[1],[0],[0],[1]], dtype=bool))) # three errors in parity bits n = np.hstack((n,np.array([[0],[0],[0],[0],[1],[1],[1]], dtype=bool))) # one error in message, two in parity n = np.hstack((n,np.array([[1],[0],[0],[0],[1],[1],[0]], dtype=bool))) n = np.hstack((n,np.array([[1],[0],[0],[0],[1],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[1],[0],[0],[0],[0],[1],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[1],[0],[0],[1],[1],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[1],[0],[0],[1],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[1],[0],[0],[0],[1],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[1],[0],[1],[1],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[1],[0],[1],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[1],[0],[0],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[0],[1],[1],[1],[0]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[0],[1],[1],[0],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[0],[1],[0],[1],[1]], dtype=bool))) # one error in message, three in parity n = np.hstack((n,np.array([[1],[0],[0],[0],[1],[1],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[1],[0],[0],[1],[1],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[1],[0],[1],[1],[1]], dtype=bool))) n = np.hstack((n,np.array([[0],[0],[0],[1],[1],[1],[1]], dtype=bool))) # 32 different errors for i in range(0, t.shape[1]): t1 = t[0:4,i] t1 = t1[:,np.newaxis] for j in range(0, n.shape[1]): r1 = np.logical_xor(t[:,i],n[:,j]) # apply noise r1 = r1[:,np.newaxis] # transpose w = syndec(h,r1) # attempt to remove noise z = m2mult(q,w) # decode if np.array_equal(t1,z): print "Error: %i in T and %i in N" % (i, j)
ed75cb8163c30157788555ab727a48e7597ec210
samarxie/Python-Machine-Learning-Homework
/20171021/kimmyzhang_20171021_01.py
646
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Kimmyzhang @Email: 902227553.com @File: kimmyzhang_20171021_01.py @Time: 2017/10/21 21:49 """ def jump_step_by_recursion(n): if n == 1 or n == 2: return n else: return jump_step_by_recursion(n - 1) + jump_step_by_recursion(n - 2) def jump_step_by_iteration(n): if n == 1 or n == 2: return n else: a1, a2 = 1, 2 for _ in range(n - 2): a1, a2 = a2, a1 + a2 return a2 if __name__ == '__main__': step_num = 100 total_times = jump_step_by_iteration(step_num) print(total_times)
6bfff2d988cea9823dd6a6167aea5df8cb84e4ef
morganbarlow/bottegaHomework
/python/feb18.py
1,881
3.984375
4
# - Build 2 python classes. # - One class must inherit from the other. # - At least one class must have a __init__ constructor function. # - At least one class must have a __str__ function. # - At least one class must have a __repr__ function. # - Between your two classes, you must have at least 5 instance attributes, and 1 class attribute. # - Between your two classes, you must have at least 3 instance methods (not including __init__, __str__, or __repr__) # - One method must use polymorphism. our_states={ 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' } our_territories = { 'American Samoa', 'District of Columbia', 'Guam', 'Northern Marianas Islands', 'Puerto Rico', 'Virgin Islands', } class States: def __init__(self,states): self.states = states def state (states): for state in states: if states in our_states: return (f'Yes, {states} is in the United States.') else: return (f'No, {states} is not a state.') # class Territories(States): def territory (territories): for territory in territories: if territory in our_territories: return f'Yes, {territories} is a United States territory!' print(States('Idaho')) print(States('Jess'))
9a00878230dce1f73c66ae529c5212c8da7cc59a
alexandraback/datacollection
/solutions_5751500831719424_0/Python/MrDubious/problem_a.py
2,684
3.59375
4
#!/usr/bin/python import sys, os, copy class TestCase: def __init__(self, strings): self.strings = strings def __repr__(self): return str(self.strings) def remove_repeats(self, string): new_str = '' for char in string: if len(new_str) > 0 and char == new_str[-1]: continue new_str += char return new_str def min_moves_for_letter(self, letter_freqs): letter_freqs.sort() num_moves = 0 median = letter_freqs[len(letter_freqs)/2] for letter_freq in letter_freqs: num_moves += abs(median - letter_freq) return num_moves def get_freq_list(self, string, nonrepeating_len): letter_list = [0]*nonrepeating_len prev_char = string[0] prev_ind = 0 letter_ind = 0 count = 1 for i in range(1, len(string)): if prev_char != string[i]: letter_list[letter_ind] = count #i - prev_ind prev_ind = i prev_char = string[i] count = 1 letter_ind += 1 else: count +=1 letter_list[-1] = count return letter_list def result(self): # Fegla wins if the non-repeating strings are not the same nonrepeating_str = self.remove_repeats(self.strings[0]) for string in self.strings[1:]: tmp_nonrepeating_str = self.remove_repeats(string) if tmp_nonrepeating_str != nonrepeating_str: return "Fegla Won" # Otherwise, compute min distance min_moves = 0 string_letter_freqs = [] for string in self.strings: string_letter_freqs.append(self.get_freq_list(string, len(nonrepeating_str))) for i in range(len(nonrepeating_str)): letter_freqs = [] for string_letter_freq in string_letter_freqs: letter_freqs.append(string_letter_freq[i]) min_moves += self.min_moves_for_letter(letter_freqs) return str(min_moves) def read_test_cases(input_filename): test_cases = [] with open(input_filename) as input_file: lines = input_file.read().split("\n") num_test_cases = lines[0] i = 1 while i < len(lines): if len(lines[i].replace(" ", '')) == 0: i += 1 continue num_strings = int(lines[i]) i += 1 strings = [] for j in range(i, i + num_strings): strings.append(lines[j]) test_cases.append(TestCase(strings)) i += num_strings return test_cases def usage(): print "Usage: problem_a.py input_file" def main(): if len(sys.argv) != 2: usage() sys.exit(1) input_filename = os.path.abspath(sys.argv[1]) test_cases = read_test_cases(input_filename) for i, test_case in enumerate(test_cases): print "Case #%d: %s" % (i+1, test_case.result()) if __name__ == "__main__": main()
f8fd0fc8e0f5fd25f0596c452ea543942e93db74
mrmukto/Python-Practise
/debugging.py
105
3.515625
4
def add(*y): sum = 0 for num in y: sum = sum + num return sum print(add(10,20))
944ede72f7ee18dd97d0712c409cfea502a3f92c
Lisss13/function
/python/1.py
1,023
3.984375
4
# замыкание # def foo (x): # def doo(y): # return x + y # return doo # # a = foo(5) # # print(a(2), a(10)) # ################################################################ # def f (x = 0): # def ff(*array): # array = [c * x for c in array] # return array # return ff # # # plus = f(10) # # print(plus(1,2,3,4,5,6,7)) ########################################################################## # # второй вариант замыкания # n = 3 # def foo( k, mul = n ): # return mul * k # # n = 7 # print( foo( 3 ) ) # n = 13 # print( foo( 5 ) ) ############################################## # псевдо случайные числа # реализовать ########################################################################## # карринг def spam( x, y ): print( 'param1 = {0}, param2 = {1}'.format( x, y ) ) def spam2( x ) : def new_spam( y ) : return spam( x, y ) return new_spam spam2( 2 )( 3 )
63d934310b55f2da71aa5dcfd189668f34f478f1
pdhhiep/Computation_using_Python
/bvec/bvec_add.py
2,697
4.25
4
#!/usr/bin/env python def bvec_add ( n, bvec1, bvec2 ): #*****************************************************************************80 # ## BVEC_ADD adds two binary vectors. # # Discussion: # # A BVEC is an integer vector of binary digits, intended to # represent an integer. BVEC(1) is the units digit, BVEC(N-1) # is the coefficient of 2^(N-2), and BVEC(N) contains sign # information. It is 0 if the number is positive, and 1 if # the number is negative. # # Example: # # N = 4 # # BVEC1 dec BVEC2 dec BVEC3 dec # ------- --- ------- --- ------- --- # 1 0 0 0 1 1 1 0 0 3 0 0 1 0 4 # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 December 2014 # # Author: # # John Burkardt # # Parameters: # # Input, integer N, the length of the vectors. # # Input, integer BVEC1(N), BVEC2(N), the vectors to be added. # # Output, integer BVEC3(N), the sum of the two input vectors. # # Output, logical OVERFLOW, is true if the sum overflows. # import numpy as np from bvec_print import bvec_print base = 2 overflow = False bvec3 = np.zeros ( n, dtype = np.int32 ) for i in range ( 0, n ): bvec3[i] = bvec1[i] + bvec2[i] for i in range ( 0, n ): while ( base <= bvec3[i] ): bvec3[i] = bvec3[i] - base if ( i < n - 1 ): bvec3[i+1] = bvec3[i+1] + 1 else: overflow = True return bvec3, overflow def bvec_add_test ( ): #*****************************************************************************80 # ## BVEC_ADD_TEST tests BVEC_ADD. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 December 2014 # # Author: # # John Burkardt # from bvec_to_i4 import bvec_to_i4 from i4_to_bvec import i4_to_bvec from i4_uniform_ab import i4_uniform_ab n = 10 seed = 123456789 test_num = 10 print '' print 'BVEC_ADD_TEST' print ' BVEC_ADD adds binary vectors representing integers;' print '' print ' I J K = I + J Kb = Ib + Jb' print '' for test in range ( 0, test_num ): i, seed = i4_uniform_ab ( -100, 100, seed ) j, seed = i4_uniform_ab ( -100, 100, seed ) print ' %8d %8d' % ( i, j ), k = i + j print ' %8d' % ( k ), bvec1 = i4_to_bvec ( i, n ) bvec2 = i4_to_bvec ( j, n ) bvec3, overflow = bvec_add ( n, bvec1, bvec2 ) k = bvec_to_i4 ( n, bvec3 ) print ' %8d' % ( k ) print '' print 'BVEC_ADD_TEST:' print ' Normal end of execution.' return if ( __name__ == '__main__' ): from timestamp import timestamp timestamp ( ) bvec_add_test ( ) timestamp ( )
cc4586fc69ce57317aa2a78f39159a762dc6bcbd
nbvc1003/python
/ch02/ex10.py
314
3.8125
4
num1 = 12 num2 = 3.567 s1 = "성공" # 사칙연산 결과를 출력 print("%d + %0.2f = %0.2f, %s"%(num1, num2, num1+num2, s1)) print("%d - %0.2f = %0.2f, %s"%(num1, num2, num1-num2, s1)) print("%d * %0.2f = %0.2f, %s"%(num1, num2, num1*num2, s1)) print("%d / %0.2f = %0.2f, %s"%(num1, num2, num1/num2, s1))
071dbb79685689db1613ef88e6437e9bcbb68c36
junyechen/PAT-Advanced-Level-Practice
/1042 Shuffling Machine.py
2,733
4.09375
4
""" Shuffling is a procedure used to randomize a deck of playing cards. Because standard shuffling techniques are seen as weak, and in order to avoid "inside jobs" where employees collaborate with gamblers by performing inadequate shuffles, many casinos employ automatic shuffling machines. Your task is to simulate a shuffling machine. The machine shuffles a deck of 54 cards according to a given random order and repeats for a given number of times. It is assumed that the initial status of a card deck is in the following order: S1, S2, ..., S13, H1, H2, ..., H13, C1, C2, ..., C13, D1, D2, ..., D13, J1, J2 where "S" stands for "Spade", "H" for "Heart", "C" for "Club", "D" for "Diamond", and "J" for "Joker". A given order is a permutation of distinct integers in [1, 54]. If the number at the i-th position is j, it means to move the card from position i to position j. For example, suppose we only have 5 cards: S3, H5, C1, D13 and J2. Given a shuffling order {4, 2, 5, 3, 1}, the result will be: J2, H5, D13, S3, C1. If we are to repeat the shuffling again, the result will be: C1, H5, S3, J2, D13. Input Specification: Each input file contains one test case. For each case, the first line contains a positive integer K (≤20) which is the number of repeat times. Then the next line contains the given order. All the numbers in a line are separated by a space. Output Specification: For each test case, print the shuffling results in one line. All the cards are separated by a space, and there must be no extra space at the end of the line. Sample Input: 2 36 52 37 38 3 39 40 53 54 41 11 12 13 42 43 44 2 4 23 24 25 26 27 6 7 8 48 49 50 51 9 10 14 15 16 5 17 18 19 1 20 21 22 28 29 30 31 32 33 34 35 45 46 47 Sample Output: S7 C11 C10 C12 S1 H7 H8 H9 D8 D9 S11 S12 S13 D10 D11 D12 S3 S4 S6 S10 H1 H2 C13 D2 D3 D4 H6 H3 D13 J1 J2 C1 C2 C3 C4 D1 S5 H5 H11 H12 C6 C7 C8 C9 S2 S8 S9 H10 D5 D6 D7 H4 H13 C5 """ ############################################ """ 非常简单,一次通过。 通过模拟重复即可。 另一种想法是通过矩阵相乘,但是在当前场景下过于复杂 """ ############################################ k = int(input()) c = [''] * 55 for i in range(1, 14): c[i] = 'S' + str(i) for i in range(14, 27): c[i] = 'H' + str(i - 13) for i in range(27, 40): c[i] = 'C' + str(i - 26) for i in range(40, 53): c[i] = 'D' + str(i - 39) for i in range(53, 55): c[i] = 'J' + str(i - 52) card = [_ for _ in range(55)] order = [int(_) for _ in input().split()] order.insert(0, 0) for _ in range(k): temp = card.copy() for i in range(1, 55): temp[order[i]] = card[i] card = temp.copy() for i in card[1:54]: print(c[i], end=' ') print(c[card[-1]])
31e6e9e69cbb37181a63030a6cd705b35308c74d
MaksymKorolyuk/LITS
/test.py
510
3.578125
4
# print('\n'.join([''.join([('Love'[(x-y) % len('Love')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)])) # def fibonacci(x): # if x < 2: return 1 # return (fibonacci(x - 2) + fibonacci(x - 1)) # # # def factorial(x): # if x < 2: return 1 # return (x * factorial(x - 1)) # # # def main(): # funcs = [fibonacci, factorial] # n = 10 # for i in range(len(funcs)): # print(funcs[i](n)) # # # main()
5d6ba773208965b9e04e32b4ab1fa31d3b432974
rcas99/BeautifulPatternsMIT
/day2/for_loop7.py
422
3.859375
4
""" Conditionals programming exercises For loop """ x = int(input("Escoge un numero positivo 'x': ")) y = int(input("Escoge un numero positivo 'y' que sera el tope de la iteracion: ")) print("La serie del 0 al 50 con saltos 'x' es:") for number in range(0, 50): if number % 5 == 0: print("El numero '{0}' es multiplo de 5".format(number)) else: print(number) if number == y: break
a1acedd55ae57e579110d787922f4fe80ecedd19
sivant/algorithms
/danidin.py
2,751
3.5
4
import random class PeopleSet: def __init__(self, size, force_danidin=False): self.size = size self.familiarity_matrix = [[False for i in range(size)] for i in range(size)] break_point = random.random() for i in range(size): for j in range(size): if random.random() > break_point: self.familiarity_matrix[i][j] = True if force_danidin: danidin = random.randrange(size) for i in range(size): self.familiarity_matrix[danidin][i] = True self.familiarity_matrix[i][danidin] = False print('Danidin is {}'.format(danidin+1)) self.call_count = 0 def find_danidin(self): for i in range(self.size): burned = False for j in range(self.size): if (j != i) and ((not self.familiarity_matrix[i][j]) or self.familiarity_matrix[j][i]): burned = True break if not burned: return i + 1 return None def familiarity(self, i, j): self.call_count += 1 return self.familiarity_matrix[i-1][j-1] def number_of_familiarity_calls(self): return self.call_count def main(): # Create the list of people, choose the size, and choose if you want to have a "danidin" in the list. # If 'force_danidin=True' - there will be a "danidin" person. # If 'force_danidin=False' - all values are random, so there may or may not be a "danidin" person. people = PeopleSet(size=1000, force_danidin=True) candidate = 1 next = 2 while next <= 1000: check = people.familiarity(candidate, next) if not check: candidate = next next += 1 check_dan = True for i in range(1, 1001): if not people.familiarity(candidate, i) and candidate != i: check_dan = False break if people.familiarity(i, candidate) and candidate != i: check_dan = False break num = people.number_of_familiarity_calls() if not check_dan: print("There is no Danidin!") else: print("The number of the Danidin: " + str(candidate)) print("Number of calls: " + str(num)) # Note that you need to use the method people.familiarity() to check if i knows j. (Remember that for 1000 people, i and j should be between 1-1000, not 0-999) # After you're done, you can call people.number_of_familiarity_calls() to see how many times people.familiarity() was called. # You can also call people.find_danidin() to see the right answer. That function returns the number of "danidin" person, or None if no "danidin" exists. main()
e2c380d0899447c065fa0460d9acefe785e875b4
ManasveeMittal/dropbox
/DataStructures/DataStructureAndAlgorithmicThinkingWithPython-master/chapter18divideandconquer/StockStrategyWithDivideAndConquer.py
2,062
3.765625
4
# Copyright (c) Dec 22, 2014 CareerMonk Publications and others. # E-Mail : info@careermonk.com # Creation Date : 2014-01-10 06:15:46 # Last modification : 2008-10-31 # by : Narasimha Karumanchi # Book Title : Data Structures And Algorithmic Thinking With Python # Warranty : This software is provided "as is" without any # warranty; without even the implied warranty of # merchantability or fitness for a particular purpose. def StockStrategy(A, start, stop): n = stop - start # edge case 1: start == stop: buy and sell immediately = no profit at all if n == 0: return 0, start, start if n == 1: return A[stop] - A[start], start, stop mid = start + n / 2 # the "divide" part in Divide & Conquer: try both halfs of the array maxProfit1, buy1, sell1 = StockStrategy(A, start, mid - 1) maxProfit2, buy2, sell2 = StockStrategy(A, mid, stop) maxProfitBuyIndex = start maxProfitBuyValue = A[start] for k in range(start + 1, mid): if A[k] < maxProfitBuyValue: maxProfitBuyValue = A[k] maxProfitBuyIndex = k maxProfitSellIndex = mid maxProfitSellValue = A[mid] for k in range(mid + 1, stop + 1): if A[k] > maxProfitSellValue: maxProfitSellValue = A[k] maxProfitSellIndex = k # those two points generate the maximum cross border profit maxProfitCrossBorder = maxProfitSellValue - maxProfitBuyValue # and now compare our three options and find the best one if maxProfit2 > maxProfit1: if maxProfitCrossBorder > maxProfit2: return maxProfitCrossBorder, maxProfitBuyIndex, maxProfitSellIndex else: return maxProfit2, buy2, sell2 else: if maxProfitCrossBorder > maxProfit1: return maxProfitCrossBorder, maxProfitBuyIndex, maxProfitSellIndex else: return maxProfit1, buy1, sell1 def StockStrategyWithDivideAndConquer(A): return StockStrategy(A, 0, len(A) - 1)
4cfb16fc13e2b8fe30a34c328f95d6495a540620
gshruti015/pyLab
/lab2/Shruti_Gupta_21.py
1,670
4.3125
4
#!/usr/bin/env python # coding: utf-8 # 1. Write a program that accepts a sentence from the keyboard, calculate and print out each unique character and its corresponding number of occurrence. Don’t count spaces. For example, if the input sentence is: the world is beautiful! , then the output should be the following: # Hint: # 1) use index to get a character in a string # 2) use dictionary to store characters and their corresponding values (# of appearance) a, 1 # ``` # !, 1 # b, 1 # e, 2 # d, 1 # f ,1 # i, 2 # h, 1 # l, 2 # o, 1 # s ,1 # r ,1 # u, 2 # t, 2 # w ,1 # ``` sentence = input() counts = dict() sentence=list(sentence.replace(" ", "")) for letter in sentence: counts[letter] = counts.get(letter,0)+1 print(counts) # 2. Write a program that can sort a given dictionary either by key or value. The program allows users to choose operations (1: sort by key, 2: sort by value). If the given dictionary is: d={'x': 7, 'y': 2, 'a': 3, 'm': 2}, the running output is following. # ``` # please select operation: (1: sort by key, 2: sort by value) 1 # a, 3 # m, 2 # x, 7 # y ,2 # please select operation: (1: sort by key, 2: sort by value) 2 # y ,2 # m, 2 # a, 3 # x, 7 # ``` choice = input("1: sort by key, 2: sort by value ") choice = int(choice) newd = dict() d={'x': 7, 'y': 2, 'a': 3, 'm': 2} d_keys = list(d.keys()) d_values = list(d.values()) if choice == 1: d_keys.sort() for k in d_keys: print(k, d[k]) else: d_values.sort() x = {} for k, v in d.items(): if v in x: x[v] += [k] #adding [k] means adding as a list , x[v] is adding as a key else: x[v] = [k] print(x)
362c9381627ded16af35b3e52e890fade50e7a57
lachlanpepperdene/CP1404_Practicals
/Prac03/asciiTable.py
554
4.09375
4
def get_number(number): if number > 10 and < 50: true get_number() def main(): value = (input("Enter character: ")) print("The ASCII code for", value, "is", ord(value), ) number = int(input("Enter number between 10 and 50: ")) while get_number(): print("The character for", number, "is", chr(number)) else: print("Invalid Number") main() # Enter a character:g # The ASCII code for g is 103 # Enter a number between 33 and 127: 100 # The character for 100 is d
4f9aa88539f5fbacda0182b1d6462c75df52d3db
alessandro-santini/TenNet
/TenNet/tools/HilbertCurve.py
10,840
3.859375
4
""" https://github.com/galtay/hilbertcurve This is a module to convert between one dimensional distance along a `Hilbert curve`_, :math:`h`, and n-dimensional points, :math:`(x_0, x_1, ... x_n)`. The two important parameters are :math:`n` (the number of dimensions, must be > 0) and :math:`p` (the number of iterations used in constructing the Hilbert curve, must be > 0). We consider an n-dimensional `hypercube`_ of side length :math:`2^p`. This hypercube contains :math:`2^{n p}` unit hypercubes (:math:`2^p` along each dimension). The number of unit hypercubes determine the possible discrete distances along the Hilbert curve (indexed from :math:`0` to :math:`2^{n p} - 1`). """ from typing import Iterable, List, Union import multiprocessing from multiprocessing import Pool import numpy as np def _binary_repr(num: int, width: int) -> str: """Return a binary string representation of `num` zero padded to `width` bits.""" return format(num, 'b').zfill(width) class HilbertCurve: def __init__( self, p: Union[int, float], n: Union[int, float], n_procs: int=0, ) -> None: """Initialize a hilbert curve with, Args: p (int or float): iterations to use in constructing the hilbert curve. if float, must satisfy p % 1 = 0 n (int or float): number of dimensions. if float must satisfy n % 1 = 0 n_procs (int): number of processes to use 0 = dont use multiprocessing -1 = use all available threads any other positive integer = number of processes to use """ if (p % 1) != 0: raise TypeError("p is not an integer and can not be converted") if (n % 1) != 0: raise TypeError("n is not an integer and can not be converted") if (n_procs % 1) != 0: raise TypeError("n_procs is not an integer and can not be converted") self.p = int(p) self.n = int(n) if self.p <= 0: raise ValueError('p must be > 0 (got p={} as input)'.format(p)) if self.n <= 0: raise ValueError('n must be > 0 (got n={} as input)'.format(n)) # minimum and maximum distance along curve self.min_h = 0 self.max_h = 2**(self.p * self.n) - 1 # minimum and maximum coordinate value in any dimension self.min_x = 0 self.max_x = 2**self.p - 1 # set n_procs n_procs = int(n_procs) if n_procs == -1: self.n_procs = multiprocessing.cpu_count() elif n_procs == 0: self.n_procs = 0 elif n_procs > 0: self.n_procs = n_procs else: raise ValueError( 'n_procs must be >= -1 (got n_procs={} as input)'.format(n_procs)) def _hilbert_integer_to_transpose(self, h: int) -> List[int]: """Store a hilbert integer (`h`) as its transpose (`x`). Args: h (int): integer distance along hilbert curve Returns: x (list): transpose of h (n components with values between 0 and 2**p-1) """ h_bit_str = _binary_repr(h, self.p*self.n) x = [int(h_bit_str[i::self.n], 2) for i in range(self.n)] return x def _transpose_to_hilbert_integer(self, x: Iterable[int]) -> int: """Restore a hilbert integer (`h`) from its transpose (`x`). Args: x (list): transpose of h (n components with values between 0 and 2**p-1) Returns: h (int): integer distance along hilbert curve """ x_bit_str = [_binary_repr(x[i], self.p) for i in range(self.n)] h = int(''.join([y[i] for i in range(self.p) for y in x_bit_str]), 2) return h def point_from_distance(self, distance: int) -> Iterable[int]: """Return a point in n-dimensional space given a distance along a hilbert curve. Args: distance (int): integer distance along hilbert curve Returns: point (iterable of ints): an n-dimensional vector of lengh n where each component value is between 0 and 2**p-1. """ x = self._hilbert_integer_to_transpose(int(distance)) z = 2 << (self.p-1) # Gray decode by H ^ (H/2) t = x[self.n-1] >> 1 for i in range(self.n-1, 0, -1): x[i] ^= x[i-1] x[0] ^= t # Undo excess work q = 2 while q != z: p = q - 1 for i in range(self.n-1, -1, -1): if x[i] & q: # invert x[0] ^= p else: # exchange t = (x[0] ^ x[i]) & p x[0] ^= t x[i] ^= t q <<= 1 return x def points_from_distances( self, distances: Iterable[int], match_type: bool=False, ) -> Iterable[Iterable[int]]: """Return points in n-dimensional space given distances along a hilbert curve. Args: distances (iterable of int): iterable of integer distances along hilbert curve match_type (bool): if True, make type(points) = type(distances) Returns: points (iterable of iterable of ints): an iterable of n-dimensional vectors where each vector has lengh n and component values between 0 and 2**p-1. if match_type=False will be list of lists else type(points) = type(distances) """ for ii, dist in enumerate(distances): if (dist % 1) != 0: raise TypeError( "all values in distances must be int or floats that are convertible to " "int but found distances[{}]={}".format(ii, dist)) if dist > self.max_h: raise ValueError( "all values in distances must be <= 2**(p*n)-1={} but found " "distances[{}]={} ".format(self.max_h, ii, dist)) if dist < self.min_h: raise ValueError( "all values in distances must be >= {} but found distances[{}]={} " "".format(self.min_h, ii, dist)) if self.n_procs == 0: points = [] for distance in distances: x = self.point_from_distance(distance) points.append(x) else: with Pool(self.n_procs) as p: points = p.map(self.point_from_distance, distances) if match_type: if isinstance(distances, np.ndarray): points = np.array(points, dtype=distances.dtype) else: target_type = type(distances) points = target_type([target_type(vec) for vec in points]) return points def distance_from_point(self, point: Iterable[int]) -> int: """Return distance along the hilbert curve for a given point. Args: point (iterable of ints): an n-dimensional vector where each component value is between 0 and 2**p-1. Returns: distance (int): integer distance along hilbert curve """ point = [int(el) for el in point] m = 1 << (self.p - 1) # Inverse undo excess work q = m while q > 1: p = q - 1 for i in range(self.n): if point[i] & q: point[0] ^= p else: t = (point[0] ^ point[i]) & p point[0] ^= t point[i] ^= t q >>= 1 # Gray encode for i in range(1, self.n): point[i] ^= point[i-1] t = 0 q = m while q > 1: if point[self.n-1] & q: t ^= q - 1 q >>= 1 for i in range(self.n): point[i] ^= t distance = self._transpose_to_hilbert_integer(point) return distance def distances_from_points( self, points: Iterable[Iterable[int]], match_type: bool=False, ) -> Iterable[int]: """Return distances along the hilbert curve for a given set of points. Args: points (iterable of iterable of ints): an iterable of n-dimensional vectors where each vector has lengh n and component values between 0 and 2**p-1. match_type (bool): if True, make type(distances) = type(points) Returns: distances (iterable of int): iterable of integer distances along hilbert curve the return type will match the type used for points. """ for ii, point in enumerate(points): if len(point) != self.n: raise ValueError( "all vectors in points must have length n={} " "but found points[{}]={}".format(self.n, ii, point)) if any(elx > self.max_x for elx in point): raise ValueError( "all coordinate values in all vectors in points must be <= 2**p-1={} " "but found points[{}]={}".format(self.max_x, ii, point)) if any(elx < self.min_x for elx in point): raise ValueError( "all coordinate values in all vectors in points must be > {} " "but found points[{}]={}".format(self.min_x, ii, point)) if any((elx % 1) != 0 for elx in point): raise TypeError( "all coordinate values in all vectors in points must be int or floats " "that are convertible to int but found points[{}]={}".format(ii, point)) if self.n_procs == 0: distances = [] for point in points: distance = self.distance_from_point(point) distances.append(distance) else: with Pool(self.n_procs) as p: distances = p.map(self.distance_from_point, points) if match_type: if isinstance(points, np.ndarray): distances = np.array(distances, dtype=points.dtype) else: target_type = type(points) distances = target_type(distances) return distances def __str__(self): return f"HilbertCruve(p={self.p}, n={self.n}, n_procs={self.n_procs})" def __repr__(self): return self.__str__() def HC_compute_config(p): hilbert_curve = HilbertCurve(p, 2) L = 2**(p) N = L**2 indexes = hilbert_curve.points_from_distances(np.arange(N),2) config = np.zeros((L,L),dtype=np.int) for i,index in enumerate(indexes): config[index[0],index[1]]=i return config
1186d2949fe41aebe310d37d6f403127990c3960
saipraneethyss/HackerRank_Codes
/calendarmod.py
146
3.65625
4
import calendar dateval = list(map(int,input().split())) print((calendar.day_name[calendar.weekday(dateval[2], dateval[0], dateval[1])]).upper())
4b025fb3cc0b097334cd2e81292f05e4acc0d650
stevestar888/leetcode-problems
/1431-kids_with_most_candy.py
1,565
3.890625
4
""" https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ Strat: For a given kid, we just have to see if their candies + extraCandies is the most (or equal to) all the other children's. The trick: the kid with the most candy (before extras are added) will always be the same. Therefore, find the max_candies and iterate through candies to see if kid + extraCandies ≥ max_candies. Speed: O(n) - 2 pass throughs, both O(n) Runtime: 8 ms, faster than 100% of Python online submissions for Kids With the Greatest Number of Candies. Memory Usage: 12.6 MB, less than 100.00% of Python online submissions for Kids With the Greatest Number of Candies. """ class Solution(object): def kidsWithCandies(self, candies, extraCandies): """ :type candies: List[int] :type extraCandies: int :rtype: List[bool] """ #find the max candies max_candy = -1 for candy in candies: if candy > max_candy: max_candy = candy max_candy = max(candies) #see if a given kid will have the most, after they receive the extra candy ans = [] for candy in candies: ans.append(candy + extraCandies >= max_candy) return ans # one liner haha def kidsWithCandies(self, candies, extraCandies): """ :type candies: List[int] :type extraCandies: int :rtype: List[bool] """ return [(candy + extraCandies >= max(candies)) for candy in candies]
bfa51ca3ff543d781b78398dd261b5f37b393ba8
M2401/P1
/loops/190720_lists/lr_odnomernie_spiski/13/13.2.py
813
3.921875
4
#13.2. Дан одномерный массив из 8 элементов. Заменить все элементы массива меньшие 15 их # удвоенными значениями. Вывести на экран монитора преобразованный массив. import random def cr(a): for i in range(8): a.append(random.randint(-15, 30)) def pr(a): for i in a: print(i, end=' ') def comp(a, b): i = 0 while i < 8: if a[i] < 15: a[i] = 2 * a[i] b.append(a[i]) i += 1 return b def main(): a = [] cr(a) pr(a) print() b = [] c = comp(a, b) if not c: print('в исходном списке нет элементов меньше 15') else: print(c) main()
e9448a063545847139eca4bf24a741ca2dfeca12
SpiritFryer/USACO
/numtri_recursive-commented-out-partially.py
3,287
3.578125
4
""" ID: seishin1 LANG: PYTHON3 TASK: numtri """ # Needs max_depth > 1. # Recursion depth exceeded for max_depth >= 998. def dfs_binary_tree(triangle, current_depth, current_index, max_depth, current_sum, max_sums): if current_depth == max_depth - 1: # print(' ' * current_depth, current_depth, current_index, 'Reached bottom, returning ', # current_sum + triangle[current_depth][current_index] + max( # triangle[current_depth + 1][current_index], # triangle[current_depth + 1][current_index + 1]) # ) return current_sum + triangle[current_depth][current_index] + max( triangle[current_depth + 1][current_index], triangle[current_depth + 1][current_index + 1] ) if max_sums[current_depth + 1][current_index] == -1: #print(' ' * current_depth, current_depth + 1, current_index, 'max_sums not found, calculating') max_sums[current_depth + 1][current_index] = \ dfs_binary_tree(triangle, current_depth + 1, current_index, max_depth, current_sum, max_sums) # else: # print(' ' * current_depth, current_depth + 1, current_index, 'available:', # max_sums[current_depth + 1][current_index]) if max_sums[current_depth + 1][current_index + 1] == -1: #print(' ' * current_depth, current_depth + 1, current_index + 1, 'max_sums not found, calculating') max_sums[current_depth + 1][current_index + 1] = \ dfs_binary_tree(triangle, current_depth + 1, current_index + 1, max_depth, current_sum, max_sums) # else: # print(' ' * current_depth, current_depth + 1, current_index + 1, 'available:', # max_sums[current_depth + 1][current_index + 1]) # print(' ' * current_depth, current_depth, current_index, 'Returning ', # max( # max_sums[current_depth + 1][current_index], # max_sums[current_depth + 1][current_index + 1] # )) return triangle[current_depth][current_index] + max( max_sums[current_depth + 1][current_index], max_sums[current_depth + 1][current_index + 1] ) fin = open('numtri.in', 'r') fout = open('numtri.out', 'w') n = int(fin.readline().strip()) rows = [list(map(int, line.split())) for line in fin] #print('\n'.join(' '.join(str(x) for x in row) for row in rows)) max_sums = [] for i in range(n): max_sums.append([-1] + [-1 for _ in range(i)]) #print(max_sums) if len(rows) == 1: max_sum = rows[0][0] else: #max_sum = dfs_binary_tree(rows, 0, 0, n - 1, 0, max_sums) max_sum = "whatever" #print('\n'.join(' '.join(str(x) for x in row) for row in max_sums)) max_sums2 = [] for i in range(n - 1): max_sums2.append([-1] + [-1 for _ in range(i)]) max_sums2.append([x for x in rows[-1]]) for i in range(len(rows) - 2, -1, -1): for j in range(len(rows[i])): max_sums2[i][j] = rows[i][j] + max(max_sums2[i + 1][j], max_sums2[i + 1][j + 1]) max_sum2 = max_sums2[0][0] print(max_sum) print(max_sum2) fout.write(str(max_sum) + '\n') fin.close() fout.close() # if(__name__ == '__main__'): # Local debug # import sys # import os # #print('type {}.out'.format(sys.argv[0].lstrip('.\').split('.')[0])) #Debug # os.system('type {}.out'.format(sys.argv[0].lstrip('.\').split('.')[0]))
5862340d3e5dccc969c45cb9b8866fbfc62f3a64
rafael1717y/repo-python
/treehouse_python/basico/13. sequences.py
438
4.03125
4
my_name = "Rafael" groceries = ['roast beef', 'cucumbers', 'lettuce', 'dog food'] for letter in my_name: print(letter) """ index = 1 for item in groceries: print(f'{index}.{item}') index+=1 """ # Enumerate for index, item in enumerate(groceries, 1): print(f'{index}.{item}') # Ranges - 3 argumentos # ranges excludem o valor de stop for i in range(0, 10, 1): print(i) for i in range(10): # default print(i)
787e2f567abf22bc07b8890daf8d0ca4fd676757
manutdmohit/mypythonexamples
/pythonexamples/findnumberofoccurencesofeachcharacterinstringdictionary.py
83
3.578125
4
word=input('Enter any string:') d={} for ch in word: d[ch]=d.get(ch,0)+1 print(d)
d1e5a4e261d513a0427a807ae8a0e86cc220fdfe
joestalker1/leetcode
/src/main/scala/common_lounge/Recursion.py
385
3.65625
4
def f(x, y): if y == 0: return 1 a = f(x, y // 2) if y % 2 == 0: return a * a else: return a * a * x def f1(x, y): if y == 0: return 1 if y == 1: return x a = f1(x, y // 2) if y % 2 == 0: return f1(x, y // 2) * f1(x, y // 2) else: return f1(x, y // 2) * f1(x, y // 2) * x print(f1(2, 5))
f2867e0033d487aa1dd8157230da44ec2cbf625d
amalshehu/Python-Introduction
/is_int.py
371
4.15625
4
# File: is_even.py # Purpose: To check a number is an integer or not # Programmer: Amal Shehu # Course: Codecademy # Date: Wednesday 31st August 2016, 05:50 PM x = raw_input("Enter a number :") def is_int(x): # if x - int(x) > 0: #failed if x % 1 == 0: return True else: return False
a8db26fcde80f2463a9146be7cf31159f11b8a03
thelsandroantunes/EST-UEA
/LPI/Listas/L2_LPI - repetição e condicionais/exe53.l2.py
593
3.734375
4
# Autor: Thelsandro Antunes # Data: 13/05/2017 # EST-UEA # Disciplina: LP1 # Professora: Elloa B. Guedes # 2 Lista de Exercicios (06/04/2015) # Questao 53: Escreva um algoritmo que leia 50 numeros e informe: # (a) O maior valor lido; # (b) O menor valor lido; # (c) A media dos valores lidos. from random import randint x=randint(1,1000) maior=0 menor=x soma = 0 for i in range(49): print(x) if(maior<x): maior=x if(menor>x): menor=x soma = soma + x x=randint(1,1000) print("maior: ",maior) print("menor: ",menor) print("media: ",soma/50)
60886328650bc204134170ed118da7c36e77198d
AndresCallejasG/holbertonschool-higher_level_programming
/0x02-python-import_modules/100-my_calculator.py
731
3.515625
4
#!/usr/bin/python3 if __name__ == "__main__": import sys from calculator_1 import mul, div, add, sub av = sys.argv argc = len(av) if argc != 4: print("Usage: ./100-my_calculator.py <a> <operator> <b>") exit(1) else: a = int(av[1]) b = int(av[3]) if av[2] == "*": print("{:d} * {:d} = {:d}".format(a, b, mul(a, b))) elif av[2] == "/": print("{:d} / {:d} = {:d}".format(a, b, div(a, b))) elif av[2] == "+": print("{:d} + {:d} = {:d}".format(a, b, add(a, b))) elif av[2] == "-": print("{:d} - {:d} = {:d}".format(a, b, sub(a, b))) else: print("Unknown operator. Available operators: +, -, * and /") exit(1)
51fd7c6964e3b2647f4d2047557b749d0b7aacea
jgartsu12/my_python_learning
/python_numbers/math_operators.py
1,101
4.21875
4
print('Addition') get_sum = 100 + 42 print(get_sum) # prints 142, an integer print('Subtraction') print(100 - 42.3) # prints 57.7;; integer and floats can work together print('Division') print(100 / 42.3) # prints 2.3640661938853281 print(100 / 42) # prints 2.380952380952381 print(100 / 38) # prints 2.631.... print('Floor Division') print(100 // 42) # prints 2 rounds down automatically for us \\ ** used for approx value that is an integer... not accurate for complex calculations print(100 // 38) # prints 2 rounds down to nearest whole number not like normal rounding print('Multiplication') print(100 * 42) # prints 4200 print('Modulus') # --> % prints the amount of times a number goes into a number to get the **REMAINDER** # use case odd vs even print(100 % 42) # prints 16 print(2 % 2) # prints 0 --> used to find if value is even or odd --> even numbers always have 0; odds always have 1 print(5 % 2) # pritns 1 print(25 % 2) # prints 1 print('Exponents') print(100 ** 42) # prints 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000
f3bab8931de0b2f203b5a25072dd277c69181336
SuchanRai/10_Question
/9th.py
148
4.0625
4
# to check the leap year year = int(input('enter the year')) if (year/4 == 0) & (year/100 != 0): print('LEAP YEAR') else: print('leap year')
f1135e62c905b285cbff21cb86188101b563840c
RagnvaldIV/AdventOfCode2020
/Day 3/part2.py
1,463
3.546875
4
# Open file and set up vars inputTxt = open("Day 3/input.txt", "r") # Read over file to get size of array lineLength = len(inputTxt.readline()) - 1 numOfLines = len(inputTxt.readlines()) + 1 slope = [[0 for i in range(lineLength)] for j in range(numOfLines)] position = 0 treeCount = [0, 0, 0, 0, 0] inputTxt.seek(0, 0) # Import input as array for row in range(numOfLines): line = inputTxt.readline() # print(line) for i in range(lineLength): slope[row][i] = line[i] # Iterate through rows, moving position # r1d1 for row in range(numOfLines): if(slope[row][position%lineLength] == '#'): treeCount[0] += 1 position += 1 # r3d1 position = 0 for row in range(numOfLines): if(slope[row][position%lineLength] == '#'): treeCount[1] += 1 position += 3 # r5d1 position = 0 for row in range(numOfLines): if(slope[row][position%lineLength] == '#'): treeCount[2] += 1 position += 5 # r7d1 position = 0 for row in range(numOfLines): if(slope[row][position%lineLength] == '#'): treeCount[3] += 1 position += 7 # r1d2 position = 0 skip = False for row in range(numOfLines): if not skip: if(slope[row][position%lineLength] == '#'): treeCount[4] += 1 position += 1 print(row) skip = not skip result = treeCount[0] * treeCount[1] * treeCount[2] * treeCount[3] * treeCount[4] print("Each run: " + str(treeCount)) print("Answer is " + str(result))
24e4d2bc5c51bedcee3ba0fbc54896273b096b93
LokiGizmo/pong
/main.py
2,822
3.640625
4
# simple bong python 3 # cridit @tokyoedtech # part 1 import turtle wn = turtle.Screen() wn.title('pong by gizmo') wn.bgcolor('black') wn.setup(width=800, height=600) wn.tracer(0) # score score_a = 0 score_b = 0 # paddle A paddle_a = turtle.Turtle() paddle_a.speed(0) paddle_a.shape('square') paddle_a.color('red') paddle_a.shapesize(stretch_wid=5, stretch_len=1) paddle_a.penup() paddle_a.goto(-350, 0) # paddle b paddle_b = turtle.Turtle() paddle_b.speed(0) paddle_b.shape('square') paddle_b.color('blue') paddle_b.shapesize(stretch_wid=5, stretch_len=1) paddle_b.penup() paddle_b.goto(+350, 0) # ball ball = turtle.Turtle() ball.speed(0) ball.shape('circle') ball.color('white') ball.penup() ball.goto(0, 0) ball.dx = .8 ball.dy = -.8 # Pen pen = turtle.Turtle() pen.speed(0) pen.color('green') pen.up() pen.hideturtle() pen.goto(0 , 260) pen.write('Player A: 0 Player B: 0 ', align='center' , font=('Courier', 24, 'normal')) # function def paddele_a_up(): y = paddle_a.ycor() y += 20 paddle_a.sety(y) def paddele_a_down(): y = paddle_a.ycor() y -= 20 paddle_a.sety(y) def paddele_b_up(): y = paddle_b.ycor() y += 20 paddle_b.sety(y) def paddele_b_down(): y = paddle_b.ycor() y -= 20 paddle_b.sety(y) # keybored binding wn.listen() wn.onkeypress(paddele_a_up, 'w') wn.onkeypress(paddele_a_down, 's') wn.onkeypress(paddele_b_up, 'Up') wn.onkeypress(paddele_b_down, 'Down') # Main game loop while True: wn.update() #move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # border checking if ball.ycor() > 290: ball.sety(290) ball.dy *= -.9 # winsound.PlaySound('' , winsound.SND_ASYNC) if ball.ycor() < -290: ball.sety(-290) ball.dy *= -.9 # winsound.PlaySound('' , winsound.SND_ASYNC) if ball.xcor() > 390: ball.goto(0, 0) ball.dx *= -.9 score_a += 1 pen.clear() pen.write('Player A: {} Player B: {} ' .format(score_a, score_b), align='center', font=('Courier', 24, 'normal')) if ball.xcor() < -390: ball.goto(0, 0) ball.dx *= -.9 score_b += 1 pen.clear() pen.write('Player A: {} Player B: {} '.format(score_a, score_b), align='center', font=('Courier', 24, 'normal')) # paddle and ball collisions if ball.xcor() > 340 and ball.xcor() < 350 and (ball.ycor() < paddle_b.ycor() + 50 and ball.ycor() > paddle_b.ycor() -50): ball.setx(340) ball.dx *= -1 # winsound.PlaySound('' , winsound.SND_ASYNC) if ball.xcor() < -340 and ball.xcor() > -350 and (ball.ycor() < paddle_a.ycor() + 50 and ball.ycor() > paddle_a.ycor() -50): ball.setx(-340) ball.dx *= -1 # winsound.PlaySound('' , winsound.SND_ASYNC)
62896e6f9a4169f6f3e952bff0d5b851de1c0661
MarkiMarki/bio-project
/src/executors/mark/my_databases.py
5,756
3.84375
4
#################### #################### #################### import sqlite3 def main(): db = sqlite3.connect('test.db') # connects to db in creats file db.row_factory = sqlite3.row # allows to specify how to return rows from curser db.execute('drop table if exists test') db.execute('create table test (t1 text, i1 int)') db.execute('drop table if exists test') db.execute('insert into test (t1. i1) values (?,?), ('one',1)) db.execute('insert into test (t1. i1) values (?,?), ('two',2)) db.execute('insert into test (t1. i1) values (?,?), ('three',3)) db.execute('insert into test (t1. i1) values (?,?), ('four',4)) db.commit() # curser = db.execute('select * from test order by t1') #can change t1 to i1 for row in curser: print(dict(row)) #print('This is the databases.py file') if __name__ == "__main__": main() ###################################### ### CRUD: the major four functions ### ###################################### def insert(db, row): #take a row, dict obj, passes the individual element to placeholders(=?, positional) in SQL db.execute('insert into test (t1, i1) values (?, ?)', (row['t1'], row['i1'])) db.commit() # use for everything that changes the db def retrieve(db, t1): # takes a key, select the entire row with sql, cursor = db.execute('select * from test where t1 = ?', (t1,)) return cursor.fetchone() # fetch one result def update(db, row): # execute with sql. passes a tuple from the tuple db.execute('update test set i1 = ? where t1 = ?', (row['i1'], row['t1'])) db.commit() def delete(db, t1): db.execute('delete from test where t1 = ?', (t1,)) db.commit() def disp_rows(db): cursor = db.execute('select * from test order by t1') for row in cursor: print(' {}: {}'.format(row['t1'], row['i1'])) def main(): db = sqlite3.connect('test.db') db.row_factory = sqlite3.Row print('Create table test') db.execute('drop table if exists test') db.execute('create table test ( t1 text, i1 int )') print('Create rows') insert(db, dict(t1 = 'one', i1 = 1)) ## just pass a dict insert(db, dict(t1 = 'two', i1 = 2)) insert(db, dict(t1 = 'three', i1 = 3)) insert(db, dict(t1 = 'four', i1 = 4)) disp_rows(db) print('Retrieve rows') print(dict(retrieve(db, 'one')), dict(retrieve(db, 'two'))) print('Update rows') update(db, dict(t1 = 'one', i1 = 101)) update(db, dict(t1 = 'three', i1 = 103)) disp_rows(db) print('Delete rows') delete(db, 'one') delete(db, 'three') disp_rows(db) if __name__ == "__main__": main() ######################################################### #### creating a database object with a class for sql #### ######################################################### class database: def __init__(self, **kwargs): # file name and table properties self.filename = kwargs.get('filename') self.table = kwargs.get('table', 'test') #no under scores= meant to be accessiable to outside def sql_do(self, sql, *params): self._db.execute(sql, params) self._db.commit() def insert(self, row): self._db.execute('insert into {} (t1, i1) values (?, ?)'.format(self._table), (row['t1'], row['i1'])) self._db.commit() def retrieve(self, key): cursor = self._db.execute('select * from {} where t1 = ?'.format(self._table), (key,)) return dict(cursor.fetchone()) def update(self, row): self._db.execute( 'update {} set i1 = ? where t1 = ?'.format(self._table), (row['i1'], row['t1'])) self._db.commit() def delete(self, key): self._db.execute('delete from {} where t1 = ?'.format(self._table), (key,)) self._db.commit() def disp_rows(self): cursor = self._db.execute('select * from {} order by t1'.format(self._table)) for row in cursor: print(' {}: {}'.format(row['t1'], row['i1'])) def __iter__(self): cursor = self._db.execute('select * from {} order by t1'.format(self._table)) for row in cursor: yield dict(row) @property # decorator to allow the filenamed to be assigned like that def filename(self): return self._filename @filename.setter def filename(self, fn): self._filename = fn self._db = sqlite3.connect(fn) self._db.row_factory = sqlite3.Row @filename.deleter def filename(self): self.close() @property def table(self): return self._table @table.setter def table(self, t): self._table = t @table.deleter def table(self): self._table = 'test' def close(self): self._db.close() del self._filename def main(): db = database(filename = 'test.db', table = 'test') #create an object an initi print('Create table test') db.sql_do('drop table if exists test') db.sql_do('create table test ( t1 text, i1 int )') print('Create rows') db.insert(dict(t1 = 'one', i1 = 1)) db.insert(dict(t1 = 'two', i1 = 2)) db.insert(dict(t1 = 'three', i1 = 3)) db.insert(dict(t1 = 'four', i1 = 4)) for row in db: print(row) print('Retrieve rows') print(db.retrieve('one'), db.retrieve('two')) print('Update rows') db.update(dict(t1 = 'one', i1 = 101)) db.update(dict(t1 = 'three', i1 = 103)) for row in db: print(row) print('Delete rows') db.delete('one') db.delete('three') for row in db: print(row) if __name__ == "__main__": main()
1349b4e71a4fbe0fb6af419e4c4958e60af4364d
vilisimo/ads
/python/leetcode/easy/ex0000_0100/ex0069.py
929
4.34375
4
# Given a non-negative integer x, compute and return the square root of x. # Since the return type is an integer, the decimal digits are truncated, # and only the integer part of the result is returned. # Note: You are not allowed to use any built-in exponent function or operator, # such as pow(x, 0.5) or x ** 0.5. # Example 1: # Input: x = 4 # Output: 2 # Example 2: # Input: x = 8 # Output: 2 # Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. # Constraints: # 0 <= x <= 2^31 - 1 class InitialSolution: def mySqrt(self, x: int) -> int: start, end = 0, x while start <= end: mid = start + (end - start) // 2 square = mid * mid if square > x: end = mid - 1 elif square < x: start = mid + 1 else: return mid return end
90a86804d1f7eec8c3af0eda8be0703d517f1ab4
AnotherContinent/thinkful
/FizzBuzz.py
368
4.0625
4
import sys num_input = raw_input("Please enter a number: ") try: num_input = int(num_input) except ValueError: print("That is not a valid integer.") else: for n in range(1,num_input): if n % 5 == 0 and n % 3 == 0: print("FizzBuzz") elif n % 5 == 0: print("Buzz") elif n % 3 == 0: print("Fizz") else: print(n)
87284010352d2f82d2e755374ec58cf9dc751793
ellyruthsilberstein/data_structures_and_algorithms
/binary_search.py
393
3.984375
4
def binary_search(collection, target): first = 0 last = len(collection) - 1 while first < last: midpoint = (first + last) // 2 if collection[midpoint] == target: return midpoint elif collection[midpoint] < target: first = midpoint + 1 else: last = midpoint - 1 return None for n in example_list: index = binary_search(list, n) print(index)
93772026e779b789ae4ebb1fd4b5b7999c546c6b
hire-blac/MyImpracticalPython
/pig_latin.py
572
4
4
'''a simple 'Pig Latin' program day15 of 100DaysOfCode''' def main(): '''main function to recieve input form user and convert to pig latin''' vowels = ['a', 'e', 'i', 'o', 'u'] message = input('Enter a word or sentence to be translated to Pig Latin:\n') translation = '' for word in message.split(): if len(word) <= 2: translation += word + ' ' elif word[0].lower() in vowels: translation += word + 'way ' else: new_word = word[1:] translation += new_word + word[0] + 'ay ' print(translation) print('\n') if __name__ == '__main__': main()
cabfd32db867ec8ecef307baed784d5c56afe565
TadasRad/Python
/Python Scripting Academy Unit 3/Module 4/sort_numbers.py
1,177
4.5
4
# [ ] Write a program that reads an unspecified number of integers from the command line, # then prints out the numbers in an ascending order # The program should have an optional argument to save the sorted numbers as a file named `sorted_numbers.txt` # The help message should look like: ''' usage: sort_numbers.py [-h] [-s] [numbers [numbers ...]] positional arguments: numbers int to be sorted optional arguments: -h, --help show this help message and exit -s, --save save the sorted numbers on a file (sorted_numbers.txt) ''' #HINT: use nargs = '*' in an add_argument method import sys import argparse parser = argparse.ArgumentParser() parser.add_argument('number',nargs = '*', type = int, help= "int to be sorted") parser.add_argument('-s','--save',action="store_true", help= "save the sorted numbers on a file (sorted_numbers.txt)") args = parser.parse_args() numbers = [] print(args.number) for i in args.number: numbers.append(i) numbers.sort() if args.save: file = open('sorted_numbers.txt', 'w') for i in numbers: file.write(str(i)+"\n") print("{} written to sorted_numbers.txt".format(numbers)) else: print(numbers)
e2914f0e3ee25f38101b484bf719b61b56cc3a47
aerospaceresearch/orbitdeterminator
/orbitdeterminator/util/state_kep.py
2,188
3.625
4
''' Takes a state vector (x, y, z, vx, vy, vz) where v is the velocity of the satellite and transforms it into a set of keplerian elements (a, e, i, ω, Ω, v) ''' import numpy as np import math def state_kep(r, v): ''' Converts state vector to orbital elements. Args: r (numpy array): position vector v (numpy array): velocity vector Returns: numpy array: array of the computed keplerian elements kep(0): semimajor axis (kilometers) kep(1): orbital eccentricity (non-dimensional) (0 <= eccentricity < 1) kep(2): orbital inclination (degrees) kep(3): argument of perigee (degress) kep(4): right ascension of ascending node (degrees) kep(5): true anomaly (degrees) ''' mu = 398600.4405 mag_r = np.sqrt(r.dot(r)) mag_v = np.sqrt(v.dot(v)) h = np.cross(r, v) mag_h = np.sqrt(h.dot(h)) e = ((np.cross(v, h)) / mu) - (r / mag_r) mag_e = np.sqrt(e.dot(e)) n = np.array([-h[1], h[0], 0]) mag_n = np.sqrt(n.dot(n)) true_anom = math.acos(np.clip(np.dot(e,r)/(mag_r * mag_e), -1, 1)) if np.dot(r, v) < 0: true_anom = 2 * math.pi - true_anom true_anom = math.degrees(true_anom) i = math.acos(np.clip(h[2] / mag_h, -1, 1)) i = math.degrees(i) ecc = mag_e raan = math.acos(np.clip(n[0] / mag_n, -1, 1)) if n[1] < 0: raan = 2 * math.pi - raan raan = math.degrees(raan) per = math.acos(np.clip(np.dot(n, e) / (mag_n * mag_e), -1, 1)) if e[2] < 0: per = 2 * math.pi - per per = math.degrees(per) a = 1 / ((2 / mag_r) - (mag_v**2 / mu)) if i >= 360.0: i = i - 360 if raan >= 360.0: raan = raan - 360 if per >= 360.0: per = per - 360 kep = np.zeros(6) kep[0] = a kep[1] = ecc kep[2] = i kep[3] = per kep[4] = raan kep[5] = true_anom return kep if __name__ == "__main__": r = np.array([5.0756899358316559e+03, -4.5590381308371752e+03, 1.9322228177731663e+03]) v = np.array([1.3360847905126974e+00, -1.5698574946888049e+00, -7.2117328822023676e+00]) kep = state_kep(r, v) print(kep)
12628120accf8502666276f71d49128e76983a26
Akashgiri1020/adventure-game
/Adventure game/game.py
4,532
3.96875
4
import time import random weapon = random.choice([" Mjölnir hammer","storm breaker"]) items = [] stone=[] def print_pause(string): print(string) time.sleep(2) def restart_game(): if weapon in items: items.remove(weapon) print_pause("GAME OVER\n") response = input("Would you like to play again yes or no?\n") if "yes" in response: adventure_game() elif "no" in response : print_pause("Thanks for playing this game! See you next time.") else: print_pause("I will ask you again") restart_game() def intro(): print_pause("you are Salman bhai ") print_pause("You find yourself standing in asgard") print_pause("The place is very deserted") print_pause(f"Rumor has it that Loki the magician is live inside a palace, " "and has been terrifying the neraby planets.") print_pause("after sometime,you find out the loki's palace.") print_pause("and your aim is to kill loki the magician who want to become GOD") print_pause("but you have only a dagger which is not affect the loki\n") print_pause(f"Loki is only kill by a {weapon} that is hide by Reality stone") print_pause("which is hide in asgardian secure house : Oregan") print_pause("reality stone is used to change the reality for other persons") print_pause("so you have two options:") def asgard(): # when player thinks what he do next print_pause(f"Enter 1 to enter in the palace.") print_pause("Enter 2 Find the reality stone.") print_pause("what would you like to do?") response = (input("(please enter 1 or 2).\n")) if "reality stone" in stone: print_pause("finally you got stone and use it to see reality") print_pause(f"you use it and take {weapon}") items.append(weapon) else: print("you have not reality stone") if response == '1': palace() elif response == '2': oregan() else: print("plz choose 1 or 2 nothing else") asgard() def palace(): # Things that happen to the player in the house. print_pause("You entered in the palace.") print_pause("You put your dagger on guard's neck" "And ask! where is the loki?") print_pause("And then enter in loki's room") if weapon in items: print_pause("As the loki moves to attack, ") print_pause(f"you unsheath your new {weapon}.") print_pause(f"The {weapon} with full of thunder " "you and your weapon is ready to attack.") print_pause("But the loki takes one look at " "your new weapon and surprised") print_pause("And loki use unlish power and attack on you" "suddenly you use realitiy and change the reality") print_pause("and failed the power of loki") print_pause(f"and then he use his {weapon} and defeat him") restart_game() elif weapon not in items: print_pause("As loki moves to attack") response = input("Would you like to (1) fight or (2) run away?\n") if response == '1': print_pause("you face loki with dagger") print_pause("finally loki defeat you.") print_pause("You have been defeated!") restart_game() elif response == '2': print_pause("You run back outside the palace. Luckily, " "you don't seem to have been followed.\n") asgard() def oregan(): # Things that happen to the player goes in the forest if weapon in items: print_pause("finally you findout the oregan in asgard.") print_pause("You go cautiously into oregan.") print_pause("You've been here before, and gotten reality stone " "the good stuff. It's just an empty now.") print_pause("You walk back out from oregan.") asgard() else: print_pause("You go cautiously into the oregan.") print_pause("finally you see reality stone inside the oregan") print_pause("you see that it is fantastic made") print_pause("take the reality stone with you.") print_pause("You walk back out from oregan.\n") stone.append("reality stone") asgard() def adventure_game(): intro() asgard() adventure_game()
74cda001f7e8cb6cd942c1da39e983819ed617dc
mridulrb/Basic-Python-Examples-for-Beginners
/Programs/MyPythonXII/Unit1/PyChap03/rowm.py
622
4.25
4
# File name: ...\\MyPythonXII\Unit1\PyChap03\rowm.py # Initializing the two dimensional array A = [[20, 40, 10], [40, 50, 30], [60, 30, 20], [40, 20, 30]] print("The original array is...") for r in range(0, 4): print(" "*10, end="") for c in range(0, 3): print (A[r][c], end=" ") print() print() # Function to calculate the multiplication of row elements def rowMultiplication(A): for i in range(4): mult = 1 for j in range(3): mult = mult * A[i][j] print("Product of row %d = %d" % (i+1, mult)) rowMultiplication(A)
29cd138c3acb8084be4e21716252ee099cbc2729
alzaia/applied_machine_learning_python
/logistic_regression/logistic_regression_fruits_dataset.py
1,801
3.75
4
# Binary logistic regression with fruits dataset (apple vs others) import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression # prepare fruits dataset using only 2 features fruits = pd.read_table('readonly/fruit_data_with_colors.txt') feature_names_fruits = ['height', 'width', 'mass', 'color_score'] X_fruits = fruits[feature_names_fruits] y_fruits = fruits['fruit_label'] target_names_fruits = ['apple', 'mandarin', 'orange', 'lemon'] X_fruits_2d = fruits[['height', 'width']] y_fruits_2d = fruits['fruit_label'] fig, subaxes = plt.subplots(1, 1, figsize=(7, 5)) y_fruits_apple = y_fruits_2d == 1 # make into a binary problem: apples vs everything else X_train, X_test, y_train, y_test = (train_test_split(X_fruits_2d.as_matrix(), y_fruits_apple.as_matrix(), random_state = 0)) # logistic regression clf = LogisticRegression(C=100).fit(X_train, y_train) # use model to predict new samples h = 6 w = 8 print('A fruit with height {} and width {} is predicted to be: {}'.format(h,w, ['not an apple', 'an apple'][clf.predict([[h,w]])[0]])) h = 10 w = 7 print('A fruit with height {} and width {} is predicted to be: {}'.format(h,w, ['not an apple', 'an apple'][clf.predict([[h,w]])[0]])) subaxes.set_xlabel('height') subaxes.set_ylabel('width') # check accruracy of model on train and test sets print('Accuracy of Logistic regression classifier on training set: {:.2f}'.format(clf.score(X_train, y_train))) print('Accuracy of Logistic regression classifier on test set: {:.2f}'.format(clf.score(X_test, y_test))) # check influence of C parameter for this_C in [0.1, 1, 100]: clf = LogisticRegression(C=this_C).fit(X_train, y_train)
2821053556785839a3add2a8258ca8a01314045d
kundan-git/apache-spark-pyspark-sql
/national_names_analysis/national_names_analysis_2.py
940
3.609375
4
from pyspark.sql import Row from pyspark import SparkContext from pyspark.sql import SQLContext if __name__=="__main__": # Create Spark Context sc = SparkContext("local[2]","Application") sqlContext = SQLContext(sc) filepath = "C:\\Users\\6910P\\Google Drive\\Dalhousie\\term_1\\data_management_analytics\\assignment_3\\NationalNames.csv" # Load data. df = sqlContext.read.load(filepath,format='com.databricks.spark.csv', header='true', inferSchema='true') df.registerTempTable("babynames") start_time = time.time() # Total number of births registered in a year by gender birth_count_by_year_gender = sqlContext.sql("SELECT year, gender , SUM(count) FROM babynames GROUP BY year, gender ORDER BY year ASC, gender ASC") print "Processing Time:"+str((time.time() - start_time)*1000)+" msec.\nTotal number of births registered in a year by gender:" birth_count_by_year_gender.show(birth_count_by_year_gender.count(),False)
f492c19d1cdc04474d9531e265c2bdd048e09668
seyedsaeidmasoumzadeh/Fuzzy-Q-Learning
/src/fuzzy_inference/fuzzyset.py
1,484
3.5
4
class Trapeziums(object): def __init__(self, left, left_top, right_top, right): self.left = left self.right = right self.left_top = left_top self.right_top = right_top def membership_value(self, input_value): if (input_value >= self.left_top) and (input_value <= self.right_top): membership_value = 1.0 elif (input_value <= self.left) or (input_value >= self.right_top): membership_value = 0.0 elif input_value < self.left_top: membership_value = (input_value - self.left) / (self.left_top - self.left) elif input_value > self.right_top: membership_value = (input_value - self.right) / ( self.right_top - self.right ) else: membership_value = 0.0 return membership_value class Triangles(object): def __init__(self, left, top, right): self.left = left self.right = right self.top = top def membership_value(self, input_value): if input_value == self.top: membership_value = 1.0 elif input_value <= self.left or input_value >= self.right: membership_value = 0.0 elif input_value < self.top: membership_value = (input_value - self.left) / (self.top - self.left) elif input_value > self.top: membership_value = (input_value - self.right) / (self.top - self.right) return membership_value
825f5fe407580e4af4e3b2db23f692673128c4de
RiyazShaikAuxo/datascience_store
/2.numpy/sharingsamememory.py
459
3.546875
4
import numpy as np a=np.arange(10) print(a) b=a print(b) #changing the one value in b b[0]=11 print(b) #a also changing print(a) # to Check whether a,b sharing same momory samememory=np.shares_memory(a,b) print(samememory) # To overcome this we will use copy method c=np.arange(10) print(c) #instead d=c use copy d=c.copy() print(d) d[0]=11 print(c) print(d) # to Check whether a,b sharing same momory samememory=np.shares_memory(c,d) print(samememory)
c20978c61078836b5b4ad1aed90a381fdb90ab5e
monster80s/Time-Series-ML
/LSTM.py
10,279
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 12 11:36:35 2018 @author: estebanlanter """ # load and plot dataset from pandas import DataFrame from pandas import read_csv from pandas import datetime from sklearn.preprocessing import MinMaxScaler from matplotlib import pyplot import os os.chdir('/Users/estebanlanter/Dropbox/Machine Learning/TimeSeries') # load def parser(x): return datetime.strptime(x, '%Y-%m') series = read_csv('raw_adjusted.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, sep=',') # summarize first few rows print(series.head()) # line plot series.plot() pyplot.show() series_normalized = MinMaxScaler(feature_range=(-1,1)).fit_transform(series) input_dat = series_normalized[:,0:6] output_dat = series_normalized[:,[0]] DataFrame(input_dat).plot() DataFrame(output_dat).plot() #we will compare LSTM vs MLP for multiple covariates for multivariate prediction. 3 independent series, and each itself for autoregressivity will be processed #we will leave it modeled in in low level tensorflow #lookback window #look forward window #batch size: influences how many lookback windows are chosen per iteration. num iterations = epochs*samplesize/batchsize. the larger the more precise but more computation (after forward feed). If we use all samples at once, we have a good approximation of thte true distribution, but it is only one learning step. If we use smaller batch (half-size) it is 2 learning steps, but less well approximated rtue distribution. In image recognition it would be number of images per learning step. #num_images equiv to inputsize = (samplesize-predwindow-lookback+1) #a single batch input has following dimensions: batchsize * lookback * numfeatures = #numfeatures: 3 external + 3 self = 6 #targetvector: 1d - num self * prediction window #GDP, INFLATION, INTEREST RATES #SELF, WEIGHTED FX, OIL, PAYROLLS, regression dummy #we will end with data #we use numpy import numpy as np LOOKBACK_WINDOW = 12 PREDICT_WINDOW = 4 nb_samples = len(input_dat) - LOOKBACK_WINDOW - PREDICT_WINDOW input_list = [np.expand_dims(input_dat[i:LOOKBACK_WINDOW+i,:], axis=0) for i in range(nb_samples)] input_mat = np.concatenate(input_list, axis=0) #batches * lookback * numfeatuers input_vector = input_mat.reshape(input_mat.shape[0],-1) #batches * flattened(features,lookback) print(input_mat.shape) print(input_vector.shape) #prepare targets - 1d array of lengtht num_images * features. we could also justt leave this a 2d array and lett tf handle tthe rtansform output_mat = np.asarray([output_dat[(LOOKBACK_WINDOW+i+1):(LOOKBACK_WINDOW+i+PREDICT_WINDOW+1),:] for i in range(nb_samples)]) #batches * features * horizon output_vector = output_mat.reshape(output_mat.shape[0],-1) print(output_mat.shape) print(output_vector.shape) input_mat_train = input_mat[0:50,:,:] input_vector_train = input_vector[0:50,:] output_mat_train = output_mat[0:50,:,:] output_vector_train = output_vector[0:50,:] input_mat_test = input_mat[51::,:,:] input_vector_test = input_vector[51::,:] output_mat_test = output_mat[51::,:,:] output_vector_test = output_vector[51::,:] #a function that takes input and output 3d-matrices and returns 2 generators def BatchGenerator2(inputdat,outputdat,size,shuffle,padrest): def unison_shuffled_copies(a, b): assert len(a) == len(b) p = np.random.permutation(len(a)) return a[p], b[p] assert inputdat.shape[0]==outputdat.shape[0] #cut away uneven data (change this...) rest = inputdat.shape[0]%size if shuffle==True: shuff_input, shuff_output = unison_shuffled_copies(inputdat,outputdat) else: shuff_input = inputdat shuff_output = outputdat if rest > 0: shuff_input = shuff_input[0:(shuff_input.shape[0]-rest)] shuff_input_rest = shuff_input[(shuff_input.shape[0]-rest)::] shuff_output = shuff_output[0:(shuff_output.shape[0]-rest)] shuff_output_rest = shuff_output[(shuff_output.shape[0]-rest)::] if padrest: toadd_input = np.zeros((size-rest,inputdat.shape[1],inputdat.shape[2])) toadd_output = np.zeros((size-rest,outputdat.shape[1],outputdat.shape[2])) shuff_input_rest = np.append(shuff_input_rest,toadd_input,0) shuff_output_rest = np.append(shuff_output_rest,toadd_output,0) splitby = inputdat.shape[0]//size x = np.split(shuff_input,splitby) y = np.split(shuff_output,splitby) if rest > 0: x.append(shuff_input_rest) y.append(shuff_output_rest) out = zip(x,y) for i in out: yield i import tensorflow as tf from tensorflow.contrib import rnn #for dropout lstm_sizes = [512,512] #hidden layers batch_size = 1 training_epochs = 10000 learning_rate=0.001 keep_prob = 1#0.9 num_examples = output_mat_train.shape[0] total_batch = int(num_examples/batch_size) lookback_window = input_mat_train.shape[1] #=time_steps number_of_sequences = input_mat_train.shape[2] num_output_sequences_to_predict = output_mat.shape[2] predict_window = output_mat_train.shape[1] tf.reset_default_graph() X = tf.placeholder("float", [batch_size, lookback_window, number_of_sequences]) # or X = tf.placeholder("float", [batch_size, lookback_window*number_of_sequences]) - IS IT SO???? Y = tf.placeholder("float", [batch_size, predict_window, num_output_sequences_to_predict]) #resize X to number_of_sequences*t[batch_size,lookback_window] or t[batch_size,lookback_window,number_of_sequences] keep_prob_node = tf.placeholder(tf.float32, name='keep_prob') # Forward passes# Forward passes lstms = [tf.contrib.rnn.BasicLSTMCell(size) for size in lstm_sizes] drops = [tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob_node) for lstm in lstms] #dropout layer cell = tf.contrib.rnn.MultiRNNCell(drops) #stacks layers together - is still a RNNCell, inherits rom it initial_state = cell.zero_state(batch_size, tf.float32) lstm_outputs, final_state = tf.nn.dynamic_rnn(cell, X, initial_state=initial_state) #Creates a recurrent neural network specified by RNNCell cell. Everytime called, it returns model output as wellas final statets #Training / prediction / loss out_weights=tf.Variable(tf.random_normal([lstm_sizes[-1],num_output_sequences_to_predict*predict_window])) out_bias=tf.Variable(tf.random_normal([num_output_sequences_to_predict*predict_window])) #we also reshape back here to the 3d form of inputs/outputs predictions=tf.reshape(tf.matmul(lstm_outputs[:, -1],out_weights)+out_bias,[batch_size, predict_window, num_output_sequences_to_predict]) #we only care about the last layer of te unrolled network. Also, this here we have basically created a manual final hidden layer +bias term. No activation function needed (equal tto linear activation). We cuold have used this also: tf.contrib.layers.fully_connected(lstm_outputs[:, -1], 1, activation_fn=None) #lstm_outputs[:, -1] is final unrolled layer which we will input into a linear activation function loss = tf.sqrt(tf.reduce_mean(tf.squared_difference(predictions, Y))) optimizer = tf.train.AdadeltaOptimizer(learning_rate).minimize(loss) #accuracy - this tests against train set accuracy = tf.sqrt(tf.reduce_mean(tf.squared_difference(predictions, Y))) #optimizers - out_weights and out_bias enters here. they are part of predictions, which are part o the loss op. All nodes making up loss_op are partt of the bpp optimization. therefore, thtey will be changed import matplotlib.pyplot as plt plotter_acc_train = [np.nan] * training_epochs plotter_acc_val = [np.nan] * training_epochs xplot = np.arange(0,training_epochs) saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) num_batches = num_examples//batch_size for epoch in range(training_epochs): print(epoch) state = sess.run(initial_state) train_acc = [] for i, (x, y) in enumerate(BatchGenerator2(input_mat_train,output_mat_train,batch_size,False,True), 1): feed = {X: x,Y: y,keep_prob_node: keep_prob,initial_state: state} loss_, state, _, batch_acc = sess.run([loss, final_state, optimizer, accuracy], feed_dict=feed) train_acc.append(batch_acc) plotter_acc_train[epoch] = batch_acc if (i + 1) % num_batches == 0: #if we are in the final step val_acc = [] val_state = sess.run(cell.zero_state(batch_size, tf.float32)) for xx, yy in BatchGenerator2(input_mat_test,output_mat_test,batch_size,False,True): feed = {X: xx,Y: yy,keep_prob_node: 1,initial_state: val_state} val_batch_acc, val_state, pred = sess.run([accuracy, final_state,predictions], feed_dict=feed) val_acc.append(val_batch_acc) plotter_acc_val[epoch] = val_batch_acc print(pred) print('____________') print(yy) print("Epoch: {}/{}...".format(epoch+1, training_epochs), "Batch: {}/{}...".format(i+1, num_batches), "Train Loss: {:.3f}...".format(loss_), "Train Accruacy: {:.3f}...".format(np.mean(train_acc)), "Val Accuracy: {:.3f}".format(np.mean(val_acc))) plt.plot(xplot,np.array(plotter_acc_train),'r') plt.plot(xplot,np.array(plotter_acc_val),'b') plt.xlim(0, training_epochs) plt.ylim(0,2) plt.show() #plt.pause(0.05) saver.save(sess, "checkpoints/lstm_state.ckpt") #stateful: hidden memory state remains between successive batches. Only once al batches are used & epoch is over is it reset. Default here #stateless: the state within the network is reset after each training batch of batch_size samples #stateful: the state within the network is maintained after each training batch of batch_size samples - deafult here #If we want to implement larger batches - eithter reset within loop of batches (inner loop). Or live hte fact that there is optimizattion of distance = batch size between time points #inputs for a gen per news event: #target data history #body of other econ series #calendar evevnts window (past / future) #outputs #binned text body
dbfde758baf733094acb16d07cd13d8402023b48
crypticani/Python-MiniProjects
/tictactoe.py
4,005
3.765625
4
def print_field(board): print('---------') for n in range(3): row = '| ' for m in range(3): row = row + board[m][n] + ' ' print(row + '|') print('---------') def evaluate_game(board): win_x = 0 win_o = 0 play_x = 0 play_o = 0 for n in range(3): for m in range(3): if board[m][n] == 'X': play_x += 1 elif board[m][n] == 'O': play_o += 1 if board[0][0] == board[0][1] == board[0][2] == 'X': # rows win_x += 1 if board[1][0] == board[1][1] == board[1][2] == 'X': win_x += 1 if board[2][0] == board[2][1] == board[2][2] == 'X': win_x += 1 if board[0][0] == board[1][0] == board[2][0] == 'X': # columns win_x += 1 if board[0][1] == board[1][1] == board[2][1] == 'X': win_x += 1 if board[0][2] == board[1][2] == board[2][2] == 'X': win_x += 1 if board[0][0] == board[1][1] == board[2][2] == 'X': # diagonals win_x += 1 if board[0][2] == board[1][1] == board[2][0] == 'X': win_x += 1 if board[0][0] == board[0][1] == board[0][2] == 'O': # rows win_o += 1 if board[1][0] == board[1][1] == board[1][2] == 'O': win_o += 1 if board[2][0] == board[2][1] == board[2][2] == 'O': win_o += 1 if board[0][0] == board[1][0] == board[2][0] == 'O': # columns win_o += 1 if board[0][1] == board[1][1] == board[2][1] == 'O': win_o += 1 if board[0][2] == board[1][2] == board[2][2] == 'O': win_o += 1 if board[0][0] == board[1][1] == board[2][2] == 'O': # diagonals win_o += 1 if board[0][2] == board[1][1] == board[2][0] == 'O': win_o += 1 if win_x == 1 and win_o == 0: return 'x' elif win_x == 0 and win_o == 1: return 'o' elif play_x + play_o == 9: return 'd' else: return '' field = [['', '', ''], ['', '', ''], ['', '', '']] cells = ' ' result = '' turn = 'x' i = 0 for n in range(3): for m in range(3): field[m][n] = cells[i] i += 1 print_field(field) print("Instructions:") print("A matrix based two player tic-tac-toe game") print("matrix format = (row, column)") while True: # evaluate game while turn == 'x': # Player X print("X's turn") choice = input('Enter the coordinates: ').split() try: if int(choice[0]) < 1 or int(choice[0]) > 3 or int(choice[1]) < 1 or int(choice[1]) > 3: print('Coordinates should be from 1 to 3!') else: column = int(choice[0]) - 1 row = int(choice[1]) - 1 if field[row][column] in ['X', 'O']: print('This cell is occupied! Choose another one!') else: field[row][column] = 'X' turn = 'o' except ValueError: print('You should enter numbers!') print_field(field) result = evaluate_game(field) if result != '': break while turn == 'o': # Player O print("O's turn") choice = input('Enter the coordinates: ').split() try: if int(choice[0]) < 1 or int(choice[0]) > 3 or int(choice[1]) < 1 or int(choice[1]) > 3: print('Coordinates should be from 1 to 3!') else: column = int(choice[0]) - 1 row = int(choice[1]) - 1 if field[row][column] in ['X', 'O']: print('This cell is occupied! Choose another one!') else: field[row][column] = 'O' turn = 'x' except ValueError: print('You should enter numbers!') print_field(field) result = evaluate_game(field) if result != '': break if result == 'x': print('X wins') elif result == 'o': print('O wins') elif result == 'd': print('Draw')
846a357dc1244cfe404871b2234438e81e92fe43
AuroraBoreas/python_advanced_tricks
/python-dict/py_05_dict.py
127
3.65625
4
mylist1 = "hello world I love python".split(" ") mylist2 = [1, 2, 3, 4, 5] mydict = dict(zip(mylist1, mylist2)) print(mydict)
6b8f9b0e5a7fa8cd6fd2795a4ddc10c25260ecf9
joseangel-sc/CodeFights
/Tournaments/sumUpNumbers.py
101
3.53125
4
def sumUpNumbers(s): s = re.split("\D",s) s = [int(i) for i in s if i!=""] return sum(s)
b30a6e6fb047a40af92691e398bb6d13493f3b9c
somodis/ClassRoomExamples
/SOE/ProgAlap2/20210317_tkinter/demo.py
520
4.28125
4
from tkinter import * def button_clicked(): print("click") Label(frame,text="inserted by click on button").pack(side="bottom") window = Tk() window.title('Demo GUI application') frame = Frame(window, bg="green") frame.pack(side="top") button=Button(frame,text="This is an example button",command=button_clicked) button.pack() for i in range(3): Label(window,text="[{}]".format(i+3), fg="red", bg="blue", font=('Arial',24)).pack(side="left" if i%2 else "right", padx=5, pady=40) window.mainloop()
bb3b4698a8522170a699792b066a326002e81b89
gabrypol/algorithms-data-structure-AE
/nth_fibonacci.py
1,698
4.28125
4
''' The Fibonacci sequence is defined as follows: the first number of the sequence is 0, the second number is 1, and the nth number is the sum of the (n - 1)th and (n - 2)th numbers. Write a function that takes in an integer n and returns the nth Fibonacci number. Important note: the Fibonacci sequence is often defined with its first two numbers as F0 = 0 and F1 = 1. For the purpose of this question, the first Fibonacci number is F0; therefore, getNthFib(1) is equal to F0, getNthFib(2) is equal to F1, etc.. Sample Input #1 n = 2 Sample Output #1 1 // 0, 1 Sample Input #2 n = 6 Sample Output #2 5 // 0, 1, 1, 2, 3, 5 ''' ''' Possible solutions: This problem can be solved also with recursion, although the time complexity would we O(2^n), with space complexity being O(n). An improvement to this solution is using dynamic programming: we store the result of nth_fibonacci(0), nth_fibonacci(1), nth_fibonacci(2), nth_fibonacci(3) and so on in a dictionary. This way, the time complexity is O(n) and the space complexity is also O(n). (Space complexity would be O(2n), one n for the call stack and one for the dictionary. Of course, 0(2n) is reduced to O(n) for our complexity analysis). An even better solution is to work up to the solution in a bottom-up fashion (see below). This way the runtime stays linear, but without additional space cost. ''' def nth_fibonacci(n): if n <= 0: raise ValueError('Number is negative or equal to zero.') if n == 1: return 0 if n == 2: return 1 a, b = 0, 1 for _ in range(n - 2): a, b = b, a + b return b number = 6 print(nth_fibonacci(number)) ''' Time: O(n) Space: O(1) '''
70024981b57ac62a4ad40c224f42e41cd812371b
kluitel/codehome
/src/map.py
164
3.875
4
#! /usr/bin/python # map will iterate trough the function def mult(val): return val * 2 my_list = [0,1,2,10,100,1000] iter = map(mult,my_list) print(list(iter))
5f9685fe4c114baf6b4fdccb9ada74499a5d56c6
chriswebb09/OneHundredProjects
/Text/check_palindrome.py
416
4.125
4
#!/usr/bin/env python* # -*- coding: UTF-8 -*- #Python 2.7 def is_palindrome(new_string): if new_string[::-1] == new_string: return "{} confirmed as palindrome".format(new_string) else: return "{} is not a palindrome".format(new_string) if __name__ == "__main__": user_string = raw_input("Input string to check : ") check_string = is_palindrome(user_string) print check_string
f38f69826d52dd548c95233c3df773343cc7fd34
sandeepvempati/lpthw_examples
/ex25p.py
1,371
4.25
4
def break_words(stuff): print "This function will break the words for us" words = stuff.split(' ') return words #print break_words("break the words") def sort_words(words): print "sort the words" return sorted(words) #print sort_words("I am good boy") def print_first_word(words): print "print the first word after popping it off." word = words.pop(0) return word #print print_first_word([1,2,3]) def print_last_word(words): print "print the last word after popping it." wordl = words.pop(-1) return wordl #print print_last_word([1,3,4,2,5,5,6,5,7,7,8,9]) def sort_sentence(sentence): "Takes in full sentence and sort the words" words = break_words(sentence) return words #print sort_sentence("sort the full word sentences") def print_first_and_last_sentence(sentence): print "first and last words of the sentence" words = break_words(sentence) print print_first_word(words) print print_last_word(words) #print print_first_and_last_sentence("first breaking the first and last") def print_first_last_words_after_sorted(sentence): print "first and last word after sorted" words = sort_sentence(sentence) print "words %s" %words print print_first_word(words) print print_last_word(words) #print print_first_last_words_after_sorted("first breaking the first and last")