blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
85c62e82199c54beed0380d13720151f4ddce77b
kingmadridli/Staj_1
/7_2021/12.07.2021/MySQL-Tkinter.py
5,024
3.6875
4
from tkinter import * import tkinter.messagebox import mysql.connector from tkinter import END root = Tk() root.geometry("600x300") root.title("Tkinter+MySQL") root.resizable(0,0) root.iconbitmap("MySQL.ico") #DEFINE FONTS AND COLORS my_font = ("bold",10) root_color = "#e3d26f" my_color = "#2f1b25" entry_color = "#426a5a" button_color = "#2660a4" button_text_color = "#f15946" root.config(bg=root_color) #DEFINE FUNCTIONS def Insert(): id = e_id.get() name = e_name.get() phone = e_phone.get() if (id == "" or name == "" or phone == ""): tkinter.messagebox.showinfo("Insert Status","All fields are required") else: connection = mysql.connector.connect( host = "localhost", user = "root", password ="MySQLite.123", database = "tkinter" ) cursor = connection.cursor() sql = "INSERT INTO student (id,name,phone) VALUES (%s,%s,%s)" values = (id,name,phone) cursor.execute(sql,values) e_id.delete(0,END) e_name.delete(0,END) e_phone.delete(0,END) try: connection.commit() print(f"{cursor.rowcount} tane kayıt eklendi") print("Son eklenen kaydın id numarası = {}".format(cursor.lastrowid)) except mysql.connector.Error as err: print("Hata : ",err) finally: connection.close() tkinter.messagebox.showinfo("Insert Status","Inserted Successfully\nDatabese closed") def Delete(): id = e_id.get() if id == "": tkinter.messagebox.showinfo("Delete Status","No ID number entered") else: connection = mysql.connector.connect( host = "localhost", user = "root", password ="MySQLite.123", database = "tkinter" ) cursor = connection.cursor() sql = "DELETE from student WHERE id = %s" value = (id,) cursor.execute(sql,value) e_id.delete(0,END) e_name.delete(0,END) e_phone.delete(0,END) try: connection.commit() print(f"{cursor.rowcount} tane kayıt silindi") except mysql.connector.Error as err: print("Hata : ",err) finally: connection.close() tkinter.messagebox.showinfo("Delete Status","Deleted Successfully\nDatabese closed") def Update(): id= e_id.get() name = e_name.get() phone = e_phone.get() if (id == "" or name == "" or phone == ""): tkinter.messagebox.showinfo("Update Status", "All fields are required") else: connection = mysql.connector.connect( host = "localhost", user = "root", password ="MySQLite.123", database = "tkinter" ) cursor = connection.cursor() sql = "UPDATE student SET name = %s, phone = %s WHERE id = %s" values = (name,phone,id) cursor.execute(sql,values) e_id.delete(0,END) e_name.delete(0,END) e_phone.delete(0,END) try: connection.commit() print(f"{cursor.rowcount} tane kayıt güncellendi") except mysql.connector.Error as err: print("Hata : ",err) finally: connection.close() tkinter.messagebox.showinfo("Update Status","Updated Successfully\nDatabese closed") def Get(): id = e_id.get() if id == "": tkinter.messagebox.showinfo("Fetch Status","No ID Entered") else: connection = mysql.connector.connect( host = "localhost", user = "root", password ="MySQLite.123", database = "tkinter" ) cursor = connection.cursor() sql = "SELECT * from student WHERE id = %s" value = (id,) cursor.execute(sql,value) rows = cursor.fetchall() for row in rows: e_name.insert(0,row[1]) e_phone.insert(0,row[2]) connection.close() #DEFINE LABELS id = Label(root,text="Enter ID",font=my_font,fg=my_color,bg=root_color) id.place(x=20,y=30) name = Label(root,text="Enter Your Name",font=my_font,fg=my_color,bg=root_color) name.place(x=20,y=60) phone = Label(root,text="Enter Your Phone Number",font=my_font,fg=my_color,bg=root_color) phone.place(x=20,y=90) #DEFINE ENTRIES e_id = Entry(fg=entry_color) e_id.place(x= 150,y=30) e_name = Entry(fg=entry_color) e_name.place(x= 150,y=60) e_phone = Entry(fg=entry_color) e_phone.place(x= 150,y=90) #DEFINE BUTTONS insert_button = Button(root, text="INSERT",font=my_font,bg=button_color,fg=button_text_color,command=Insert) insert_button.place(x=20,y=140) delete_button = Button(root, text="DELETE",font=my_font,bg=button_color,fg=button_text_color,command=Delete) delete_button.place(x=70,y=140) update_button = Button(root, text="UPDATE",font=my_font,bg=button_color,fg=button_text_color,command=Update) update_button.place(x=130,y=140) get_button = Button(root, text="GET",font=my_font,bg=button_color,fg=button_text_color,command=Get) get_button.place(x=190,y=140) root.mainloop()
da7d8575aa268d02cea4e1978e2819363bed1111
chanzer/leetcode
/LeftRotateString.py
574
3.75
4
""" 左旋转字符串 题目描述: 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务, 就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请 你把其循环左移K位后的序列输出。例如,字符序列S=“abcXYZdef”, 要求输出循环左移3位后的结果,即“XYZdefabc”。 是不是很简单?OK,搞定它! """ class Solution: def LeftRatateString(self,s,n): length = len(s) if length == 0: return '' n = n % length return s[n:] + s[:n]
ea56f043b20c88c5ab025c5137fb1ebbd9a36ba8
billykeyss/CodingQustions
/Strings/Anagrams.py
308
3.953125
4
# Determine if 2 Strings are anagrams def anagramSolver(string1, string2): string1 = ''.join(sorted(string1.replace(" ", ""))) string2 = ''.join(sorted(string2.replace(" ", ""))) if string1 == string2: print 'true' else: print 'false' anagramSolver('anagram', 'nag a ram');
616fb44ca7edaaf766bc010c0c98f9ecd62ca198
kokuraxc/-Algorithmic-Toolbox
/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py
1,007
3.671875
4
# Uses python3 import sys def fibonacci_sum_naive(n): if n <= 1: return n # previous = 0 # current = 1 # sum = 1 # for _ in range(n - 1): # previous, current = current, previous + current # sum += current # return sum % 10 pre, cur, total = 0, 1, 1 for _ in range(n - 1): pre, cur, total = cur, (pre + cur) % 10, (pre + cur + total) % 10 return total def get_fib_rep(n, m): rems = [0, 1] pre = 0 cur = 1 for _ in range(n - 1): pre, cur = cur, pre + cur rems.append(cur % m) if rems[-2:] == [0, 1]: rems = rems[:-2] break return rems def get_fib_sum_last(n): rems = get_fib_rep(n, 10) rep_rem = sum(rems) * ((n+1)//len(rems)) % 10 rest_rem = sum(rems[:(n+1)%len(rems)]) % 10 return (rep_rem + rest_rem) % 10 if __name__ == "__main__": # input = sys.stdin.read() input = input() n = int(input) print(get_fib_sum_last(n))
937a45dfd66cfb101064ca2f66e8d4d44c85904a
dcryptOG/pyclass-notes
/py-tutorial/10-additional/additional.py
39,836
4.65625
5
# Python Iterators #! ITERATORS # What are iterators in Python? # *ITERATIORS = are objects that can be iterated upon which will return data, one element at a time. # An object is called iterable if we can get an iterator from it. Most of built-in containers in Python like: list, tuple, string etc. are iterables. # Iterators are everywhere in Python. They are elegantly implemented within for loops, comprehensions, generators etc. but hidden in plain sight. # ! 2 special methods, # Build your own iterator using 2 special methods: # ? __iter__() # ? __next__(), # Technically speaking, Python iterator object must implement collectively called the iterator protocol. # * iter() # (which in turn calls the __iter__() method) returns an iterator from them. # Iterating Through an Iterator in Python # *next() # To manually iterate through all the items of an iterator. When we reach the end and there is no more data to be returned, it will raise StopIteration. # # NOTE EX # define a list my_list = [4, 7, 0, 3] # get an iterator using iter() my_iter = iter(my_list) # iterate through it using next() # prints 4 print(next(my_iter)) # prints 7 print(next(my_iter)) # next(obj) is same as obj.__next__() # prints 0 print(my_iter.__next__()) # prints 3 print(my_iter.__next__()) # This will raise error, no items left # next(my_iter) # A more elegant way of automatically iterating is by using the for loop. Using this, we can iterate over any object that can return an iterator, for example list, string, file etc. # >>> for element in my_list: # ... print(element) # ... # 4 # 7 # 0 # 3 # As we see in the above example, the for loop was able to iterate automatically through the list. In fact the for loop can iterate over any iterable. # # ? Let's take a closer look at how the for loop is actually implemented in Python. # for element in iterable: # # do something with element # NOTE Is actually implemented as. # # create an iterator object from that iterable # iter_obj = iter(iterable) # # infinite loop # while True: # try: # # get the next item # element = next(iter_obj) # # do something with element # except StopIteration: # # if StopIteration is raised, break from loop # break # So internally, the for loop creates an iterator object, iter_obj by calling iter() on the iterable. # ? This for loop is actually an infinite while loop. # Inside the loop, it calls next() to get the next element and executes the body of the for loop with this value. After all the items exhaust, StopIteration is raised which is internally caught and the loop ends. Note that any other kind of exception will pass through. # ==========================#========================== #! Building Your Own Iterator in Python # Building an iterator from scratch is easy in Python. We just have to implement the methods __iter__() and __next__(). # ? The __iter__() method returns the iterator object itself. If required, some initialization can be performed. # ? The __next__() method must return the next item in the sequence. On reaching the end, and in subsequent calls, it must raise StopIteration. # NOTE EX # that will give us next power of 2 in each iteration. Power exponent starts from zero up to a user set number. class PowTwo: """Class to implement an iterator of powers of two""" def __init__(self, max=0): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): if self.n <= self.max: result = 2 ** self.n self.n += 1 return result else: raise StopIteration # Now we can create an iterator and iterate through it as follows. a = PowTwo(4) i = iter(a) print(next(i)) # 1 # >>> next(i) # 2 # >>> next(i) # 4 # >>> next(i) # 8 # >>> next(i) # 16 # >>> next(i) # Traceback (most recent call last): # ... # StopIteration # We can also use a for loop to iterate over our iterator class. # >>> for i in PowTwo(5): # ... print(i) # ... # 1 # 2 # 4 # 8 # 16 # 32 #! Python Infinite Iterators # It is not necessary that the item in an iterator object has to exhaust. There can be infinite iterators (which never ends). We must be careful when handling such iterator. # Here is a simple example to demonstrate infinite iterators. # The built-in function iter() can be called with two arguments where the first argument must be a callable object (function) and second is the sentinel. The iterator calls this function until the returned value is equal to the sentinel. # >>> int() # 0 # >>> inf = iter(int,1) # >>> next(inf) # 0 # >>> next(inf) # 0 # We can see that the int() function always returns 0. So passing it as iter(int,1) will return an iterator that calls int() until the returned value equals 1. This never happens and we get an infinite iterator. # We can also built our own infinite iterators. The following iterator will, theoretically, return all the odd numbers. class InfIter: """Infinite iterator to return all odd numbers""" def __iter__(self): self.num = 1 return self def __next__(self): num = self.num self.num += 2 return num # A sample run would be as follows. # >>> a = iter(InfIter()) # >>> next(a) # 1 # >>> next(a) # 3 # >>> next(a) # 5 # >>> next(a) # 7 # And so on... # Be careful to include a terminating condition, when iterating over these type of infinite iterators. # The advantage of using iterators is that they save resources. Like shown above, we could get all the odd numbers without storing the entire number system in memory. We can have infinite items (theoretically) in finite memory. # ==========================#========================== #! GENERATORS # There's an easier way to create iterators in Python. To learn more visit: Python generators using yield. # Create iterations easily using Python generators, how is it different from iterators and normal functions, and why you should use it. # What are generators in Python? # There is a lot of overhead in building an iterator in Python; we have to implement a class with __iter__() and __next__() method, keep track of internal states, raise StopIteration when there was no values to be returned etc. # This is both lengthy and counter intuitive. Generator comes into rescue in such situations. # Python generators are a simple way of creating iterators. All the overhead we mentioned above are automatically handled by generators in Python. # Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time). # ? How to create a generator in Python? # It is fairly simple to create a generator in Python. It is as easy as defining a normal function with yield statement instead of a return statement. # If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator function. Both yield and return will return some value from a function. # The difference is that, # a return statement TERMINATES a function entirely, # yield statement PAUSES the function saving all its states and later continues from there on successive calls. print('#==========================#==========================') # ? Differences between Generator function and a Normal function # Here is how a generator function differs from a normal function. # Generator function contains ONE or MORE YIELD STATEMENT. # WHEN CALLED, it returns an object (iterator) but DOES NOT start execution immediately. # Methods like __iter__() and __next__() are IMPLEMENTED AUTOMATICALLY. So we can iterate through the items using next(). # ONCE FUNCTION YIELDS, the function is PAUSED and the control is transferred to the caller. # Local variables and their states are remembered between successive calls. # FINALLY, when the function terminates, StopIteration is raised automatically on further calls. # NOTE EX # illustrate all of the points stated above. We have a generator function named my_gen() with several yield statements. # A simple generator function def my_gen(): n = 1 print(f'\nThis is printed first\n {n}') # Generator function contains yield statements yield n n += 1 print(f'This is printed second\n {n}') yield n n += 1 print(f'This is printed at last\n {n}') yield n # An interactive run in the interpreter is given below. Run these in the Python shell to see the output. # >>> # It returns an object but does not start execution immediately. a = my_gen() # We can iterate through the items using next(). next(a) # This is printed first # 1 # Once the function yields, the function is paused and the control is transferred to the caller. # Local variables and theirs states are remembered between successive calls. next(a) # This is printed second # 2 next(a) # This is printed at last # 3 # Finally, when the function terminates, StopIteration is raised automatically on further calls. # NOTE >>> next(a) # NOTE Traceback (most recent call last): # ... # StopIteration # >>> next(a) # Traceback (most recent call last): # ... # StopIteration # One interesting thing to note in the above example is that, the value of variable n is remembered between each call. # Unlike normal functions, the local variables are not destroyed when the function yields. # # Furthermore, the GENERATOR OBJ can be ITERATED ONLY ONCE. # RESTART PROCESS we need to create another generator object using something like a = my_gen(). # NOTE: One final thing to note is that we can use generators with for loops DIRECTLY. Because, a for loop takes an iterator and iterates over it using next() function. It automatically ends when StopIteration is raised. print('\nExample equivalent') # A simple generator function def my_gen(): n = 1 print('This is printed first') # Generator function contains yield statements yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n # Using for loop for item in my_gen(): print(item) # When you run the program, the output will be: # This is printed first # 1 # This is printed second # 2 # This is printed at last # 3 print('The above example is of less use and we studied it just to get an idea of what was happening in the background.\n#==========================#==========================\n') #! Python Generators with a Loop # Normally, generator functions are implemented with a loop having a suitable terminating condition. # NOTE # a generator that reverses a string. print('Python Generators with a Loop') def rev_str(my_str): length = len(my_str) for i in range(length - 1, -1, -1): yield my_str[i] # For loop to reverse the string # Output: # o # l # l # e # h for char in rev_str("hello"): print(char) # In this example, we use range() function to get the index in reverse order using the for loop. # It turns out that this generator function not only works with string, but also with other kind of iterables like list, tuple etc. #! Python Generator Expression # Simple generators can be easily created on the fly using GENERATOR EXPRESSIONS. It makes building generators easy. # NOTE Same as LAMBDA function creates an ANONYMOUS function, # ? GENERATOR EXPRESSIONS creates an ANONYMOUS generator function. #! SYNTAX for generator expression # Similar to a LIST COMPREHENSION, but the square brackets # ? are replaced with ROUND PARENTHESIS. # NOTE The major difference between a list comprehension and a generator expression # list comprehension produces the entire list, # ? GENERATOR EXPRESSION produces ONE ITEM AT A TIME. # For this reason, a GENERATOR EXPRESSION is much MORE MEMORY EFFICIENT than an equivalent list comprehension. print('\nGENERATOR EXPRESSION vs LIST COMPREHENSION ex') # Initialize the list my_list = [1, 3, 6, 10] # square each term using list comprehension # Output: [1, 9, 36, 100] print('\nList comprehension', [x**2 for x in my_list]) print('\nUsing GENERATOR EXPRESSION') # Output: <generator object <genexpr> at 0x0000000002EBDAF8> print((x**2 for x in my_list)) # Generator expression did not produce the required result immediately. Instead, it returned a generator object with produces items on demand. # Intialize the list my_list = [1, 3, 6, 10] a = (x**2 for x in my_list) # Output: 1 print(next(a)) # Output: 9 print(next(a)) # Output: 36 print(next(a)) # Output: 100 print(next(a)) # Output: StopIteration # next(a) print('\nGENERATOR EXPRESSION can be used INSIDE FUNCTIONS. ') # ? GENERATOR EXPRESSION can be used INSIDE FUNCTIONS. # The ROUND PARENTHESIS can be dropped. print(sum(x**2 for x in my_list)) # 146 print(max(x**2 for x in my_list)) # 100 #! Why generators are used in Python? # There are several reasons which make generators an attractive implementation to go for. # ? 1. Easy to Implement # Generators can be implemented in a clear and concise way as compared to their iterator class counterpart. # NOTE EX to implement a sequence of power of 2's using iterator class. class PowTwo: def __init__(self, max=0): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): if self.n > self.max: raise StopIteration result = 2 ** self.n self.n += 1 return result # This was lengthy. Now lets do the same using a generator function. def PowTwoGen(max=0): n = 0 while n < max: yield 2 ** n n += 1 print('\n', PowTwo(5), '\n', PowTwoGen(5)) # Since, generators keep track of details automatically, it was concise and much cleaner in implementation. # ? 2. Memory Efficient # A normal function to return a sequence will create the entire sequence in memory before returning the result. This is an overkill if the number of items in the sequence is very large. # Generator implementation of such sequence is memory friendly and is preferred since it only produces one item at a time. # ? 3. Represent Infinite Stream # Generators are excellent medium to represent an infinite stream of data. # Infinite streams cannot be stored in memory and since generators produce only one item at a time, it can represent infinite stream of data. # NOTE EX can generate all the even numbers (at least in theory). def all_even(): n = 0 while True: yield n n += 2 print('\n', all_even()) # ? 4. Pipelining Generators # Generators can be used to pipeline a series of operations. # This is best illustrated using an example. Suppose we have a log file from a famous fast food chain. The log file has a column (4th column) that keeps track of the number of pizza sold every hour and we want to sum it to find the total pizzas sold in 5 years. # Assume everything is in string and numbers that are not available are marked as 'N/A'. A generator implementation of this could be as follows. # with open('sells.log') as file: # pizza_col = (line[3] for line in file) # per_hour = (int(x) for x in pizza_col if x != 'N/A') # print("Total pizzas sold = ",sum(per_hour)) # This pipelining is efficient and easy to read (and yes, a lot cooler!). # ==========================#========================== #! CLOSURES print('\n#==========================#==========================\n\t\tCLOSURES\n') # Nonlocal variable in a nested function # Before getting into what a closure is, we have to first understand what a nested function and nonlocal variable is. # * NESTED FUNCTION = function defined inside another function . # Nested functions can access variables of the enclosing scope. # ? Non-local variables are READ-ONLY by DEFAULT # ? TO MODIFY must declare explicitly as non-local (using NONLOCAL KEYWORD) # ==========================#========================== # NOTE EX of a nested function accessing a non-local variable. print('Nested Function EX') def print_msg(msg): # This is the outer enclosing function def printer(): # This is the nested function print(msg) printer() # We execute the function # Output: Hello print_msg("Hello") # We can see that the NESTED FUNCTION printer() was able to access the NON-LOCAL VAR msg of the enclosing function. #! Defining a Closure Function # In the example above, what would happen if the last line of the function print_msg() returned the printer() function instead of calling it? This means the function was defined as follows. print('\nEX Nested Function w/ return') def print_msg(msg): # This is the outer enclosing function def printer(): # This is the nested function print(msg) return printer # this got changed # Now let's try calling this function. # Output: Hello another = print_msg("Hello") another() # That's unusual. # The print_msg() function was called with the string "Hello" and the returned function was bound to the name another. On calling another(), the message was still remembered although we had already finished executing the print_msg() function. # *CLOSURE = technique by which some data ("Hello") gets attached to the code # This value in the enclosing scope is remembered even when the variable goes out of scope or the function itself is removed from the current namespace. # Try running the following in the Python shell to see the output. # >>> del print_msg # >>> another() # Hello # >>> print_msg("Hello") # Traceback (most recent call last): # ... # NameError: name 'print_msg' is not defined #! When do we have a closure? # CLOSURE when a nested function references a value in its enclosing scope. # * CRITERIA that must be met to create closure: # ? 1. We must have a NESTED FUNCTION (function inside a function). # ? 2. The nested function must refer to a VALUE defined in the ENCLOSING FUNCTION # ? 3. The enclosing function must RETURN the NESTED FUNCTIONM. #! When to use closures? # So what are closures good for? # Closures can AVOID the use of GLOBAL VALUES and provides some form of DATA HIDING. It can also provide an object oriented solution to the problem. # CLOSURES ideal when there are FEW METHODS (ONE in MOST CASES) to be implemented in a class, closures can provide an alternate and more elegant solutions. # # When the number of METHODS and ATTRIBUTES gets larger, better implement a class. # NOTE EX where a closure might be more preferable than defining a class and making objects. But the preference is all yours. print('\nEX CLOSURE \nAll Function Objects have a __closure__ attribute ') def make_multiplier_of(n): def multiplier(x): return x * n return multiplier # Multiplier of 3 times3 = make_multiplier_of(3) # Multiplier of 5 times5 = make_multiplier_of(5) # Output: 27 print(times3(9)) # Output: 15 print(times5(3)) # Output: 30 print(times5(times3(2))) # DECORATORS in Python make an extensive use of closures as well. # The values that get enclosed in the closure function can be found out. # All function objects have a __closure__ attribute that returns a TUPLE of cell objects if it is a CLOSURE FUNCTION. # # Referring to the example above, we know times3 and times5 are CLOSURE FUNCTIONS. # >>> make_multiplier_of.__closure__ print('\n', times3.__closure__) # (<cell at 0x0000000002D155B8: int object at 0x000000001E39B6E0>,) # The cell object has the attribute cell_contents which stores the closed value. print(times3.__closure__[0].cell_contents) # 3 print(times5.__closure__[0].cell_contents) # 5 # ==========================#========================== #! DECORATORS # A decorator takes in a function, adds some functionality and returns it. # What are decorators in Python? # Python has an interesting feature called decorators to add functionality to an existing code. # This is also called METAPROGRAMMING as a part of the program tries to modify another part of the program at COMPILE TIME. # Prerequisites for learning decorators # In order to understand about decorators, we must first know a few basic things in Python. # We must be comfortable with the fact that, everything in Python (Yes! Even classes), are objects. Names that we define are simply identifiers bound to these objects. Functions are no exceptions, they are objects too (with attributes). Various different names can be bound to the same function object. # NOTE EX print('\n#==========================#==========================') print('\tDECORATORS\nEX Decorator') def first(msg): print(msg) first("Hello") second = first second("Hello") # When you run the code, both functions first and second gives same output. Here, the names first and second refer to the same function object. # Now things start getting weirder. # Functions can be passed as arguments to another function. If you have used functions like map, filter and reduce in Python, then you already know about this. # * DECORATOR = takes in a function, adds some functionality and returns it. # *HIGHER ORDER FUNCTIONS = function that take other functions as arguments. # NOTE EX print('\n') def inc(x): return x + 1 def dec(x): return x - 1 def operate(func, x): result = func(x) return result # We invoke the function as follows. print(operate(inc, 3)) # 4 print(operate(dec, 3)) # 2 # ==========================#========================== print('\n') # Furthermore, a function can return another function. def is_called(): def is_returned(): print("Hello") return is_returned new = is_called() # Outputs "Hello" print(new()) # Here, is_returned() is a nested function which is defined and returned, each time we call is_called(). # ==========================#========================== # Functions and methods are called callable as they can be called. # In fact, any object which implements the special method __call__() is termed callable. So, in the most basic sense, a decorator is a CALLABLE that returns a CALLABLE. print('\n') def make_pretty(func): def inner(): print("I got decorated") func() return inner def ordinary(): print("I am ordinary") # When you run the following codes in shell, print(ordinary()) # I am ordinary # >>> # let's decorate this ordinary function pretty = make_pretty(ordinary) pretty() # I got decorated # I am ordinary # In the example shown above, make_pretty() is a decorator. In the assignment step. # pretty = make_pretty(ordinary) # The function ordinary() got decorated and the returned function was given the name pretty. # We can see that the decorator function added some new functionality to the original function. This is similar to packing a gift. The decorator acts as a wrapper. The nature of the object that got decorated (actual gift inside) does not alter. But now, it looks pretty (since it got decorated). # ==========================#========================== # Generally, we decorate a function and reassign it as, # ordinary = make_pretty(ordinary). # This is a common construct and for this reason, Python has a syntax to simplify this. # ? @ symbol along with the name of the DECORATOR FUNCTION # place it above the definition of the function to be decorated. # NOTE EX #! @make_pretty #! def ordinary(): #! print("I am ordinary") # ? is equivalent to #! def ordinary(): #! print("I am ordinary") #! ordinary = make_pretty(ordinary) # This is just a syntactic sugar to implement decorators. The above decorator was simple and it only worked with functions that did not have any parameters. # ==========================#========================== #! Decorating Functions with Parameters # What if we had functions that took in parameters like below? def divide(a, b): return a/b # This function has two parameters, a and b. We know, it will give error if we pass in b as 0. divide(2, 5) # 0.4 # NOTE >>> divide(2,0) # NOTE Traceback (most recent call last): # ... # NOTE ZeroDivisionError: division by zero print("Now let's make a decorator to check for this case that will cause the error.") def smart_divide(func): def inner(a, b): print("I am going to divide", a, "and", b) if b == 0: print("Whoops! cannot divide") return return func(a, b) return inner @smart_divide def divide(a, b): return a/b # This new implementation will return None if the error condition arises. divide(2, 5) # I am going to divide 2 and 5 # 0.4 divide(2, 0) # I am going to divide 2 and 0 # Whoops! cannot divide # In this manner we can decorate functions that take parameters. # A keen observer will notice that parameters of the nested inner() function inside the decorator is same as the parameters of functions it decorates. # # Taking this into account, now we can make general decorators that work with any number of parameter. # Done as function(*args, **kwargs). In this way, args will be the tuple of positional arguments and kwargs will be the dictionary of keyword arguments. # NOTE EX def works_for_all(func): def inner(*args, **kwargs): print("I can decorate any function") return func(*args, **kwargs) return inner #! Chaining Decorators in Python # Multiple decorators can be chained in Python. # This is to say, a function can be decorated multiple times with different (or same) decorators. We simply place the decorators above the desired function. def star(func): def inner(*args, **kwargs): print("*" * 30) func(*args, **kwargs) print("*" * 30) return inner def percent(func): def inner(*args, **kwargs): print("%" * 30) func(*args, **kwargs) print("%" * 30) return inner @star @percent def printer(msg): print(msg) printer("Hello") # This will give the output. # ****************************** # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Hello # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # ****************************** # * SYNTAX #! @star #! @percent #! def printer(msg): #! print(msg) # is equivalent to #! def printer(msg): #! print(msg) #! printer = star(percent(printer)) # ?The order in which we chain decorators matter. # If we had reversed the order as, # @percent # @star # def printer(msg): # print(msg) # The execution would take place as, # NOTE OUTPID OPPOSITE # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # ****************************** # Hello # ****************************** # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # ==========================#========================== #! @PROPERTY # Python @property # @property; pythonic way to use GETTERS and SETTERS. # NOTE EX # Let us assume that you decide to make a class that could store the temperature in degree Celsius. It would also implement a method to convert the temperature into degree Fahrenheit. One way of doing this is as follows. class Celsius: def __init__(self, temperature=0): self.temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 # We could make objects out of this class and manipulate the attribute temperature as we wished. Try these on Python shell. # >>> # create new object # >>> man = Celsius() # >>> # set temperature # >>> man.temperature = 37 # >>> # get temperature # >>> man.temperature # 37 # >>> # get degrees Fahrenheit # >>> man.to_fahrenheit() # 98.60000000000001 # The extra decimal places when converting into Fahrenheit is due to the floating point arithmetic error (try 1.1 + 2.2 in the Python interpreter). # Whenever we assign or retrieve any object attribute like temperature, as show above, Python searches it in the object's __dict__ dictionary. # >>> man.__dict__ # {'temperature': 37} # Therefore, man.temperature internally becomes man.__dict__['temperature']. # Now, let's further assume that our class got popular among clients and they started using it in their programs. They did all kinds of assignments to the object. # One fateful day, a trusted client came to us and suggested that temperatures cannot go below -273 degree Celsius (students of thermodynamics might argue that it's actually -273.15), also called the absolute zero. He further asked us to implement this value constraint. Being a company that strive for customer satisfaction, we happily heeded the suggestion and released version 1.01 (an upgrade of our existing class). # Using Getters and Setters # An obvious solution to the above constraint will be to hide the attribute temperature (make it private) and define new getter and setter interfaces to manipulate it. This can be done as follows. class Celsius: def __init__(self, temperature=0): self.set_temperature(temperature) def to_fahrenheit(self): return (self.get_temperature() * 1.8) + 32 # new update def get_temperature(self): return self._temperature def set_temperature(self, value): if value < -273: raise ValueError("Temperature below -273 is not possible") self._temperature = value # We can see above that new methods get_temperature() and set_temperature() were defined and furthermore, temperature was replaced with _temperature. An underscore (_) at the beginning is used to denote private variables in Python. # >>> c = Celsius(-277) # Traceback (most recent call last): # ... # ValueError: Temperature below -273 is not possible # >>> c = Celsius(37) # >>> c.get_temperature() # 37 # >>> c.set_temperature(10) # >>> c.set_temperature(-300) # Traceback (most recent call last): # ... # ValueError: Temperature below -273 is not possible # This update successfully implemented the new restriction. We are no longer allowed to set temperature below -273. # Please note that private variables don't exist in Python. There are simply norms to be followed. The language itself don't apply any restrictions. # >>> c._temperature = -300 # >>> c.get_temperature() # -300 # But this is not of great concern. The big problem with the above update is that, all the clients who implemented our previous class in their program have to modify their code from obj.temperature to obj.get_temperature() and all assignments like obj.temperature = val to obj.set_temperature(val). # This refactoring can cause headaches to the clients with hundreds of thousands of lines of codes. # All in all, our new update was not backward compatible. This is where property comes to rescue. #! The Power of @property # The pythonic way to deal with the above problem is to use property. Here is how we could have achieved it. class Celsius: def __init__(self, temperature=0): self.temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 def get_temperature(self): print("Getting value") return self._temperature def set_temperature(self, value): if value < -273: raise ValueError("Temperature below -273 is not possible") print("Setting value") self._temperature = value temperature = property(get_temperature, set_temperature) # And, issue the following code in shell once you run it. # >>> c = Celsius() # We added a print() function inside get_temperature() and set_temperature() to clearly observe that they are being executed. # The last line of the code, makes a property object temperature. Simply put, property attaches some code (get_temperature and set_temperature) to the member attribute accesses (temperature). # Any code that retrieves the value of temperature will automatically call get_temperature() instead of a dictionary (__dict__) look-up. Similarly, any code that assigns a value to temperature will automatically call set_temperature(). This is one cool feature in Python. # We can see above that set_temperature() was called even when we created an object. # Can you guess why? # The reason is that when an object is created, __init__() method gets called. This method has the line self.temperature = temperature. This assignment automatically called set_temperature(). # >>> c.temperature # Getting value # 0 # Similarly, any access like c.temperature automatically calls get_temperature(). This is what property does. Here are a few more examples. # >>> c.temperature = 37 # Setting value # >>> c.to_fahrenheit() # Getting value # 98.60000000000001 # By using property, we can see that, we modified our class and implemented the value constraint without any change required to the client code. Thus our implementation was backward compatible and everybody is happy. # Finally note that, the actual temperature value is stored in the private variable _temperature. The attribute temperature is a property object which provides interface to this private variable. #! Digging Deeper into Property # In Python, property() is a built-in function that creates and returns a property object. The signature of this function is # property(fget=None, fset=None, fdel=None, doc=None) # where, fget is function to get value of the attribute, fset is function to set value of the attribute, fdel is function to delete the attribute and doc is a string (like a comment). As seen from the implementation, these function arguments are optional. So, a property object can simply be created as follows. # >>> property() # <property object at 0x0000000003239B38> # A property object has three methods, getter(), setter(), and deleter() to specify fget, fset and fdel at a later point. This means, the line # temperature = property(get_temperature,set_temperature) # could have been broken down as # # make empty property # temperature = property() # # assign fget # temperature = temperature.getter(get_temperature) # # assign fset # temperature = temperature.setter(set_temperature) # These two pieces of codes are equivalent. # Programmers familiar with decorators in Python can recognize that the above construct can be implemented as decorators. # We can further go on and not define names get_temperature and set_temperature as they are unnecessary and pollute the class namespace. For this, we reuse the name temperature while defining our getter and setter functions. This is how it can be done. class Celsius: def __init__(self, temperature=0): self._temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 @property def temperature(self): print("Getting value") return self._temperature @temperature.setter def temperature(self, value): if value < -273: raise ValueError("Temperature below -273 is not possible") print("Setting value") self._temperature = value # The above implementation is both, simple and recommended way to make properties. You will most likely encounter these types of constructs when looking for property in Python. # ==========================#========================== #! ASSERT # Python Assert Statement # In this article we will learn about assertion in Python using assert. # What is Assertion? # Assertions are statements that assert or state a fact confidently in your program. For example, while writing a division function, you're confident the divisor shouldn't be zero, you assert divisor is not equal to zero. # Assertions are simply boolean expressions that checks if the conditions return true or not. If it is true, the program does nothing and move to the next line of code. However, if it's false, the program stops and throws an error. # It is also a debugging tool as it brings the program on halt as soon as any error is occurred and shows on which point of the program error has occurred. # You can learn more about assertions in the article: The benefits of programming with Assertions # We can be clear by looking at the flowchart below: # Python Assert Flowchart # Python assert Statement # Python has built-in assert statement to use assertion condition in the program. assert statement has a condition or expression which is supposed to be always true. If the condition is false assert halts the program and gives an AssertionError. # Syntax for using Assert in Pyhton: # assert <condition> # assert <condition>,<error message> # In Python we can use assert statement in two ways as mentioned above. # assert statement has a condition and if the condition is not satisfied the program will stop and give AssertionError. # assert statement can also have a condition and a optional error message. If the condition is not satisfied assert stops the program and gives AssertionError along with the error message. # Let's take an example, where we have a function which will calculate the average of the values passed by the user and the value should not be an empty list. We will use assert statement to check the parameter and if the length is of the passed list is zero, program halts. # Example 1: Using assert without Error Message # def avg(marks): # assert len(marks) != 0 # return sum(marks)/len(marks) # mark1 = [] # print("Average of mark1:",avg(mark1)) # When we run the above program, the output will be: # AssertionError # We got an error as we passed an empty list mark1 to assert statement, the condition became false and assert stops the program and give AssertionError. # Now let's pass another list which will satisfy the assert condition and see what will be our output. # Example 2: Using assert with error message # def avg(marks): # assert len(marks) != 0,"List is empty." # return sum(marks)/len(marks) # mark2 = [55,88,78,90,79] # print("Average of mark2:",avg(mark2)) # mark1 = [] # print("Average of mark1:",avg(mark1)) # When we run the above program, the output will be: # Average of mark2: 78.0 # AssertionError: List is empty. # We passed a non-empty list mark2 and also an empty list mark1 to the avg() function and we got output for mark2 list but after that we got an error AssertionError: List is empty. The assert condition was satisfied by the mark2 list and program to continue to run. However, mark1 doesn't satisfy the condition and gives an AssertionError. # Key Points to Remember # Assertions are the condition or boolean expression which are always supposed to be true in the code. # assert statement takes an expression and optional message. # assert statement is used to check types, values of argument and the output of the function. # assert statement is used as debugging tool as it halts the program at the point where an error occurs. #!#==========================#========================== CANCEL GITHUB PAGES #==========================#==========================
2732066e3a271e021f7ed71e180041a8cb9fd796
szmuschi/Python
/Lab2/src/12.py
445
4.28125
4
# Write a function that will order a list of string tuples based on the 3rd character of the 2nd element in the tuple. Example: ('abc', 'bcd'), ('abc', 'zza')] ==> [('abc', 'zza'), ('abc', 'bcd')] # take second element for sort import random def take_last_of_second(elem): return elem[1][-1] def ex_12(l): l.sort(key=take_last_of_second) return l if __name__ == '__main__': print(ex_12([('abc', 'bcd'), ('abc', 'zza')]))
0becf7b1bab8e43b65cd919a8516aed8fa27308e
manuwhs/Hackathons
/Codility/5.py
4,062
3.78125
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 30 17:55:45 2016 @author: montoya """ def case_just_1(A, first_1): # Tells if it is winnable for just 1 1 and what to do A_len = len(A) if (first_1 > 0 and first_1 < A_len - 1): # If the one is not in the extremes # If there are more than 1 0s at any side, we can sustrac them. # Actually we sustract them, if it is even, we are fucked N_0s_left = first_1 N_0s_right = A_len - 1 - first_1 if (N_0s_left > 1) and (N_0s_right > 1): if ((N_0s_left + N_0s_right)%2) == 0: # Even number, we die return "NO SOLUTION" else: if (N_0s_left % 2): return str(0) +"," + str(first_1-3) else: return str(first_1+1) +"," + str(A_len-1 - 2) elif (N_0s_left == 1 and N_0s_right > 1): return str(first_1 + 1) +"," + str(A_len - 2) # We leave it like 010 elif (N_0s_right == 1 and N_0s_left > 1): return str(0) +"," + str(first_1 -2) # We leave it like 010 elif (N_0s_right == 1 and N_0s_left == 1): return "NO SOLUTION" else: # In the case the 1 is in the extremes if (first_1 == 0): return str(1) +"," + str(A_len - 1) else: return str(0) +"," + str(A_len - 2) def solution(A): # odd numbers must be removed by pairs # You can also choose to remove just an even number of an even number and a pair of integers # Mmm in the first move you should remove everything you can and leave the situation # 010 or 1 or ... # You remove all the 1s possible and play also with the 0s in the boundaries of the 1s # Transform A into bit array A_bin = [] A_len = len(A) for i in range (A_len): A_bin.append(A[i]%2) A = A_bin # Substitution # print A first_1 = -1; # Find first position of 1. There has to be an even number of 1s, otherwise you can win in the first move for i in range(A_len): if(A[i] == 1): first_1 = i break; if (first_1 == -1): # No 1s found return [0,A_len - 1] # We remove everything # Find the position of the one before the last 1. antepel_1 = -1; penul = 0; for i in range(A_len): if(A[A_len -1-i] == 1): if (penul == 0): penul = 1 last_1 = i else: antepel_1 = i break if (antepel_1 == -1): # If there is only 1 one !! return case_just_1(A, first_1) else: """ We have to remove them so that the left scenario makes them dead""" # We have to leave anything but 0100 or 01 # 0s left and right after removing the 1s # Remove the inbetween N_0s_left = first_1 # Extra 0s we can put either way to win N_0s_right = last_1 - antepel_1 - 1 A_final = A_bin[0:first_1] A_final.extend(A_bin[antepel_1 + 1:]) resul = case_just_1(A_final, last_1); # If the other can win if (resul == "NO SOLUTION"): # We already won if (N_0s_left % 2): return str(1) +"," + str(antepel_1) else: return str(0) +"," + str(antepel_1) else: # We can add 0s to left or right to try to win # We can add an odd number of 1s to right or left if (N_0s_left >= 1): if (N_0s_left % 2): return str(0) +"," + str(antepel_1) else: return str(1) +"," + str(antepel_1) elif (N_0s_right >= 1): return str(first_1) +"," + str(antepel_1 + 1) else: return "NO SOLUTION" A = [4, 5, 3, 7, 2] #A = [2,5,4] print solution(A)
2da45ed4181fae770fae24c0d4459ba4373b897e
AngieCastano/holbertonschool-higher_level_programming
/0x0A-python-inheritance/7-base_geometry.py
578
4
4
#!/usr/bin/python3 """ Write an empty class BaseGeometry """ class BaseGeometry: """ empty class BaseGeometry """ def area(self): """ args: self = instance """ raise Exception("area() is not implemented") def integer_validator(self, name, value): """ that validates value type """ types = [int] if type(value) not in types: raise TypeError("{} must be an integer".format(name)) if value < 1: raise ValueError("{} must be greater than 0".format(name))
ef96b618f40af3d02e37305e725fdff2455f98c5
bobowang2017/python_study
/algorithm/leetcode/69.x的平方根.py
925
4.21875
4
# -*- coding: utf-8 -*- # 实现 int sqrt(int x) 函数。 # 计算并返回 x 的平方根,其中 x 是非负整数。 # 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 # 示例 1: # 输入: 4 # 输出: 2 # 示例 2: # 输入: 8 # 输出: 2 # 说明: 8 的平方根是 2.82842..., #   由于返回类型是整数,小数部分将被舍去。 # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/sqrtx # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 # 牛顿迭代法:https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ if x <= 1: return x r = x while r > x / r: r = (r + x / r) // 2 return int(r)
5ef767b9f974e6adf724f84c9d4d741e1c6b2d08
thecodemonk101/pc_health
/health_check.py
514
3.734375
4
#!/usr/bin/env python3 import shutil import psutil def check_disk_usage(disk): du = shutil.disk_usage(disk) free = du.free/du.total*100 return free>20 def check_cpu_usage(): usage = psutil.cpu_percent(1) return usage <75 if not check_disk_usage("/") or not check_cpu_usage(): print("ERROR") else: print("EVERYTHING IS FINE!") #Detect dangerously high CPU usage levels across a network and scale back the CPU clock speeds of those devices, or shut them down to prevent overheating
b3c403a5b8c838673ee2e795f07e71f6d8d4618e
WooSeok-03/Algorithm
/Baekjoon/Python/8958 - OX Quiz.py
213
3.515625
4
N = int(input()) for i in range(N): score = 0 extra_score = 1 ox_list = list(str(input())) for j in ox_list: if j == 'O': score += extra_score extra_score += 1 else: extra_score = 1 print(score)
f65e0692028ddc156095f72d0b15008ca275ad78
JakeAttard/Python-2807ICT-NoteBook
/ExamPratice/examExamples.py
5,156
3.78125
4
# for i in range(10): # for j in range(i): # print(i * j) # x = 1 # y = -1 # z = 1 # # if x > 0: # if y > 0: # print("x > 0 and y > 0") # elif z > 0: # print("1 < 0 and 1 > 0") # i = 1 # while i < 9: # i += 1 # if i % 2 == 0: # continue # print(i, end=' ') # def nPrint(message, n): # while n > 0: # print(message) # n-= 1 # nPrint('a', 4) # for i in range(10, 20): # for j in range(i): # print(i + j) # i = 2 # while True: # if i % 3 == 0: # break # print(i) # i += 2 # def say(message, times = 1): # print(message * times) # say('Hello') # say('World', 3) # n = int(input()) # for row in range(n): # for col in range(1, n - row + 1): # print(col, end=" ") # print() # def nextSquare(n): # i = 0 # while i * i <= n: # i += 1 # return i * i # for i in range(6): # for j in range(i): # print(j) # for x in [1, 2, 4]: # for y in [4, 2, 1]: # if x != y: # if y < x: # print("apple") # else: # print("banana") # else: # print("cherry") # print([(a, b) for a in "abc" for b in range(1, 3)]) # for i in range(8): # for j in range(16): # if (i + j) % 8 in [1, 5]: # print('/', end='') # elif (j - i) % 8 in [2, 6]: # print('\\', end='') # else: # print(' ', end='') # print() # intList = [int(input()) for i in range(int(input()))] # print(sum([intList[i] for i in range(len(intList)) # if intList[i] not in intList[:i] + intList[i + 1:]])) # def is_prime(n): # if (n==1): # return False # elif (n==2): # return True # else: # for x in range(2,n): # if(n % x==0): # return False # return True # print(is_prime(1)) # import re # # # def isValidPassword(password): # password = "jake" # flag = 0 # # # while True: # if (len(password) < 8): # flag = -1 # break # elif not re.search("[a-z]", password): # flag = -1 # break # elif not re.search("[A-Z]", password): # flag = -1 # break # elif not re.search("[0-9]", password): # flag = -1 # break # elif not re.search("[_@$]", password): # flag = -1 # break # elif re.search("\s", password): # flag = -1 # break # else: # flag = 0 # print("Valid Password") # break # # if flag == -1: # print("Not a Valid Password") # class Person: # def __init__(self, n, a): # self.fullName = n # self.age = a # # def getAge(self): # return self.age # # class Student(Person): # def __init__(self, n, a, s): # Person.__init__(self, n, a) # self.school = s # # def StudentSchool(self): # return self.school() # class Person: # def __init__(self, name, dob, addr, income): # self.name = name # self.birthDate = dob # self.address = addr # self.income = income # # def updateAddress(self, newAddress): # self.address = newAddress # print("Update Address " + self.address) # # p1 = Person("Jake Attard", "04-01-1999", "1 Griffith Drive GC", "$1,000") # p1.updateAddress("Zac Cripps") # def isValidPassword(word): # specialCharacters = ["#", "$", "%", "+"] # for i in word: # if i.isupper(): # for j in word: # if j.islower(): # for k in word: # if k.isdigit(): # for a in word: # if a in specialCharacters: # return print("True") # else: # print("False") # break # word = input() # isValidPassword(word) # i = 5 # while True: # if i % 9 == 0: # break # print(i, end="") # i += 1 # class Person: # def __init__(self, name, dob, addr, income): # self.name = name # self.birthDate = dob # self.address = addr # self.income = income # # def printUserDetails(self): # print("Full Name: " + self.name) # print("Date Of Birth: " + self.birthDate) # print("Address: " + self.address) # print("Income: " + self.income) # # p1 = Person("David Smith", "23-Jan-2000", "28 Johnson Street, Southport QLD 4215", "$15308.5") # p1.printUserDetails() # for i in range(10, 20): # for j in range(i): # print(i + j) # i = 2 # while True: # if i % 3 == 0: # break # print(i) # i += 2 def greaterCheck(list): for i in range(len(list)): if list[i][0] > list[i][1]: a = list[i][0] break return a listA = [(10, 4), (5, 6), (1, 2)] print(greaterCheck(listA)) def greaterChe2ck(list): orignalList = [] for i in range(len(list)): if list[i][0] <= list[i][1]: orignalList.append(list[i]) return orignalList listA = [(1, 4), (8, 6), (1, 2)] print(greaterCheck(listA))
cce4d91751dc736097b0695362cebee09babd7c7
SFenijn/Python2017
/Les 4/Final Assignment 4/FA 4.py
1,041
3.625
4
#leeftijd = (float(input('Wat is uw leeftijd?'))) #afstandKM = (float(input('Wat is de afstand in KM die u aflegt?'))) #weekendrit = bool(input('Is het weekend? ja/nee')) def standaardprijs(afstandKM): 'berekend hoeveel een kaartje kost aan de hand van de afgelegde km.' if afstandKM > 50: afstandKM = 15 + 0.60 * afstandKM return afstandKM elif (afstandKM <= 50) and (afstandKM > 0): afstandKM = 0.80 * afstandKM return afstandKM else: afstandKM = 0 return afstandKM def ritprijs(leeftijd, weekendrit, afstandKM): 'kijkt naar uitzonderingen op het standaardtarief.' if (leeftijd < 12) or (leeftijd >= 65): if weekendrit == True: prijs = afstandKM * 0.65 else: prijs = afstandKM * 0.7 else: if weekendrit == True: prijs = afstandKM * 0.6 else: prijs = afstandKM return prijs leeftijd = 23 afstandKM = 20 weekendrit = True print( ritprijs(leeftijd, weekendrit, afstandKM))
0e0208dbbfe7a56be05865ae53e757b526b21d38
reCursedd/NC_FSS
/w4/rows.py
3,391
3.515625
4
from w3.num import Num from w3.sym import Sym from w12 import w2 import util import re class Data: def __init__(self): self.w = {} self.syms = {} self.nums = {} self.dclass = None self.rows = {} # Name of cols self.name = {} # Use are the cols that we will be using self.use = {} self.indeps = [] def indep(self, c): return c not in self.w and self.dclass != c def dep(self, c): return not self.indep(c) # sets header and use cols def header(self, cells): for i,x in enumerate(cells): if not re.match('\?', x): # print ("printing x", x) c = len(self.use) # print ("Printing C", c) self.use[c] = i self.name[c] = x if re.match("[<>$]",x): self.nums[c] = Num(0) else: self.syms[c] = Sym() #----why are setting goals for length of us? Shouldn't it be for each column? if re.match("<",x) : self.w[c] = -1 elif re.match(">",x): self.w[c] = 1 elif re.match("!", x): self.dclass = c else: self.indeps.append(c) # print("last name", self.name) # print ("last use", self.use) # for every row this gets called once for formatting and incrementing values def row(self, cells): r = len(self.rows) # print ("r:", r) # print ("cells:", cells) self.rows[r] = [] for i, c in (self.use).items(): x = cells[c] if x != "?": if i in self.nums: x = float(x) self.nums[i].numInc(x) else: self.syms[i].symInc(x) self.rows[r].append(x) # Only a csv reader, try doing with w2 code! def readerRows(self, file): t = Data() with open(file) as f: # ? how does this work first = True for line in f.readlines(): re.sub("[\t\r\n ]*", "", line) re.sub("#.*", "", line) cells = [x.strip() for x in line.split(",")] if len(cells) > 0: if first: t = self.header(cells) else: t = self.row(cells) first = False return t def display(self): print("\nindex \t name \t\t n\t mode \t frequency") for i, sym in self.syms.items(): print('{:<8} {:<12} {:<4} {:<12} {:<12}'.format(i+1, self.name[i], sym.n, sym.mode, sym.most)) print("\nindex \tname \t\t\t n\t mu\t\t\tsd") for i, num in self.nums.items(): print('{:<8} {:<14} {:<4} {:<10.2f} {:<8.2f}'.format(i+1, self.name[i], num.n, num.mu, (num.sd))) # Can't we manually test # @util.O.k # def rowTest(): # d1 = Data() # print('\n\n weather.csv') # x = d1.readerRows("weather.csv") # d1.display() # # d2 = Data() # print('\n\n weatherLong.csv') # d2.readerRows("weatherLong.csv") # d2.display() # # d3 = Data() # print('\n\n auto.csv') # d3.readerRows("auto.csv") # d3.display()
344e11dc6c95c6c505fc80bc123d9e068098069d
adamafriansyahb/algorithm-practice
/string_construction.py
182
3.5
4
def stringConstruction(s): unique = {} cost = 0 for i in s: if i not in unique: unique[i] = 1 cost += 1 return cost
cd3efaa501ad0b3cacb1f46c80cf2e9cee383988
jaebradley/leetcode.py
/populating_next_right_pointers_in_each_node_2.py
3,031
4.0625
4
from tree_link_node import Node """ https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ Given a binary tree struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Example: Input: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1} Output: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":null,"right":null,"val":7},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"6","left":null,"next":null,"right":{"$ref":"5"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"6"},"val":1} Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. Note: You may only use constant extra space. Recursive approach is fine, implicit stack space does not count as extra space for this problem. # Definition for a Node. class Node(object): def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next Strategy: * While current node is non-null... * Create a "dummy" node for a given "level" * For each "level" iterate over children of current node setting the next references for each non-null node * After processing children of current node, next current node is the next reference from previous current node * These next references are set by previous level so other than root node, should refer to the node next to it * Do this for loop until finished iterating through nodes in level (i.e. current level node is null) * When done with a level, set the current node to be start of next level * This is just the dummy node's next reference, which should be the left-most child of the first node in the level """ class Solution(object): def connect(self, root): """ :type root: Node :rtype: Node """ tree = root while root != None: level_start_placeholder = Node(0) current_level_node = level_start_placeholder while root != None: if root.left != None: current_level_node.next = root.left current_level_node = current_level_node.next if root.right != None: current_level_node.next = root.right current_level_node = current_level_node.next root = root.next root = level_start_placeholder.next return tree
96a40711c148e2e9cdaecfaee6c8fe367fa855f2
ClaudiaStrm/UriOnlineJudge
/i_bhaskara.py
590
3.71875
4
''' Leia 3 valores de ponto flutuante e efetue o cálculo das raízes da equação de Bhaskara. Se não for possível calcular as raízes, mostre a mensagem correspondente “Impossivel calcular”, caso haja uma divisão por 0 ou raiz de numero negativo. ''' bask = [float(x) for x in input().split()] from math import sqrt delta = bask[1] ** 2 - 4 * bask[0] * bask[2] if bask[0] == 0 or delta <= 0: print("Impossivel calcular") else: r1 = (- bask[1] + sqrt(delta)) / (2 * bask[0]) print("R1 = %.5f" %r1) r2 = (- bask[1] - sqrt(delta)) / (2 * bask[0]) print("R2 = %.5f" %r2)
f3027ea4e2f90bd46f5fd67448ebd60121f67188
deepkumarchaudhary/python-poc
/midlevel/countFactor.py
381
3.78125
4
#factor counts def solution(N): candidate = 1 result = 0 while candidate * candidate < N: # N has two factors: candidate and N // candidate if N % candidate == 0: result += 2 candidate += 1 # If N is square of some value. if candidate * candidate == N: result += 1 return result print("Total no of factor:", solution(24))
67c11a43217ad320a9f74ab08c62446c7fe7ba26
9minsu0603/git_python_study
/chapter04/set_study.py
751
4.09375
4
# 로또번호 생성기를 작성하고 당첨번호에 따라 순위를 구하는 프로그램 # 5000원치 로또번호를 생성하세요. import random as rnd from chapter04.exam02(use) import bubble_sort def lotto_generator (): lotto_num = set() while len(lotto_num) < 6: lotto_num.add(rnd.randint(1, 46)) return lotto_num if __name__ == "__main__": rnd.seed(4) sorted_lotto = list(lotto_generator()) print("로또번호 : {}".format(bubble_srt(sorted_lotto))) # 정렬된 결과 num = rnd.randint(1, 46) lotto_num = set() for result in lotto_num lotto_num.add(num) lotto_num.add(rnd.randint(1, 46)) print("{}\t{}".format(lotto_num, len(lotto_num))) set_lotto = lotto_generator()
98213e69a02e12b60e417d611043732bee290af4
Kedaj/Cmp108
/.gitignore/MJ43.py
247
3.828125
4
#Makeda joseph #04/24/2017 def calculater_tax(income): if income < 250000: tax = income *.40 else: tax = 250000*.40 + (income - 250000) *.8 return tax def main(): y = calculater_tax(300000) print (y) main()
b5a9001f1fe65fc456db64632da7825b27d24406
kabilanvennila/Python-projects-
/Alarm.py
1,082
3.6875
4
#Alarm basic app V1.0 #Importing modules that are needed import time import datetime import pygame print('*****') print(' *** ') print(' * ') print(' *** ') print('*****') #This is just a basic Greetings print('Welcome to Alarm App') print('SET OF RULES FOR USAGE:') #User should enter the time in 24 Hours Time format print('******USE ONLY 24 HOURS CLOCK FORMAT******') current_time=time.asctime() current_time=current_time[11:-8] #prints the current Time print("The current time in Your Country is: "+current_time) #Gets Input from the User To set the alarm timer User_time=input("plese enter a time : ") Set_time=User_time #Execution Part #NOTE: Change the music location if you want to use this code as it is Bool=True while Bool: time=datetime.datetime.now() time=str(time.hour)+':'+str(time.minute) if(Set_time==time): Bool=False pygame.mixer.init() pygame.mixer.music.load(r"C:\Users\HP\Music\05+The+Conquest+Of+Time+(Instrumental)+-+Adhi.mp3") pygame.mixer.music.play()
6f885a4b5ca649bf8379e0ab7366b72b68a4c4cf
indiegoforlaunch/mood_light
/mood_light/mood_light.py
8,309
3.5
4
import magichue import csv import attributes from functools import partial import time class LightSource: """ Contains data and functions relevant to a single light source. The consumer will be able to power on and off the light source, set different modes (with different patterns and speeds), colors, brightness, and white values (warm or cold). """ def __init__(self, name, ip_addr, room): """ Initialize and create a light source, off by default :param name: string to identify the light source :param ip_addr: string ip address the light source is at :param room: string to identify the room the light source is in """ self.name = name self.ip_addr = ip_addr self.room = room self.light_source = magichue.Light(ip_addr) def power_on(self): """ Turns the light source on :return: n/a """ self.light_source.on = True def power_off(self): """ Turns the light source off :return: n/a """ self.light_source.on = False def current_color(self): """ Returns the current RGB value of the light source :return: integer tuple for red, green, and blue ranging from 0-255 """ return self.light_source.rgb def enable_color(self): """ Turns off the white LEDs and turns on the color LEDs :return: n/a """ self.light_source.is_white = False def disable_color(self): """ Turns off the color LEDs and turns on the white LEDs :return: n/a """ self.light_source.is_white = True def set_white(self, warm_white, cold_white): """ Sets the white LEDs color to be warm or cold :param warm_white: integer value ranging from 0-255 :param cold_white: integer value ranging from 0-255 :return: n/a """ # turn off color mode so white LED's work self.disable_color() # change the value of warm to cold whites self.light_source.w = warm_white self.light_source.cw = cold_white def set_rgb_color(self, red, green, blue): """ Sets the different levels of red, green, or blue LEDs :param red: integer value ranging from 0-255 :param green: integer value ranging from 0-255 :param blue: integer value ranging from 0-255 :return: n/a """ # turn on color mode self.enable_color() # change the values of red, blue, and green LEDs self.light_source.r = red # sleep allows commands to get to the bulb and allow time # for processing or colors will not change time.sleep(0.2) self.light_source.g = green time.sleep(0.2) self.light_source.b = blue time.sleep(0.2) def set_hsb_color(self, hue, saturation, brightness): """ Sets the different levels of hue, saturation, or brightness LED's :param hue: float value ranging from 0-1 :param saturation: float value ranging from 0-1 :param brightness: integer value ranging from 0-255 :return: n/a """ # turn on color mode self.enable_color() # change the values of hue, saturation, and brightness self.light_source.hue = hue # sleep allows commands to get to the bulb and allow time # for processing or colors will not change time.sleep(0.2) self.light_source.saturation = saturation time.sleep(0.2) self.light_source.brightness = brightness time.sleep(0.2) def toggle_fade(self): """ Toggle the fade effect when changing colors on or off :return: n/a """ if self.light_source.allow_fading is False: self.light_source.allow_fading = True else: self.light_source.allow_fading = False def current_mode(self): """ Returns the string name of the current built in flash pattern mode :return: string name of mode """ return self.light_source.mode.name def set_mode(self, mode): """ Sets flash pattern mode to built in pattern from magichue lib :param mode: magichue object the defines the type of mode :return: n/a """ self.light_source.mode = mode def set_speed(self, speed): """ Sets the speed at which the mode flashes to :param speed: float value ranging from 0-1 :return: n/a """ self.light_source.speed = speed def name_checker(num_of_new_lights, current_lights): # check to see if generic name is currently in the list generic_name = 'New Light ' + str(num_of_new_lights) if current_lights: if not any([True for item in current_lights if generic_name == item.name]): num_of_new_lights += 1 generic_name = 'New Light ' + str(num_of_new_lights) # recurse through the function until at a generic name # that does not currently exist name_checker(num_of_new_lights, current_lights) return generic_name def discover_bulbs(current_lights): # keep track of all the new lights being added num_of_new_lights = 0 # get a list all of bulb addresses found on LAN all_lights = magichue.discover_bulbs() # scan through list of current lights to find which ones are new for new_light in all_lights: num_of_new_lights += 1 # create generic name based on number of new lights # being added as long as it does not currently exist generic_name = name_checker(num_of_new_lights, current_lights) # only add if ip address is not already present if not any([True for item in current_lights if item.ip_addr == new_light]): # create a new light source and added it to current list add_light = LightSource(generic_name, new_light, 'Unknown') current_lights.append(add_light) def color_selector(light_source): # set the light source to on light_source.power_on() # print out the list of colors available to choose from for key in attributes.rgb_colors: print(key) # accept user input and change the color of the light source color = input("Select a color: ") if color in attributes.rgb_colors: colors = attributes.rgb_colors.get(color) light_source.set_rgb_color(colors[0], colors[1], colors[2]) def save_lights_to_file(current_lights): # save list of current light sources to the csv file # for later loading with open('docs/light_list.csv', 'w', newline='') as csv_file: file_writer = csv.writer(csv_file, delimiter=',') for item in current_lights: file_writer.writerow([item.name, item.ip_addr, item.room]) def load_lights_from_file(): # load list of current light sources from csv file # and create a list of LightSource class objects from that current_lights = [] with open('docs/light_list.csv', newline='') as csv_file: file_reader = csv.reader(csv_file, delimiter=',') for row in file_reader: # break up the row into name, ip address, and room light_source = LightSource(row[0], row[1], row[2]) current_lights.append(light_source) return current_lights def options(current_lights, selection=0, light_source=0): switcher = { # add new bulbs from ip address scan 1: partial(discover_bulbs, current_lights), 2: partial(color_selector, light_source) } # get the selection from those available func = switcher.get(selection, lambda: "Invalid Selection") # execute the option selected func() def main(): current_lights = [] # Get all lights currently stored current_lights = load_lights_from_file() # get current light sources options(current_lights, 1) for item in current_lights: light_source = item # load options for user input options(current_lights, 2, light_source) save_lights_to_file(current_lights) if __name__ == "__main__": main()
1575b56a6da28194063a2f43cc0b2f5437def73a
arodrrigues/DP_CS_Code_ARodrigues
/Python_Contest/tournamentSelection.py
306
3.5
4
# def tournamentSelection(wins, data): wins = 0 for i in range(0,6,1): if data[i] == 'w': wins = wins + 1 if wins >= 5: print(1) elif wins == 3 or wins == 4: print(2) elif wins == 1 or wins == 2: print(3) else: print(-1)
bc3601a6d676f776353683f6633f497cc5518e35
joshanjohn/mysql-hotel_management
/B_update.py
4,139
3.5
4
import app def changeNo(): #update B_no mydb = app.connection.connect() cursor = mydb.cursor() no = input('\nWhich B_name is Updating :') assgn = int(input('New B_no = ')) a = "update booking set B_no={} where B_name='{}'".format(assgn,no) cursor.execute(a) mydb.commit() mydb.close() print('B_no Updated successfully \n\n') #app.B_display.showall() #display updates b = input('see Updates (yes/no) ->') if b == 'y' or b == 'Y' or b == 'yes' or b == 'YES': app.B_display.showall() else: print('') #changeNo() def changeName(): #change B_name mydb = app.connection.connect() cursor = mydb.cursor() no = int(input('Which B_no is Updating :')) assgn = input('New B_Name = ') a = "update booking set B_name='{}' where B_no={}".format(assgn,no) cursor.execute(a) mydb.commit() mydb.close() print('B_Name Updated successfully ^_^\n\n') #app.B_display.showall() #display updates b = input('see Updates (y/n) ->') if b == 'y' or 'Y' or 'yes' or 'YES': app.B_display.showall() else: print('') #changeName() def changeAddress(): #change B_address mydb = app.connection.connect() cursor = mydb.cursor() no = int(input('Which B_no is Updating :')) assgn = input('New B_address = ') a = "update booking set B_address='{}' where B_no={}".format(assgn,no) cursor.execute(a) mydb.commit() mydb.close() print('B_address Updated successfully ^_^\n\n') #app.B_display.showall() #display updates b = input('see Updates (y/n) ->') if b == 'y' or 'Y' or 'yes' or 'YES': app.B_display.showall() else: print('') #changeAddress() def changePhno(): #update Ph_No mydb = app.connection.connect() cursor = mydb.cursor() no = int(input('\nWhich B_no is Updating :')) assgn = int(input('New Ph_no = ')) a = "update booking set Ph_No={} where B_no={}".format(assgn,no) cursor.execute(a) mydb.commit() mydb.close() print('Phone No Updated successfully \n\n') #app.M_display.showall() #display updates b = input('see Updates (yes/no) ->') if b == 'y' or 'Y' or 'yes' or 'YES': app.B_display.showall() else: print('') #changePhno() def changeEmail(): #change Email mydb = app.connection.connect() cursor = mydb.cursor() no = int(input('Which B_no is Updating :')) assgn = input('New Email = ') a = "update booking set Email='{}' where B_no={}".format(assgn,no) cursor.execute(a) mydb.commit() mydb.close() print('Email Updated successfully ^_^\n\n') #app.M_display.showall() #display updates b = input('see Updates (y/n) ->') if b == 'y' or 'Y' or 'yes' or 'YES': app.B_display.showall() else: print('') #changeEmail() def changeDate(): #change date mydb = app.connection.connect() cursor = mydb.cursor() no = int(input('Which B_no is Updating :')) assgn = input('New Date (yyyy-mm-dd) = ') a = "update booking set B_date='{}' where B_no={}".format(assgn,no) cursor.execute(a) mydb.commit() mydb.close() print('Date Updated successfully ^_^\n\n') #app.M_display.showall() #display updates b = input('see Updates (y/n) ->') if b == 'y' or 'Y' or 'yes' or 'YES': app.B_display.showall() else: print('') #changeDate() def changeClass(): #change date mydb = app.connection.connect() cursor = mydb.cursor() no = int(input('Which B_no is Updating :')) assgn = input('New Class = ') a = "update booking set Class='{}' where B_no={}".format(assgn,no) cursor.execute(a) mydb.commit() mydb.close() print('Class Updated successfully ^_^\n\n') #app.M_display.showall() #display updates b = input('see Updates (y/n) ->') if b == 'y' or 'Y' or 'yes' or 'YES': app.B_display.showall() else: print('') #changeClass()
7c35f6e372f479d2d5a5dd1f2e90fedf030afda0
indo-seattle/python
/Sandesh/Week3_0324-0330/CollectionDataTypes/10_CountEachStatefromList.py
458
4.03125
4
#Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times each state appeared in the list. mylist = ["WA", "CA", "NY", "IL", "WA", "CA", "WA"] for x in mylist: print(mylist.count(x),x) print("WA is", mylist.count("WA"), "in the list") print("CA is", mylist.count("CA"), "in the list") print("NY is", mylist.count("NY"), "in the list") print("IL is", mylist.count("IL"), "in the list")
383e8a8e35daf9e4b5d3335ce3585f0150b1bc46
Leo-X/my_python
/graphics.py
484
3.796875
4
import re line="fsjknfdjknbfkdl;sfl" line2 = "Cats are smarter than dogs" # reg_str='^f.*l$' reg_str=r'(.*) are (.*?) .*' # result=re.match(reg_str,line2).group(0,1,2) # result=re.match(reg_str,line2).groups() result=re.finditer(reg_str,line2) #匹配所有的并作为迭代器返回 # result=re.match(reg_str,line).group() for item in result: print('item:', item.group()) # if re.match(reg_str,line): # print('result:', 'yes') # else: # print('result:', 'not match')
71ae82df16f921dba43e0a9720d746745210aa0c
Tepau/GrandPyBot
/app/geocode.py
1,486
3.625
4
import googlemaps import os class GoogleMap: """class who recovers informations about a place through the api "googlemap\"""" def __init__(self): self.gmaps = googlemaps.Client(key=os.environ.get('KEY')) def find_adress(self, search): # Get the full adress of a place geocode_result = self.gmaps.geocode(search) adress = geocode_result[0]["formatted_address"] return adress def find_location(self, search): # Get the longitude and latitude of a place geocode_result = self.gmaps.geocode(search) latitude = geocode_result[0]["geometry"]["location"]["lat"] longitude = geocode_result[0]["geometry"]["location"]["lng"] return (latitude, longitude) def wiki_search(self, search): # Get informations needed for a wikipedia research geocode_result = self.gmaps.geocode(search) location = geocode_result[0]["address_components"][1]["long_name"] ville = geocode_result[0]["address_components"][2]["long_name"] if len(geocode_result[0]["address_components"]) > 5: pays = geocode_result[0]["address_components"][5]["long_name"] return location + ", " + ville + ", " + pays return location + ", " + ville if __name__ == '__main__': app = GoogleMap() print(app.find_adress('openclassrooms paris')) print(app.find_location('openclassrooms paris')) print(app.wiki_search('openclassrooms paris'))
7287ec1c482885e6e1cb6f1fcaa635974cf943c6
sonyjagatap/MedhaTraining
/Himangi/Assignments/validatephone - Copy.py
747
3.859375
4
phoneNo=raw_input("Please enter Phone no.: ") def validate(phoneNo): y = 0 for i in range(0, len(phoneNo)): if phoneNo[i].isdigit(): y=y+1 else: break if(y==11): if(phoneNo[0]=='1' and phoneNo[1]!='0' and phoneNo[4]!='0'): print "USA phone no" else: print "oops! not a valid no." + phoneNo[0] elif(y==12): if(phoneNo[0]=='9' and phoneNo[1]=='1' and phoneNo[2]!='0' and phoneNo[4]!='0'): print "india phone no" else: print "oops! not a valid no. here i am" + phoneNo[3] else: print "Please enter a valid no." validate(phoneNo)
fece2ab9b92d8c8b2f5c34bcbdf029b0ed669099
Jabed27/Data-Structure-Algorithms-in-Python
/Program templates/Comparator/comparator and Sorting().py
947
4.125
4
L=[15,10,9,7,4,2] L.sort() print(L) L.sort(reverse = True) #descending order print(L) #If you want to create a new sorted list without # modifying the original one, you should use the sorted function instead. L = [15, 22.4, 8, 10, 3.14] sorted_list = sorted(L) print(sorted_list) sorted(L, reverse = True) #descending print(sorted_list) #Sorting list of tuples #sort by age or sort by second element L = [("Alice", 25), ("Bob", 20), ("Alex", 5)] L.sort(key=lambda x: x[1]) print(L) # output # [('Alex', 5), ('Bob', 20), ('Alice', 25)] #Sorting a list of objects class User: def __init__(self, name, age): self.name = name self.age = age L=[] L.append(User('sajid',20)) L.append(User('rain',25)) L.append(User('sachi',22)) L.sort(key=lambda x: x.name) print([item.name for item in L]) # output: ['Alice', 'Bob', 'Leo'] L.sort(key=lambda x: x.age) print([item.name for item in L]) # output: ['Leo', 'Bob', 'Alice']
1b160ac54fa89127837328690d88cb7769cdb643
Vlad-Harutyunyan/interview_tasks
/interviewTask/main.py
4,213
3.546875
4
import threading as t import time import random from queue import Queue #init max queue size and buffer size for threads MAX_QSIZE = 100 BUFF_SIZE = 20 #Producer class class ProducerThread: def __init__(self, queue, sm ): #init queue self.queue = queue #init queue self.s = sm # init semaphore def run(self): #mehtod for Producer class starting try: #try to catch keyboard interrupt error , still doesnt work #if queue doesnt full ,we also can use queue class full method with not while self.queue.qsize() < 100 : self.s.release() #Acquire a semaphore. item = random.randint(1,101) #random number in 1-100 range self.queue.put(item) # insert random number to queue print('Putting: {} elements in queue'.format(self.queue.qsize()) ) time.sleep(random.random()) # sleep random miliseconds in range 0.1 - 0.99 ~ 10 - 99.99 milliseconds if self.queue.qsize() == 100: #if queue size is full stop threads and alert in console print('Queue is full,producer waiting...') self.s.acquire() # Thread sleep if self.queue.qsize() == 80 : self.s.release()#Thread wake up except KeyboardInterrupt: # still doesnt work , print('ok') hust for testing print('ok') #Consumer Class class ConsumerThread: def __init__(self, queue ,sm):#iniit queue self.queue = queue # init qeuee self.s = sm #init semaphore def run(self): try: #try to catch keyboard interrupt error , still doesnt work while not self.queue.empty(): # if queue is not empty item = self.queue.get() # getting first item from queue (FIFO-first in first out) f = open('data.txt' , 'a+')#open data.txt file a+ (we can open and add new text without deleting old text in this file) f.write(str(item)) f.close() # close file , if we doesnt close file , loop doesnt work self.s.release() self.queue.task_done() # Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. print ('Getting: {} elements in queue'.format(self.queue.qsize()) ) time.sleep(random.random()) # sleep random miliseconds in range 0.1 - 0.99 ~ 10 - 99.99 milliseconds self.s.acquire() print ("consumer:Waiting...") except KeyboardInterrupt: print('ok') def main(prod_count,cons_conut): q = Queue(maxsize=MAX_QSIZE) #init queue Producer_Thread_List = [] # list for all producer threds for i in range(prod_count):# appending N conut threads to list # creating semaphore for multiprocessroing s = t.Semaphore(prod_count) producer = ProducerThread(q,s) producer_thread = t.Thread(target=producer.run , name = f'poducer_{i}') Producer_Thread_List.append(producer_thread) Consumer_Thread_List = [] # list for all consumer threds for i in range(cons_conut): # appending N conut threads to list # creating semaphore for multiprocessroing s = t.Semaphore(cons_conut) consumer = ConsumerThread(q,s) consumer_thread = t.Thread(target=consumer.run , name = f'consumer_{i}') Consumer_Thread_List.append(consumer_thread) for elem in Producer_Thread_List:#start all producer threads elem.start() for elem in Consumer_Thread_List:#start all consumer threads elem.start() q.join() # Blocks until all items in the queue have been gotten and processed. if __name__ == '__main__': prod_count = int(input('Please enter number of producers : ')) #getting count of producers thread cons_count = int(input('Please enter number of consumers : ')) #getting count of consumers thread try:#try catch error here still doesnt work main(prod_count,cons_count) except KeyboardInterrupt: print('Please wait')
cdf27c88d18992aced7188e8f419c440ef7fdd21
akshay-sahu-dev/PySolutions
/GeeksforGeeks/Kth Smallest element.py
246
3.578125
4
#https://practice.geeksforgeeks.org/problems/kth-smallest-element/ for i in range(int(input())): N = int(input()) Ar = list(map(int,input().split())) k = int(input()) Min = Ar[-1] Ar.sort() print(Ar[k-1])
7c2ea61fd7c043b74e191e5e7a6baa16ae644397
shujuan/leetcode
/python/connecting_graph3.py
1,124
3.78125
4
class ConnectingGraph3: """ @param a: An integer @param b: An integer @return: nothing """ def __init__(self, n): self.cnt = n self.father = {} for i in range(1,n+1) : self.father[i] = i # def find(self, a): # if (self.father[a] == a): # return a # return self.find(self.father[a]) def find(self, node): path = [] while node != self.father[node]: path.append(node) node = self.father[node] for n in path: self.father[n] = node return node def connect(self, a, b): # write your code here root_a = self.find(a) root_b = self.find(b) if (root_a != root_b) : self.father[root_a] = root_b self.cnt -= 1 """ @return: An integer """ def query(self): return self.cnt # write your code here test = ConnectingGraph3(5) res = [] res.append(test.query()) test.connect(1,2) res.append(test.query()) print(res)
e0e2d7775f9284770b87bc57d625612b8ad64998
w10pp/LeetCode-Practice
/49_GroupAnagrams.py
333
3.625
4
''' LeetCode Python Practice 49.Group Anagrams ''' class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: dictionary = {} for word in sorted(strs): key = tuple(sorted(word)) dictionary[key] = dictionary.get(key, []) + [word] return dictionary.values()
f4937c222674c91bfec21cdfdb014bb3d08f0564
diegogcc/py-pluralsight
/advanced/advanced-python/8-abstract_base_classes/weapons04.py
3,694
3.78125
4
""" Implementing abstract base classes using the standard library abc abc module - ABCMeta metaclass - ABC base class - @abstracmethod decorator can also be combined with other decorators (@staticimethod, @classmethod and @property) as long as @abstractmethod is the innermost one. class AbstractBaseClass(ABC): @staticmethod @abstractmethod def an_abstract_static_method(): raise NotImplementedError Declase abstract methods: abstract method: a method which is declared bt which doesn't have a useful definition must be overridden in concrete classes For @properties: they are implemented using descriptors. For own descriptor implementations: The descriptor should identify as abstract by implementing __isabstractmethod__() class MyDataDescriptor(ABC): @abstractmethod def __get__(self, instance, owner): pass @abstractmethod def __set__(self, instance, value): pass @abstractmethod def __delete__(self, instance): pass @property def __isabstractmethod__(self): return True # or False if not abstract Example: class AbstractBaseClass(ABC): @property @abstractmethod def abstract_property(self): raise NotImplementedError @property def concrete_property(self): return "sand, cement, water" AbstractBaseClass.abstract_property.__isabstractmethod__ # True AbstractBaseClass.concrete_property.__isabstractmethod__ # False """ from abc import ABC, abstractmethod class Sword(ABC): # virtual base class @classmethod def __subclasshook__(cls, sub): return ((hasattr(sub, 'swipe') and callable(sub.swipe) and hasattr(sub, 'parry') and callable(sub.parry) and hasattr(sub, 'thrust') and callable(sub.thrust) and hasattr(sub, 'sharpen') and callable(sub.sharpen)) or NotImplemented) @abstractmethod def swipe(self): raise NotImplementedError # must be overridden in concrete class @abstractmethod def parry(self): raise NotImplementedError # must be overridden in concrete class @abstractmethod def thrust(self): print("Thrusting...") class BroadSword(Sword): def swipe(self): print("Swoosh!") def sharpen(self): print("Shink!") class BroadSword2(Sword): def swipe(self): print("Swoosh!") def thrust(self): super().thrust() def parry(self): print("Parry") def sharpen(self): print("Shink!") class SamuraiSword: def swipe(self): print("Slice!") def sharpen(self): print("Shink!") class Rifle: def fire(self): print("Bang!") if __name__ == "__main__": """ If we now make BroadSword an explicit subclass of Sword, we won't be able to instantiate it because we haven't implemented parry and thrust""" # broad_sword = BroadSword() # TypeError: Can't instantiate abstract class BroadSword with abstract methods parry, thrust """ We have to implement those methods in the concrete class (see BroadSword2) """ broad_sword = BroadSword2() """ The requirement of implementation of abstractmethods only applies for explicit subclasses. For SamuraiSword, it's not necessary to implement parry() and thrust() """ samurai_sword = SamuraiSword()
2120354617034cca247e025750f3bd4518ef466e
JagadeeshJK/Python
/list.py
178
3.6875
4
list = ['maths', 'social', 99, 100]; print("value available at index 2 :") print(list[2]) list[2] = 101; print("new value available at index 2 :") print(list[2]) print(list[2:3])
ad29e777069784539f37f90e14dc11beea1319ee
jinloke22/python
/FX重温python基础.py/class/jcsy_class.py
611
3.96875
4
class Animal(): def __init__(self,name,age): self.name = name self.age = age self.__money = 1000 @staticmethod def __test(): print("我是Animal中的私有方法") class Person(Animal): def __demo(self): print("我是Person中的私有方法") p = Person("jin",21) p._Person__demo() #p._Person__test() p._Animal__test() q = Person("wei",21) #isinstance用于判断是否是属于这个类 print(isinstance(q,Person)) print(isinstance(q,Animal)) #issubclass拥有判断一个类是不是属于其父类 print(issubclass(Person,Animal))
96b4c7c072bae0c5e4544f6c050794cceb478426
petey9891/CSV-JSONPY
/csv-to-json/csv_to_json.py
620
3.765625
4
import csv import json """ Converts CSV file with two columns into JSON file with dictionary format """ def csv_to_json(): # file = <input file> with open(file, "r") as csvfile: csv_list = [] reader = csv.reader(csvfile, delimiter=",") for row in reader: csv_list.append(row) csvfile.close() csv_list.pop(0) csv_dict = {} for row in csv_list: csv_dict[row[0]] = row[1] jsonfile = open("../resources/json_info.json", "w") json.dump(csv_dict, jsonfile, indent=4) jsonfile.close() if __name__ == "__main__": csv_to_json()
2873e22cff5c771ae8379d9002a69fe3792fab17
toncysara17/luminarpythonprograms
/Advance_Python/Polymorphism/methodovrloadng.py
329
3.78125
4
#Polymorphism means "many forms" #Method Overloading #Method overriding class Person: def show(self,num1): self.num1=num1 print(self.num1) class Student(Person): def show(self,num2,num3): self.num2=num2 self.num3=num3 print(self.num2,self.num3) per=Student() per.show(3,4)
9aee4347b18e20e71991dd52682697d23724127f
barvaliyavishal/DataStructure
/Leetcode Problems/48. Rotate Image .py
520
3.5625
4
def rotate(matrix): n = len(matrix[0]) for i in range(n // 2 + n % 2): for j in range(n // 2): tmp = [0] * 4 row, col = i, j for k in range(4): tmp[k] = matrix[row][col] row, col = col, n - 1 - row for k in range(4): matrix[row][col] = tmp[(k - 1) % 4] row, col = col, n - 1 - row arr = [[1,2,3],[4,5,6],[7,8,9]] rotate(arr) for i in arr: for j in i: print(j,end=" ") print()
15843785d7029b0d67f185f51675953bd15e4b02
meking03/MIT6001
/problem sets/ps1/ps1c.py
3,507
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sun May 3 20:18:24 2020 @author: egultekin """ def calcTotalSaving(annualSalary, savingRate, roi, semiAnnualRaise): monthPassed = 0 # this first guess is your saving rate, calculate your total savings in 36 months with this guess (saving rate) totalSaving = 0 monthlySaving = (annualSalary / 12) * savingRate # first month where there is no return from investment totalSaving = totalSaving + monthlySaving monthPassed += 1 # remaining 35 months (monthly saving, return from investment, salary raise every 6 months) for month in range(2, 37): # incrementing total saving by roi totalSaving = totalSaving * (1 + (roi / 12)) # increasing total saving by monthly saving totalSaving += monthlySaving monthPassed += 1 # updating annual salary and monthly saving semi annually if month % 6 == 0: annualSalary = annualSalary * (1 + semiAnnualRaise) monthlySaving = (annualSalary / 12) * savingRate return totalSaving def findSavingRate(annualSalary, downPaymentNeeded, roi, semiAnnualRaise): # initialize local variables # epsilon epsilon = 10 # num of guesses numGuesses = 0 # binary search variables: low, high, initial guess = mid point in search space # savings rate range: 0 - 1 low = 0 high = 1 guess = (high + low) / 2.0 #calculate total savings usıng initial guess totalSaving = calcTotalSaving(annualSalary, guess, roi, semiAnnualRaise) # execute binary search: update your guess by comparing the total savings to the expected result, guess will always be the middle point of our search space # If total savıngs below result, then we need to increase our guess, which means we ll need to search ın the upper half of the search space # and vice versa while abs(totalSaving - downPaymentNeeded) >= epsilon: if totalSaving < downPaymentNeeded: # look in the upper half search space low = guess else: # look in the lower half search space high = guess # next guess is halfway in the new search space guess = (high + low) / 2.0 numGuesses += 1 ###calculating total saving with the new guess totalSaving = calcTotalSaving(annualSalary, guess, roi, semiAnnualRaise) # once we reach a satisfactory result, exit the loop and return the result return guess, numGuesses def main(): # annual salary annualSalary = float(input('Enter your annual salary: ')) # salary raise every six months semiAnnualRaise = float(input('Enter your semi annual raise: ')) # annual return of investments roi = float(input('Enter your annual return on investment: ')) # portion of down payment needed for the house downPayment = float(input('Enter your portion of down payment for the house: ')) # total cost of the house totalCost = float(input('Enter total cost of the house: ')) # down payment needed for the house downPaymentNeeded = totalCost * downPayment # calculate saving rate savingRate, numGuesses = findSavingRate(annualSalary, downPaymentNeeded, roi, semiAnnualRaise) # print the output print('number of guesses =', numGuesses) print('Your saving rate should be ' + str(savingRate)) main()
bf3d837c3822d4117be63bd68b7853b9dc88708a
kbeisiegel/LearnPythonTheHardWay
/ex44c.py
241
3.515625
4
class Other(object): def implicit(self): print("OTHER implicit") class Dog(object): def __init__(self): self.other = Other() def implicit(self): self.other.implicit() animal = Dog() animal.implicit()
1e683f81351d1e46a097795a7d8b7edc247e8159
sankeerth/Algorithms
/Backtracking/python/leetcode/expression_add_operators.py
2,838
4.375
4
""" 282. Expression Add Operators Given a string num that contains only digits and an integer target, return all possibilities to add the binary operators '+', '-', or '*' between the digits of num so that the resultant expression evaluates to the target value. Example 1: Input: num = "123", target = 6 Output: ["1*2*3","1+2+3"] Example 2: Input: num = "232", target = 8 Output: ["2*3+2","2+3*2"] Example 3: Input: num = "105", target = 5 Output: ["1*0+5","10-5"] Example 4: Input: num = "00", target = 0 Output: ["0*0","0+0","0-0"] Example 5: Input: num = "3456237490", target = 9191 Output: [] Constraints: 1 <= num.length <= 10 num consists of only digits. -231 <= target <= 231 - 1 """ from typing import List class Solution: def addOperators(self, num: str, target: int) -> List[str]: if target > 0 and int(num) == target: return [num] operators = ['+', '-', '*'] n, res = len(num), [] def evaluate(expression): stack = [] cur, op = 0, '+' for i, e in enumerate(expression): if e.isdigit(): cur = int(e) if e in operators or i == len(expression)-1: if op == '+': stack.append(cur) elif op == '-': stack.append(-1 * cur) elif op == '*': stack.append(stack.pop() * cur) op = e total = 0 while stack: total += stack.pop() return total def addOperatorsRecursive(i, expression): if i == len(num): ret = evaluate(expression) if ret == target: res.append("".join(expression)) return for j in range(i, len(num)): integer = num[i:j+1] if integer[0] == '0' and len(integer) > 1: # imp to not create numbers with 0 as prefix return expression.append(integer) if j == len(num)-1: addOperatorsRecursive(j+1, expression) else: for op in operators: expression.append(op) addOperatorsRecursive(j+1, expression) expression.pop() expression.pop() addOperatorsRecursive(0, []) return res sol = Solution() print(sol.addOperators("123", 6)) print(sol.addOperators("123", 123)) print(sol.addOperators("6", 6)) print(sol.addOperators("232", 8)) print(sol.addOperators("105", 5)) print(sol.addOperators("00", 0)) print(sol.addOperators("3456237490", 9191)) print(sol.addOperators("123456789", 45)) # failed testcase
b2e030ef91d59ddcf24e21f0d3b37bcf65a193bc
Patchers/dungeon_game
/main.py
1,913
3.984375
4
from random import randint, choice ENEMIES = [{ "name" : "drake", "hp" : 50, "attack" : 50, "magic" : 25 }, { }] def init_player(): user = {} user_name = (input('Greetings. What is your name? > ')) valid_user = False while not valid_user: user_class = (input("Warrior or Mage? > ")) if user_class.lower() == "warrior": user["hp"] = randint(50,60) user["attack"] = randint(55,65) user["magic"] = 0 valid_user = True elif user_class.lower() == "mage": user["hp"] = randint(45,55) user["attack"] = randint(57,70) user["magic"] = randint(20,40) valid_user = True else: print("Please enter a valid choice.") user["name"] = user_name user["class"] = user_class print("Welcome " + user["name"] + " the " + user["class"] + ".") print("Your health is at: " + str(user["hp"]) + "\nYour attack power is: " + str(user["attack"])+ "\nYour magic level is: " + str(user["magic"])) return user #0. Function - init Player #1. Function - Attack def attack(player, enemy, strike = 1): ''' { "name" : #, "hp" : #, "attack" : # } ''' duel = [player, enemy] # random strike selection fighter = choice([0,1]) opponent = abs(fighter - 1) print("Strike {} made by {}!".format(strike,duel[fighter]["name"])) # random strike power strike_power = randint(0,duel[fighter]["attack"]) # reduce opponent hp duel[opponent]["hp"] = duel[opponent]["hp"] - strike_power # check hp > 0 return #2. Function - post_battle (XP) if __name__ == "__main__": test_user = { "name" : "danie", "attack": 50, "hp":50 } test_enemy = { "name" : "evil danie", "attack": 50, "hp":50 } player = init_player() attack(test_user, test_enemy) # call init player Function # loop through enemies ## call attack function ## evaluatue result and update post battle
6676605dcc3645833220f946e84863e37091a902
emma-metodieva/SoftUni_Python_Advanced_202106
/06. File Handling/06-02-02. Line Numbers.py
846
3.65625
4
# 06-02. File Handling - Exercise # 02. Line Numbers import os import string def count_letters(characters): count = 0 for char in characters: if char.isalpha(): count += 1 return count def count_punctuation(characters): count = 0 for char in characters: if char in string.punctuation: count += 1 return count current_dir = os.path.dirname(os.path.abspath(__file__)) input_path = os.path.join(current_dir, "Exercise Files", "06-02-02", "input.txt") output_path = os.path.join(current_dir, "Exercise Files", "06-02-02", "output.txt") with open(input_path) as in_file: text = in_file.read().split('\n') with open(output_path, "w") as file: for i, line in enumerate(text): file.write(f"Line {i+1}: {line} ({count_letters(line)}) ({count_punctuation(line)})\n")
ccda78d12aa8da2092666c2ad24f85b50d2d5b34
Manoj-sahu/datastructre
/ArraysAndStrings/1.5.py
896
3.75
4
#program to find two strings are one character away or not s1 = 'pale' s2 = 'bake' def checkOneAway(s1, s2): if len(s1) == len(s2): print(onEditReplace(s1, s2)) elif len(s1) + 1 == len(s2): print(onRemoveReplace(s1,s2)) elif len(s1) -1 == len(s2): print(onRemoveReplace(s1, s2)) def onEditReplace(s1, s2): onDiffFound = False for i in range(len(s1)): if s1[i] != s2[i]: if(onDiffFound): #here it's comes mean there is second diff also return False onDiffFound = True return onDiffFound def onRemoveReplace(s1, s2): i1 = 0 i2 = 0 while i2 < len(s2) and i1 < len(s1): if s1[i1] != s2[i2]: if i1 != i2: return False i2 += 1 else: i1 += 1 i2 += 1 return True checkOneAway(s1, s2)
8c456e84cfedcfbd9062c0ab0b868c38d49cc1d1
Paraniod1/Project
/课程作业/回文数变形计.py
402
3.546875
4
# -*- codeing = utf-8 -*- # @Time : 2021/9/20 18:06 # @Author : chao # @File : 回文数变形计.py # @Software : PyCharm n = input() # n= 12 i = 1 # print(n[:]) # 12 # print(n[::-1]) # 21 while i < 7: a = eval(n[:]) + eval(n[::-1]) # print(a) a = str(a) if a[:] == a[::-1]: print(i) break elif i < 7: n = a i = i + 1 if i == 7: print(0)
5ad2e260b43c595e72050ef72c741dd1de94d56b
prmelehan/PolyAlphabeticCipher
/de-enc.py
3,077
3.984375
4
#import system for Python version check import sys #Check to see if python version is version 3 if(sys.version_info[0] < 3): exit("Python 3 is required") # A script that decrypts a Poly Alphabetic Cipher sentence = input("Gimme your encoded phrase: ") shiftword = input("Provide shift word: ") shiftletters = list(shiftword) # In this case. The letters are from the encrypted phrase letters = list(sentence) if(len(shiftletters) == 0 or len(sentence) == 0): exit("Both a passphrase and an encoded phrase is required") #print(letters) PolyDict = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25, 'A':26, 'B':27,'C':28,'D':29,'E':30,'F':31,'G':32,'H':33,'I':34,'J':35,'K':36,'L':37,'M':38,'N':39,'O':40,'P':41,'Q':42,'R':43,'S':44,'T':45,'U':46,'V':47,'W':48,'X':49,'Y':50,'Z':51,'1':52,'2':53,'3':54,'4':55,'5':56,'6':57,'7':58,'8':59,'9':60,'0':61,'!':62,'@':63,'#':64,'$':65,'%':66,'^':67,'&':68,'*':69,'(':70,')':71,'-':72,'+':73,'=':74,':':75,';':76,'"':77,"'":78,',':79,'<':80,'>':81,'.':82,'?':83,' ':84} #create a check to see if the input is in the dictionary notInDictErrorMsg = "Invalid Chracters: One or more characters in your phrase or passcode is not accepted by this program" #Check the phrase for valid characters for letter in sentence: if(letter in PolyDict): pass else: exit(notInDictErrorMsg) #Check the passcode for valid chracters for letter in shiftword: if(letter in PolyDict): pass else: exit(notInDictErrorMsg) ##end check for dictionary # A function that replaces ord() with a custom indexing function for the PolyDict dictionary def find_value(letter): letter = str(letter) key = PolyDict[letter] return int(key) def find_key(val): for key in PolyDict.keys(): if PolyDict[key] == val: return str(key) ordinated = [] for letter in letters: #Converting all letters to their PolyDict equivilants ordinatedLetter = find_value(letter) ordinated.append(ordinatedLetter) #print(ordinated) #Shift all the numbers by the "Ordinated" value of the first letter #Use the shift word to un-shift the encrypted characters usedChars = [] allshifted = [] #Shift based on word for number in ordinated: #Get first letter in shift word array] #First check to see if it is empty if(len(shiftletters) > 0): shiftLetter = shiftletters[0] #print(shiftLetter) convertedLetter = find_value(shiftLetter) #print(convertedLetter) shiftByNum = (number - convertedLetter) % 85 #print(number) allshifted.append(shiftByNum) usedChars.append(shiftLetter) shiftletters.remove(shiftLetter) if(len(shiftletters) == 0): for element in usedChars: shiftletters.append(element) del usedChars[:] #print(usedChars, shiftletters) elif(len(shiftletters) == 0): for element in usedChars: shiftletters.append(element) del usedChars[:] #print(allshifted) encString = [] for number in allshifted: char = find_key(number) encString.append(char) #print(encString) print(''.join(encString))
f90af3b286de259dbebbbb9e4ed2a4943af5c434
alberzenon/Python_basic
/1.TiposDeDatosSImples/cociente_y_resto.py
635
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 2 23:46:57 2021 @author: alberto Escribir un programa que pida al usuario dos números enteros y muestre por pantalla la <n> entre <m> da un cociente <c> y un resto <r> donde <n> y <m> son los números introducidos por el usuario, y <c> y <r> son el cociente y el resto de la división entera respectivamente. """ n1 = input("Introduce el primer numero: ") n2 = input("Introduce el segundo numero: ") c=int(n1) // int(n2) r=int(n1) % int(n2) print("******* " +n1 + " entre " +n2 +" da un cociente de "+str(c)+" y un resto de: "+str(r)+" ********")
99307bb8f9c62cdfccd10eaad5440e40afd133d5
MrHamdulay/csc3-capstone
/examples/data/Assignment_1/smtada002/question3.py
787
3.9375
4
print("Enter first name:") first = input() print("Enter last name:") last = input() print("Enter sum of money in USD:") money = eval(input()) print("Enter country name:") country = input() percent = (money/100)*30 print("\nDearest", first, "\nIt is with a heavy heart that I inform you of the death of my father,\nGeneral Fayk", last + ", your long lost relative from Mapsfostol. \nMy father left the sum of", str(money) + "USD for us, your distant cousins. \nUnfortunately, we cannot access the money as it is in a bank in", country + ".\nI desperately need your assistance to access this money.\nI will even pay you generously, 30% of the amount -", str(percent) + "USD,\nfor your help. Please get in touch with me at this email address asap.\nYours sincerely \nFrank", last)
d96852d0ca086a12065ba7ea169bdc5641b1bccc
Mjg79/reddit-backend
/reddit/accounts/utils.py
308
3.578125
4
import random import string def generate_random_username(length: int = 16) -> str: """Generate random user name Generate a random username that conforms to User model's custom username field :return: """ return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))
6faab902360039f3daa51c05ab683ca913149070
AmitGreen/TeacherSample
/Percentage.py
816
3.796875
4
# # Copyright (c) 2019 Amit Green. All rights reserved. # # # percentage__with_considering_0_of_0_as_100(top, bottom): # Calcuate `top / bottom` as a percentage with rounding. # # Calculate a percentage without rouding: *ONLY* using integers. # # This avoids the whole quagmire of the unsual behavior of `round` in python. # # NOTE: # `top` and `bottom` are used instead of numerator & denominator as they are easier nouns to remember. # def percentage__with_considering_0_of_0_as_100(top, bottom): assert (type(top) is int) and (0 <= top <= bottom) assert (type(bottom) is int) and (bottom >= 0) if bottom is 0: return 100 return ((top * 1000) // bottom + 5) // 10 # # Exports # __all__ = (( 'percentage__with_considering_0_of_0_as_100', ))
83436f42570c81d8ec0b89fed2a879c85b04402c
shinan0/python
/JOSEPH.py
625
3.75
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: def move(players,step): num = step - 1 while num > 0: tmp = players.pop(0) players.append(tmp) num = num - 1 return players def play(players,step,alive): list1=[i for i in range(1,players+1)] while len(list1) > alive: list1=move(list1, step) list1.pop(0) return list1 players_num=int(input("请输入参与游戏的人数 ")) step_num=int(input("请输入淘汰的数字 ")) alive_num=int(input("请输入幸存的人数 ")) alive_list=play(players_num, step_num, alive_num) print(alive_list) # In[ ]:
f79588992e352ed514f67a449ee58214d0383046
selvex/flee-vis
/outputanalysis/FormatPyplotFigures.py
539
3.640625
4
import matplotlib import matplotlib.pyplot as plt def set_margins(l=0.13,b=0.13,r=0.96,t=0.96): #adjust margins - Setting margins for graphs fig = plt.gcf() fig.subplots_adjust(bottom=b,top=t,left=l,right=r) def prepare_figure(xlabel="Days elapsed",ylabel="Number of refugees"): #prepares and formats a basic flee visualization figure. plt.clf() plt.xlabel(xlabel) plt.ylabel(ylabel) matplotlib.rcParams.update({'font.size': 20}) fig = matplotlib.pyplot.gcf() fig.set_size_inches(12, 8) set_margins() return fig
d8d494650e8bccb8b4ae6193c71dcbd6fc4d7709
EvertonSerpa/Curso_Guanabara_Python_Mundo01
/Exer_12.py
557
3.921875
4
'''Exercício Python 12: Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.''' print() preco = float(input('Toda a loja está com 5% de desconto!\n\nInforme o preço do produto para receber o desconto R$ ')) desconto = preco - (preco * 5 / 100) print(f'O valor do produto {preco:.2f}\ncom o desconto fica {desconto:.2f}') '''Explicando o código foi criado duas variaveis, a primeira recebe o valor do produto e a segunda faz o calculo da % e subtrai do valor do produto, assim dando o valor com o desconto.'''
8628795de3ba7161f4accdbe67ef698b8fd7b3b9
codacy-badger/pythonApps
/mobiusFunction.py
723
3.625
4
def isSquareFree(factors): for i in factors: if factors.count(i) > 1: return False return True def primeFactor(number): i = 2 factors = [] while i * i <= number: if number % i: i += 1 else: number //= i factors.append(i) if number > 1: factors.append(number) return factors def mobiusFunction(number): ''' define mobius fnction ''' factors = primeFactor(number) if isSquareFree(factors): if len(factors) % 2 == 0: return 1 elif len(factors) % 2 != 0: return -2 else: return 0 print(mobiusFunction(25)) print(primeFactor(120))
a6a73933b8e4f9aaf3002bf1d7f648c3b8ba50f0
LWZ7/algorithm
/leetcode/排序/合并K个排序链表.py
1,507
4.0625
4
''' 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: p = ListNode(0) head = p if not l1 and not l2: return None if l1 and not l2: return l1 if l2 and not l1: return l2 while l1 and l2: if l1.val <= l2.val: p.next = l1 l1 = l1.next else: p.next = l2 l2 = l2.next p = p.next if l2: p.next = l2 if l1: p.next = l1 return head.next def helper(self, lists: List[ListNode]) -> ListNode: a = len(lists) if a==1: return lists[0] else: a_left = self.helper(lists[0:int(a/2)]) a_right = self.helper(lists[int(a/2):]) head = self.mergeTwoLists(a_left , a_right) return head def mergeKLists(self, lists: List[ListNode]) -> ListNode: if len(lists)==0: return None head = self.helper(lists) return head ''' 通过递归树分析,算法的时间复杂度是(K-1)*log K + K '''
7b6fb8046b42e19c1c6eef02cb6f8b1e7e7077eb
NickjClark1/PythonClass
/Chapter 8/piglatintranslator.py
1,272
4.03125
4
def main(): word = input("word: ") print(translateWordToPigLatin(word)) def translateWordToPigLatin(word): if word[0] in "aeiouAEIOU" and not word[-1] in ",": word = (word + "yay") if word[0] in "aeiouAEIOU" and word[-1] in ",": word = (word[:-1] + "yay" + word[-1]) if word[0] not in "aeiouAEIOU" and word[-1] in "," and not word[0].isupper(): word = (word[1:-1] + word[0] + "ay" + word[-1]) if word[0] not in "aeiouAEIOU" and word[-1] in "." and not word[0].isupper(): word = (word[1:-1] + word[0] + "ay" + word[-1]) if word[0] not in "aeiouAEIOU" and not word[-1] in "," and not word[-1] in "." and not word[0].isupper(): word = (word[1:] + word[0] + "ay") if word[0] not in "aeiouAEIOU" and word[-1] in "," and word[0].isupper(): word = (word[1].upper() + word[2:-1] + word[0].lower() + "ay" + word[-1]) if word[0] not in "aeiouAEIOU" and word[-1] in "." and word[0].isupper(): word = (word[1].upper() + word[2:-1] + word[0].lower() + "ay" + word[-1]) if word[0] not in "aeiouAEIOU" and not word[-1] in "," and not word[-1] in "." and word[0].isupper(): word = (word[1].upper() + word[2:] + word[0].lower() + "ay") return word main()
5ed8646c849bdd5e6b63fdccfd9ce5b53ff9f0a6
vlacor99/numeros_complejos
/marbles.py
4,228
3.828125
4
from math import * import unittest def Suma_Resta(NumA,NumB,Op): """ PRE = Nos entran dos tuplas la cuales cada una es un numero imaginario NumA y NumB dentro de ellas la posicion [0] de cada una nos da la parte real y la parte [1] es la parte imaginaria, Ademas nos entra un Op el cual si es "1" hacemos suma entre complejos y si es "0" hacemos la resta entre complejos. POS = Devolvemos una tupla en la cual la posicion [0] nos da la parte real y la parte [1] es la parte imaginaria """ if Op==1: SumParteR = NumA[0]+NumB[0] SumParteI = NumA[1]+NumB[1] else: SumParteR = NumA[0]-NumB[0] SumParteI = NumA[1]-NumB[1] Respuesta = (SumParteR , SumParteI) return Respuesta def Multiplicacion(NumA,NumB): """ PRE = Nos entran dos tuplas la cuales cada una es un numero imaginario NumA y NumB dentro de ellas la posicion [0] de cada una nos da la parte real y la parte [1] es la parte imaginaria, hallamos ParteA y ParteD para al final sumarlos y hallar la parte real despues hallamos ParteB y ParteC las cuales sumamos para hallar la parte imaginaria. POS = Devolvemos una tupla en la cual la posicion [0] nos da la parte real y la parte [1] es la parte imaginaria """ ParteA=NumA[0]*NumB[0] ParteB=NumA[0]*NumB[1] ParteC=NumA[1]*NumB[0] ParteD=(NumA[1]*NumB[1])*(-1) SumParteR = ParteA+ParteD SumParteI = ParteB+ParteC Respuesta = (SumParteR , SumParteI) return Respuesta def Marbles_Booleanos(matrizAdj, estadoInicial, clicks): '''Se simula el experimento de las canicas despues de varios clicks UTILIZANDO suma y resta de numeros imaginarios''' while clicks > 0: clicks -= 1 aux = [] for i in range(len(matrizAdj)): sume = (0,0) for j in range(len(estadoInicial)): sume = Suma_Resta(sume,Multiplicacion(estadoInicial[j],matrizAdj[i][j]),1) aux.append(sume) estadoInicial = aux return aux def Marbles_Reales(matrizAdj, estadoInicial, clicks): '''Se simula el experimento de las canicas despues de varios clicks UTILIZANDO suma y resta de numeros imaginarios''' while clicks > 0: clicks -= 1 aux = [] for i in range(len(matrizAdj)): sume = (0,0) for j in range(len(estadoInicial)): sume = Suma_Resta(sume,Multiplicacion(estadoInicial[j],matrizAdj[i][j]),1) aux.append(sume) estadoInicial = aux return aux class MyTestCase(unittest.TestCase): def test_Marbles_Reales(self): result = Marbles_Reales([[(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)],[(1/2,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)],[(1/2,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)],[(0,0),(1/3,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)],[(0,0),(1/3,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)],[(0,0),(1/3,0),(1/3,0),(0,0),(0,0),(0,0),(0,0),(0,0)],[(0,0),(0,0),(1/3,0),(0,0),(0,0),(0,0),(0,0),(0,0)]],[(1,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)],2) self.assertEqual(result,[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.16666666666666666, 0.0), (0.16666666666666666, 0.0), (0.3333333333333333, 0.0), (0.16666666666666666, 0.0)]) def test_Marbles_Booleanos(self): result = Marbles_Booleanos([[(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)],[(0,0),(0,0),(0,0),(0,0),(0,0),(0,0)],[(0,0),(1,0),(0,0),(0,0),(0,0),(1,0)],[(0,0),(0,0),(0,0),(1,0),(0,0),(0,0)],[(0,0),(0,0),(1,0),(0,0),(0,0),(0,0)],[(1,0),(0,0),(0,0),(0,0),(1,0),(0,0)]],[(6,0),(2,0),(1,0),(5,0),(3,0),(10,0)],1) self.assertEqual(result,[(0, 0), (0, 0), (12, 0), (5, 0), (1, 0), (9, 0)]) def test_Marbles_Complejos(self): result = Marbles_Booleanos([[(6,3),(2,6),(5,5),(1,4),(2,4),(4,3)],[(6,3),(1,1),(2,2),(3,2),(4,1),(5,6)],[(6,3),(5,1),(5,2),(4,4),(2,4),(4,6)],[(6,3),(2,1),(5,2),(1,4),(2,4),(4,6)],[(6,3),(2,1),(5,2),(1,4),(2,4),(4,6)],[(6,3),(2,1),(5,2),(1,4),(2,4),(4,6)]],[(6,2),(2,3),(1,3),(5,2),(3,1),(0,1)],1) self.assertEqual(result,[(2, 108), (41, 71), (44, 110), (23, 95), (23, 95), (23, 95)]) if __name__== '__main__': unittest.main()
85f79b5d3db29f365bec57d3b4b6c8266f623c49
rachelduan/Question-and-answer-summary-and-reasoning
/seq2seq_pgn_tf2/utils/misc.py
521
3.6875
4
import copy def merge_dict(dict1, dict2): """Merges :obj:`dict2` into :obj:`dict1`. Args: dict1: The base dictionary. dict2: The dictionary to merge. Returns: The merged dictionary :obj:`dict1`. """ for key, value in dict2.items(): if isinstance(value, dict): dict1[key] = merge_dict(dict1.get(key, {}), value) else: dict1[key] = value return dict1 def clone_layer(layer): """Clones a layer.""" return copy.deepcopy(layer)
d4993cf844476c0596f5c512cd9c4aed6ce8ba35
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/cbrown/Lesson 4/trigrams.py
3,299
4.5625
5
#!/usr/bin/env python3 #Lesson 4-Trigrams Excercise import random import sys def read_in_data(filename): ''' Reads in file and returns either basic text back or cleaned Up text if it is a more complex file ''' line_by_line = [] with open(filename,'r') as f: #checks to see if its a basic txt doc or something more complex text = f.read() if 'Gutenberg' not in text: return text else: f.seek(0,0) for line in f: line = line.strip(',\n *' ) if 'START OF THIS PROJECT GUTENBERG' in line: line_by_line.append(line) elif 'End of the Project Gutenberg' in line: line_by_line.append(line) elif 'Gutenberg' in line: continue elif line.isspace() == True: continue elif line.startswith(('I','V','X')): continue elif line.isupper(): continue elif not line: continue line = line.replace('.','') line_by_line.append(line) for i, elem in enumerate(line_by_line): if 'START OF THIS PROJECT GUTENBERG' in elem: start = i elif 'End of the Project Gutenberg' in elem: end = i line_by_line = line_by_line[start + 1:end] line_by_line = " ".join(line_by_line) return line_by_line def clean_words(data): ''' Splits cleaned text into a list to be used in trigrams dictionary ''' cleaned_data = data.split() return cleaned_data def build_dict(words): ''' Creates the needed dictionary for trigrams text ''' tri_dict = {} for i in range(len(words)-2): pair = tuple(words[i:i + 2]) follower = words[i + 2] f_list = [] f_list.append(follower) if pair in tri_dict: value = tri_dict.get(pair).extend(f_list) else: tri_dict[pair] = f_list return tri_dict def build_trigram(tri_dict): ''' Builds up the trigrams text using the trigrams dictionary ''' #Creates first trigram of sequence num_of_keys = len(tri_dict.keys()) - 1 ran_num = random.randint(0,num_of_keys) first_key = list(tri_dict.keys())[ran_num] next_word = tri_dict.get(first_key)[0] trigram_list = [] trigram_list.append(first_key[0]) trigram_list.append(first_key[1]) trigram_list.append(next_word) #builds random trigram text for i in range(100): new_seq = tuple(trigram_list[-2:]) if len(trigram_list) >= 250: break elif new_seq in tri_dict: next_word = random.choice(tri_dict.get(new_seq)) trigram_list.append(next_word) else: break full_text = " ".join(trigram_list) print(full_text) if __name__ == '__main__': try: filename = sys.argv[1] except IndexError: print('Please Pass In An Available File') sys.exit(1) data = read_in_data(filename) words = clean_words(data) tri_dict = build_dict(words) build_trigram(tri_dict)
08ec56f750ddf9b51e2306efc939bf07732ccf0d
enasuzuki/Python-Practice
/CodingBad.py
2,256
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 27 23:03:00 2020 @author: ena """ #def-1 def hello(): # def + function name + (): print("Hello") #transaction hello() #call the function def ena(): print("Ena") ena() #def-2 def add(a, b): return (a + b) x = add(3, 4) print(x) def devide(c, d): return (c / d) y = devide(30, 6) print(y) def print_add(a, b, c): print("a = ", a) print("b = ", b) print("c = ", c) print("a + b + c = ", a + b + c) print_add(1, 4, 6) #in the order of a,b,c print_add(1, c=10, b=5) #you can decide the order def print_add_default(a, b, c=100): #you can set default print("a = ", a) print("b = ", b) print("c= ", c) print("a + b + c = ", a + b + c) print_add_default(5, 13) #def-3 *args def func_args(*args): #*をつけると何個でも呼び出し可能 print(args) func_args(1, 10) func_args(1, 2, 3, 4, 5) #def-3 *kwargs def func_kwargs(**kwargs): #**をつけると辞書として受け取る print(kwargs) func_kwargs(a=1, b=10) func_kwargs(c=90, d=100, e=70) #def-4 return def func_return(a, b): return (a + b) x = func_return(3, 4) print(x) print(type(x)) def func_return_multi(a, b): return [a + b, a * b, a / b] #[]で囲むとリスト y = func_return_multi(1, 2) print(y) print(type(y)) """ CodingBad """ #warmup-1 #near_hundred def near_hundred(n): if (n <= 110 and n >= 90) or (n <= 210 and n >= 190): return (True) else: return (False) #pos_neg def pos_neg(a, b, negative): if negative: return (a < 0 and b < 0) else: return ((a < 0 and b > 0) or (a > 0 and b < 0)) #front3 def front3(str): if len(str) >= 3: return (str[:3] * 3) else: return (str * 3) #missing_char !!! def missing_char(str, n): front = str[:n] back = str[n + 1:] return (front + back) #front_back def front_back(str): if len(str) >= 2: front = str[0] back = str[len(str) - 1] middle = str[1:-1] return (back + middle + front) #not_strnig !!! def not_string(str): if len(str) >= 3 and str[:3] == "not": return (str) else: return ("not " + str)
6959343a66d2fb851cd51dd0df1ec4e0367d17c3
duartecgustavo/PythonProgress
/desafios/Mundo 2/Ex056EXTRAlaços.py
989
3.9375
4
# Desafio 56 - EXTRA - Aula 13 : Programa que leia o NOME, IDADE e SEXO de 4 PESSOAS e apresente: # A/ MÉDIA DE IDADE do grupo. # B/ NOME do HOMEM mais VELHO. # C/ Quantas MULHERES tem MENOS DE 20 ANOS. plussage = 0 oldman = '' oldageman = 0 youngwoman = 0 for c in range(1, 5): print(f'------------ {c}° pessoa ------------') nome = str(input(f'\033[32mNome\033[m: ')).lower() sexo = str(input(f'\033[32mSexo\033[m: ')).lower() age = int(input(f'\033[32mIdade\033[m: ')) plussage += age if sexo in 'Mm' and c == 1: oldageman = age oldman = nome else: if sexo in 'Mm' and age > oldageman: oldageman = age oldman = nome if sexo in 'Ff' and age <=20: youngwoman += 1 print(f'A média de idade deste grupo é de {plussage/4} anos!') print(f'O nome do homem mais velho é {oldman.capitalize()} e tem {oldageman} anos.') print(f'O numero de mulheres com menos de 20 anos é igual à {youngwoman}.')
f14d0cd46b46685b8895b176659e9e8e16022475
jace-bae/Python_App
/Algorithm/02_max.py
197
3.71875
4
def find_max(a): n = len(a) max_n = a[0] for i in range(1, n): if a[i] > max_n: max_n = a[i] return max_n v = [10, 2, 18, 23, 59, 24, 33, 62] print(find_max(v))
0e4105700050a8ba7f9a75971dcb602f489abf33
stevelittlefish/svggraph
/svggraph/util.py
5,085
3.953125
4
""" Graphing Utility Function """ import logging import datetime __author__ = 'Stephen Brown (Little Fish Solutions LTD)' log = logging.getLogger(__name__) def fill_missing_days(data, empty_row=None, fill_to_today=False): """ Data must be a list of lists (or tuples) where the first cell in each row is a datetime which represents a month. The data must be ordered by the first column, This will return a new list of lists, with empty data added for each missing month :param data: The data set :param empty_row: Optional, list of values for all columns except the first to use for missing rows. :param fill_to_today: Optional, if set to True will add empty months to the end of the list up until this month """ if not data: return data def find_row(date): for row in data: if row[0].date() == date: return row return None if not empty_row: empty_row = [] for i in range(len(data[0]) - 1): empty_row.append(None) else: empty_row = [x for x in empty_row] start_date = data[0][0].date() end_date = data[-1][0].date() if fill_to_today: end_date = datetime.date.today() log.debug('Filling for date range %s - %s' % (start_date, end_date)) dates = [] current_date = start_date while current_date <= end_date: dates.append(current_date) current_date += datetime.timedelta(days=1) out = [] for date in dates: existing_row = find_row(date) if existing_row: out.append(existing_row) else: out.append([datetime.datetime(date.year, date.month, date.day)] + empty_row) return out def fill_missing_weeks(data, empty_row=None, fill_to_today=False): """ Data must be a list of lists (or tuples) where the first cell in each row is a datetime which represents a month. The data must be ordered by the first column, This will return a new list of lists, with empty data added for each missing month :param data: The data set :param empty_row: Optional, list of values for all columns except the first to use for missing rows. :param fill_to_today: Optional, if set to True will add empty months to the end of the list up until this month """ if not data: return data def find_row(date): for row in data: if row[0].date() == date: return row return None if not empty_row: empty_row = [] for i in range(len(data[0]) - 1): empty_row.append(None) else: empty_row = [x for x in empty_row] start_date = data[0][0].date() end_date = data[-1][0].date() if fill_to_today: end_date = datetime.date.today() log.debug('Filling for date range %s - %s' % (start_date, end_date)) dates = [] current_date = start_date while current_date <= end_date: dates.append(current_date) current_date += datetime.timedelta(days=7) out = [] for date in dates: existing_row = find_row(date) if existing_row: out.append(existing_row) else: out.append([datetime.datetime(date.year, date.month, date.day)] + empty_row) return out def fill_missing_months(data, empty_row=None, fill_to_today=False): """ Data must be a list of lists (or tuples) where the first cell in each row is a datetime which represents a month. The data must be ordered by the first column, This will return a new list of lists, with empty data added for each missing month :param data: The data set :param empty_row: Optional, list of values for all columns except the first to use for missing rows. :param fill_to_today: Optional, if set to True will add empty months to the end of the list up until this month """ if not data: return data def find_row(date): for row in data: if row[0].date() == date: return row return None if not empty_row: empty_row = [] for i in range(len(data[0]) - 1): empty_row.append(None) else: empty_row = [x for x in empty_row] start_date = data[0][0].date() end_date = data[-1][0].date() if fill_to_today: today = datetime.date.today() end_date = datetime.date(today.year, today.month, 1) log.debug('Filling for date range %s - %s' % (start_date, end_date)) dates = [] current_date = start_date while current_date <= end_date: dates.append(current_date) if current_date.month == 12: current_date = datetime.date(current_date.year + 1, 1, 1) else: current_date = datetime.date(current_date.year, current_date.month + 1, 1) out = [] for date in dates: existing_row = find_row(date) if existing_row: out.append(existing_row) else: out.append([datetime.datetime(date.year, date.month, date.day)] + empty_row) return out
c5df13c562b7d2b01db99297488f80bac9c4f7fa
jmomarty/NeuralLandPirates
/CorpusViz/interactive.py
4,586
3.921875
4
# License: Creative Commons Zero (almost public domain) http://scpyce.org/cc0 """ Example usage of matplotlibs widgets: Build a small 2d Data viewer. Shows 2d-data as a pcolormesh, a click on the image shows the crossection (x or y, depending on the mouse button) and draws a corresponding line in the image, showing the location of the crossections. A reset button deletes all crossections plots. Works with matplotlib 1.0.1. """ from matplotlib.widgets import Cursor, Button import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.size'] = 8 class viewer_2d(object): def __init__(self, z, x=None, y=None): """ Shows a given array in a 2d-viewer. Input: z, an 2d array. x,y coordinters are optional. """ if x is None: self.x = np.arange(z.shape[0]) else: self.x = x if y is None: self.y = np.arange(z.shape[1]) else: self.y = y self.z = z self.fig = plt.figure() # Doing some layout with subplots: self.fig.subplots_adjust(0.05, 0.05, 0.98, 0.98, 0.1) self.overview = plt.subplot2grid((8, 4), (0, 0), rowspan=7, colspan=2) self.overview.pcolormesh(self.x, self.y, self.z) self.overview.autoscale(1, 'both', 1) self.x_subplot = plt.subplot2grid((8, 4), (0, 2), rowspan=4, colspan=2) self.y_subplot = plt.subplot2grid((8, 4), (4, 2), rowspan=4, colspan=2) # Adding widgets, to not be gc'ed, they are put in a list: cursor = Cursor(self.overview, useblit=True, color='black', linewidth=2) but_ax = plt.subplot2grid((8, 4), (7, 0), colspan=1) reset_button = Button(but_ax, 'Reset') but_ax2 = plt.subplot2grid((8, 4), (7, 1), colspan=1) legend_button = Button(but_ax2, 'Legend') self._widgets = [cursor, reset_button, legend_button] # connect events reset_button.on_clicked(self.clear_xy_subplots) legend_button.on_clicked(self.show_legend) self.fig.canvas.mpl_connect('button_press_event', self.click) def show_legend(self, event): """Shows legend for the plots""" for pl in [self.x_subplot, self.y_subplot]: if len(pl.lines) > 0: pl.legend() plt.draw() def clear_xy_subplots(self, event): """Clears the subplots.""" for j in [self.overview, self.x_subplot, self.y_subplot]: j.lines = [] j.legend_ = None plt.draw() def click(self, event): """ What to do, if a click on the figure happens: 1. Check which axis 2. Get data coord's. 3. Plot resulting data. 4. Update Figure """ if event.inaxes == self.overview: # Get nearest data xpos = np.argmin(np.abs(event.xdata-self.x)) ypos = np.argmin(np.abs(event.ydata-self.y)) # Check which mouse button: if event.button == 1: # Plot it c, = self.y_subplot.plot(self.y, self.z[:, xpos], label=str(self.x[xpos])) self.overview.axvline(self.x[xpos], color=c.get_color(), lw=2) elif event.button == 3: # Plot it c, = self.x_subplot.plot(self.x, self.z[ypos, :], label=str(self.y[ypos])) self.overview.axhline(self.y[ypos], color=c.get_color(), lw=2) if event.inaxes == self.y_subplot: ypos = np.argmin(np.abs(event.xdata-self.y)) c = self.x_subplot.plot(self.x, self.z[ypos, :], label=str(self.y[ypos])) self.overview.axhline(self.y[ypos], color=c.get_color(), lw=2) if event.inaxes == self.x_subplot: xpos = np.argmin(np.abs(event.xdata-self.x)) c, = self.y_subplot.plot(self.y, self.z[:, xpos], label=str(self.x[xpos])) self.overview.axvline(self.x[xpos], color=c.get_color(), lw=2) # Show it plt.draw() if __name__ == '__main__': # Build some strange looking data: x = np.linspace(-3, 3, 300) y = np.linspace(-4, 4, 400) X, Y = np.meshgrid(x, y) z = np.sqrt(X**2 + Y**2) + np.sin(X**2 + Y**2) w, h = 512, 512 # from matplotlib import cbook # datafile = cbook.get_sample_data('ct.raw', asfileobj=False) # print 'loading', datafile # s = file(datafile, 'rb').read() # A = np.fromstring(s, np.uint16).astype(float) # A *= 1.0/max(A) # Put it in the viewer fig_v = viewer_2d(z, x, y) # Show it plt.show()
a63b35712dd029cbb6debab249b9628dc2167fd0
pedroalpacheco/caixaeletronico
/troco.py
629
3.5
4
# -*- coding: utf-8 -*- """ Created on Wed May 27 11:49:30 2015 @author: papacheco """ #contador de troco preco = int(raw_input("Digite o valor da compra:")) dinheiro = int(raw_input("Digite a quantia de dinheiro entregue: ")) print troco = dinheiro - preco if troco > 0: print "Valor do troco: R$ %s." % troco print #for p in 100, 50, 20, 10, 5, 2, 1: for p in 100,50,20,10,5,2,1: if troco >= p: n = troco / p r = troco - p * n print ": %s nota(s) de R$ %s." % (n, p) troco = r else: print "O dinheiro entregue é menor do que o valor da compra."
7e0c59da4979992e041eb0dfcba2e18ce8e249d6
JurgenBlokhuis/Python
/Les 5/PE 5_2.py
215
3.859375
4
leeftijd = int(input("Hou oud ben je? : ")) Nederlandspaspoort= input("Heeft u een nederlands paspoort? : ") if leeftijd >= 18 and Nederlandspaspoort == 'ja': tekst = 'gefeliciteerd u mag stemmen' print(tekst)
b73db7c40f42768d1b2b26fcd755429ae72e900b
farzanehsalari/pyclass
/s4.py
217
3.703125
4
add1 = int(input ()) add2 = int(input()) amal = input("vared konid amalgar\n") if amal == "+": print (add1 + add2) elif amal == "-": print (add1 - add2) elif amal == "*": print (add1 * add2) else : print ("nashenas hast")
ace58c271eb7acfd08627e60c695a4ec29654d41
ShawnHan1993/EC602
/hw5/poly56.py
2,042
3.578125
4
\ \ \ \ class Polynomial(): def __init__(self,value=0): self={0:value} def __getitem__(self,key): try: return self[key] except KeyError: self.missing(self,key) def __missing__(self,key): return 0 def __setitem__(self,keys,value): self[keys]=value def __add__(self,value): result={0:0} a=list(dict(self).keys()) b=list(dict(value).keys()) i=0 j=0 while(i<len(a)): result[a[i]]=self.get(a[i],0)+value.get(a[i],0) i+=1 while(j<len(b)): result[b[j]]=self.get(b[j],0)+value.get(b[j],0) j+=1 return result def __sub__(self,value): result={0:0} a=list(dict(self).keys()) b=list(dict(value).keys()) i=0 j=0 while(i<len(a)): result[a[i]]=self.get(a[i],0)-value.get(a[i],0) i+=1 while(j<len(b)): result[b[j]]=self.get(b[j],0)-value.get(b[j],0) j+=1 return result def __mul__(self,value): result={0:0} a=list(dict(self).keys()) b=list(dict(value).keys()) i=0 while(i<len(a)): j=0 while(j<len(b)): result[a[i]+b[j]]=result.get(a[i]+b[j],0)+self[a[i]]*value[b[j]] j+=1 i+=1 return result def __eq__(self,value): i=cmp(dict(self),dict(value)) if(i==0): return True else: return False def eval(self,value): result = 0 a=list(dict(self).keys()) i=0 while(i<len(a)): result+=self[a[i]]*value**a[i] i+=1 return result def derive(self): result={0:0} a=list(dict(self).keys()) i=0 while(i<len(a)): result[a[i]-1]=self[a[i]]*a[i] i+=1 return result
555d73c28279a34b3e6b4fe0722ec23cda59aa37
raghumina/Python_basics
/Indexes.py
1,660
4.28125
4
# INDEXES # the list contains several numbers. Print the third number from this list. #You don't have to handle the input. #Sample Input 1: #[5230, 5661, 5081, 9539, 5563] #Sample Output 1: # 5081 # One way numbers = [5230, 5661, 5081, 9539, 5563] third_element = numbers[-3] print(third_element) # another way numbers = ['5230', '5661', '5081', '9539', '5563'] #third_element = numbers[-3] print(numbers[-3]) # one more way numbers = [5230, 5661, 5081, 9539, 5563] #third_element = numbers[-3] print(numbers[2]) # 2nd Problem # We have created a variable for the lowercase English alphabet: # alphabet = 'abcdefghijklmnopqrstuvwxyz' # Your task is to print the 15th letter of this string. alphabet = 'abcdefghijklmnopqrstuvwxyz' print(alphabet[-12]) # Problem 3 #Find the initial letter of a person's name and print it out. #Make use of the variable name that stores a string. #Sample Input 1: #Kate #Sample Output 1: #K #Sample Input 2: #Ivor #Sample Output 2: #I name = "Kate" print(name[-len(name)]) name = "Ivor" k = name[0] print(k) # Problem 4 #Sentences generally end with a certain punctuation mark: a period ., an exclamation point !, or a question mark ?. #Find out which of these symbols marks the end of a string stored in the variable sentence and print it out. #Sample Input 1: #What a lovely day! #Sample Output 1: #! sentence = "What a lovely day!" print(sentence[-1]) # Problem 5 # Modify the list numbers so that each number in it coincides with its index (not the negative one). In the end, print the list. numbers = [4, 1, 0, 3, 2, 5] # This is also the given list index = numbers.index(4, 1, 0, 3, 2, 5) print(index)
fa84ad9ebc8a94adeac3dbdd0ba77bb4bb6f1292
0xlimE/ITU-sec1-Elgamal
/mh1.py
2,425
4.125
4
#Python script to solve 1-3 in mandatory handin 1 - El Gamal # Author: Emil Hørning. 0xlimE #Helper function for finding the multiplicative inverse of a (mod m), this means that a * x mod m = 1 (where we want to find x) #This helper function basically just bruteforces from 1-m, I dont think this is the best way def modInverse(a, m) : a = a % m; for x in range(1, m) : if ((a * x) % m == 1) : return x return 1 g = 666 p = 6661 PK_bob = 2227 #Bobs public key g^x mod p ############Part 1: Send the message '2000' to bob. print("Assignment part 1") message = 2000 y = 201 # Random y PK_alice = pow(g,y,p) gxy = pow(PK_bob,y,p) c = (gxy * message) % p print("sending g^y:",PK_alice, "and c:",c,"from alice to bob") #bob recovers message by calculating c/g^yx (we actually want c * (g^yx)^-1 (the multiplicative inverse)) gxy_1 = modInverse(gxy,p) message_reconstructed = (c * gxy_1) %p print("Bob recovers the secret",message_reconstructed) print("") print("-------------") print("") ############Part 2: You are now Eve and intercept Alice’s encrypted message. Find Bob’s private key and reconstruct Alice’s message #Eve observes both g and p and bobs public key. Eves first step is to try and bruteforce the private key (bobs x), bruteforce from 1-p print("Assignment part 2") print("Hehe I am the evil eve and will try and bruteforce bobs private key") for i in range(1,6662): if(pow(g,i,p) == PK_bob): x = i print("Haha! I found bobs private key, it is x =",i) break #Eve can calculate g^xy since g^y is given from alice eve_gxy = pow(PK_alice,x,p) #again get multiplicative inverse eve_gxy_1 = modInverse(eve_gxy,p) message_intercepted = (c*eve_gxy_1)%p print("I find alice' message =",message_intercepted) print("") print("-------------") print("") ############Part 3 You are now mallory and intercept alice encrypted message, you cannot find bobs private key, modify alice message so it says 6000 instead of 2000. print("Assignment part 3") print("I am mallory!, I see the ciphertext and will multiply it to make the number seem bigger!") c = c*3 #We intercept just the ciphertext and multiply this by 3 to get 6000. gxy_1 = modInverse(gxy,p) message_reconstructed = (c * gxy_1) %p print("Bob recovers the secret",message_reconstructed) print("") print("-------------")
2a5ce4c6a784755384387bd7c10e9fd97a3fff65
priyankachapala/Elgamal-Elliptic-Curve-Cryptography
/text.py
4,129
3.578125
4
import collections import numpy as np import string def inv(n, q): """div on PN modulo a/b mod q as a * inv(b, q) mod q >>> assert n * inv(n, q) % q == 1 """ for i in range(q): if (n * i) % q == 1: return i pass assert False, "unreached" pass def sqrt(n, q): """sqrt on PN modulo: returns two numbers or exception if not exist >>> assert (sqrt(n, q)[0] ** 2) % q == n >>> assert (sqrt(n, q)[1] ** 2) % q == n """ assert n < q for i in range(1, q): if i * i % q == n: return (i, q - i) pass raise Exception("not found") Coord = collections.namedtuple("Coord", ["x", "y"]) 1 class EC(object): """System of Elliptic Curve""" def __init__(self, a, b, q): """elliptic curve as: (y**2 = x**3 + a * x + b) mod q - a, b: params of curve formula - q: prime number """ assert 0 < a and a < q and 0 < b and b < q and q > 2 assert (4 * (a ** 3) + 27 * (b ** 2)) % q != 0 self.a = a self.b = b self.q = q # just as unique ZERO value representation for "add": (not on curve) self.zero = Coord(0, 0) pass def is_valid(self, p): if p == self.zero: return True l = (p.y ** 2) % self.q r = ((p.x ** 3) + self.a * p.x + self.b) % self.q return l == r def at(self, x): """find points on curve at x - x: int < q - returns: ((x, y), (x,-y)) or not found exception >>> a, ma = ec.at(x) >>> assert a.x == ma.x and a.x == x >>> assert a.x == ma.x and a.x == x >>> assert ec.neg(a) == ma >>> assert ec.is_valid(a) and ec.is_valid(ma) """ assert x < self.q ysq = (x ** 3 + self.a * x + self.b) % self.q y, my = sqrt(ysq, self.q) return Coord(x, y), Coord(x, my) def neg(self, p): """negate p >>> assert ec.is_valid(ec.neg(p)) """ return Coord(p.x, -p.y % self.q) 2 def add(self, p1, p2): """<add> of elliptic curve: negate of 3rd cross point of (p1,p2) line >>> d = ec.add(a, b) >>> assert ec.is_valid(d) >>> assert ec.add(d, ec.neg(b)) == a >>> assert ec.add(a, ec.neg(a)) == ec.zero >>> assert ec.add(a, b) == ec.add(b, a) >>> assert ec.add(a, ec.add(b, c)) == ec.add(ec.add(a, b), c) """ if p1 == self.zero: return p2 if p2 == self.zero: return p1 if p1.x == p2.x and (p1.y != p2.y or p1.y == 0): # p1 + -p1 == 0 return self.zero if p1.x == p2.x: # p1 + p1: use tangent line of p1 as (p1,p1) line l = (3 * p1.x * p1.x + self.a) * inv(2 * p1.y, self.q) % self.q pass else: l = (p2.y - p1.y) * inv(p2.x - p1.x, self.q) % self.q pass x = (l * l - p1.x - p2.x) % self.q y = (l * (p1.x - x) - p1.y) % self.q return Coord(x, y) def mul(self, p, n): """n times <mul> of elliptic curve >>> m = ec.mul(p, n) >>> assert ec.is_valid(m) >>> assert ec.mul(p, 0) == ec.zero """ r = self.zero m2 = p # O(log2(n)) add while 0 < n: if n & 1 == 1: r = self.add(r, m2) pass n, m2 = n >> 1, self.add(m2, m2) pass # [ref] O(n) add # for i in range(n): # r = self.add(r, p) # pass 3 return r def order(self, g): """order of point g >>> o = ec.order(g) >>> assert ec.is_valid(a) and ec.mul(a, o) == ec.zero >>> assert o <= ec.q """ assert self.is_valid(g) and g != self.zero for i in range(1, self.q + 1): if self.mul(g, i) == self.zero: return i pass raise Exception("Invalid order") pass if __name__ == "__main__": # shared elliptic curve system of examples a = int(input("enter curve parameter 'a': ")) b = int(input("enter curve parameter 'b': ")) q = int(input("enter prime number 'q' (prime number): ")) ec = EC(a, b, q) na = int(input("enter private key of A:")) nb = int(input("enter private key of B:")) k = int(input("enter a random number: ")) # produce generator point g,m = ec.at(0) #assert ec.order(g) <= ec.q print(g) # Public Keys Genration pa=ec.mul(g,na) pb=ec.mul(g,nb)) kg=ec.mul(g,k) print(kg) pass # Creating Dictionary for each alphabet in the text message Dict={} k=0 msg = (input("enter message: ")) for s in msg: 4 Dict[s]=ec.mul(g,ord(s)) k=k+1 print(Dict) print("\n") m=np.zeros(k) l=0 print("encrypted msg is:") for s in msg: m[l]=(ec.add(Dict[s],ec.mul(pb,k).x) #print(m[l]) l=l+1 str=[] for i in range(0,k): str.append(chr(int(m[i]))) print(str) p=[] for k in m: dec,enc=ec.at(k) m=ec.add(dec,ec.neg(ec.mul(kg,nb))) n=ec.add(enc,ec.neg(ec.mul(kg,nb))) print(m) for key in Dict.keys(): if Dict[key]==m or Dict[key]==n: print(key) p.append(key) 5
9a01973cad18d977b217d559133ba53112c15e37
jlmeunier/pystruct
/pystruct/utils/plotting.py
1,112
3.953125
4
import numpy as np def plot_grid(x, cmap=None, border_color=None, axes=None, linewidth=1): """Plot a grid labeling including grid boundaries. Parameters ========== x : array-like, 2d Input array to plot. cmap : matplotlib colormap Colormap to be used for array. border_color : matplotlib color Color to be used to plot borders between grid-cells. axes : matplotlib axes object We will plot into this. linewidth : int Linewidth for the grid-cell borders. Returns ======= axes : matplotlib axes object The axes object that contains the plot. """ import matplotlib.pyplot as plt if axes is not None: axes.matshow(x, cmap=cmap) else: axes = plt.matshow(x, cmap=cmap).get_axes() axes.set_xticks(np.arange(1, x.shape[1]) - .5) axes.set_yticks(np.arange(1, x.shape[0]) - .5) if border_color is None: border_color = 'black' axes.grid(linestyle="-", linewidth=linewidth, color=border_color) axes.set_xticklabels(()) axes.set_yticklabels(()) return axes
37c741e5fecc44e66f178308be1a08d2ec0bb1a1
BaldomeroPerez/Exercicio-para-Python
/063 Sequencia de Fibonacci versão 1.py
516
4.09375
4
# Exercício Python 063: Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. print('-'*25) print('Sequencia de Fibonacci') print('-'*25) n = int(input('Quantos termos voce quer mostrar? ')) t1 = 0 t2 = 1 print('~'*25) print('{} -> {}'.format( t1, t2), end='') cont = 3 while cont <= n: t3 = t1 + t2 print(' -> {} '.format(t3), end='') t1 = t2 # dessa maneira o t1 vai mudando do 0 t2 = t3 cont +=1 print(' -> FIM')
92aa58270755428768e2013506adfdf230eda961
HaneulParkSky/sun_python
/Day 13~16/ch06ex02_뺄셈문제.py
347
3.8125
4
# ch06ex02.py # 계산문제 2 (뺄셈 문제 만드는 함수 makeQuiz() 만들기) import random def make_quiz(): num1 = random.randint(10, 20) num2 = random.randint(1, 10) quiz = f'{num1} - {num2}' return quiz for x in range(5): quiz = make_quiz() ans = eval(quiz) print(f'{quiz} = {ans}')
280f20f3b157d8aea3ee1367de7dded1cc72c26a
mateuscv/competitive-programming-exercises
/URI/URI1176.py
408
3.53125
4
#encoding = UTF-8 test_cases = int(input()) cont = 0 while cont < test_cases: n = int(input()) if n == 0: print("Fib(" + str(n) + ") = 0") else: Fib = [] Fib.append(0) Fib.append(1) forRange = range(n+1) for i in forRange[2:]: Fib.append(Fib[i-1] + Fib[i-2]) print("Fib(" + str(n) + ") = " + str(Fib[-1])) cont += 1
a867bbe6c9278c72549f14d27a50b5880e94533b
leon-zhu/python-oop-learn
/chapter06/temp/tuple_exercise.py
984
3.65625
4
import datetime from collections import namedtuple, defaultdict def middle(stock, date): symbol, current, high, low = stock return ((high + low) / 2), date mid_value, date = middle(('FB', 75.0, 75.03, 74), datetime.date(2014, 10, 5)) print(mid_value, date) Stock = namedtuple('Stock', 'Symbol current high low') stock = Stock('FB', 75.0, high=75.03, low=74) def letter_frequency(sentence): frequencies = {} for letter in sentence: frequency = frequencies.setdefault(letter, 0) frequencies[letter] = frequency + 1 return frequencies def letter_frequency_2(sentence): frequencies = defaultdict(int) for letter in sentence: frequencies[letter] += 1 return frequencies num_items = 0 def tuple_counter(): global num_items num_items += 1 return num_items, [] if __name__ == '__main__': # Stock(Symbol='FB', current=75.0, high=75.03, low=74) print(stock) print(letter_frequency('abcdefafafaf'))
1135d040901a82f37ec15435ba6782c866c6d0b4
VaasviAgarwal/BasicPythonforBeginners
/ProgramsToPracticeConditionalStatements-Part1.py
2,146
4.28125
4
#menu driven program #writing a program to understand the use of conditional statements print("Enter the part number you want to be executed") print("Part 1) finding the greater number out of the two") print("Part 2) seeing if the number is +ve, -ve or zero") print("Part 3) check whether the number enterd by the user is divisible by 5 and 11") print("Part 4) check whether the number entered by the user is a leap year or not") print("Part 5) finding out if a number is even or odd") choice = int(input("Enter your choice : ")) if(choice == 1): #accepting numbers a and b and assuming that the user will enter an integer value a=int(input('Enter the first number : ')) b=int(input('Enter the second number : ')) if (a>b) : print(a,"is greater than",b) elif (a<b) : print(b,"is greater than",a) else : print("Both numbers are equal") elif(choice == 2): #assuming that the user enters an int value n=int(input("Enter an integer number : ")) if (n>0) : print(n,"is a positive number") elif (n<0) : print(n,"is a negative number") else : print(n,"is zero") elif(choice == 3) : #assuming that the user enters a positive integer m m=int(input("Enter a postive number : ")) if (m%5==0) or (m%11==0) : if(m%5==0) and (m%11==0): print(m,"is divisible by both 5 and 11") elif(m%5==0): print(m,"is only divisible by 5 and not 11") else: print(m,"is only divisible by 11 and not 5") else : print(m,"is neither divisible by 11 not 5") elif(choice == 4) : #assuming user enters a positive whole number as the year year=int(input("Enter the year you want to check for : ")) if(year%4==0 and year%100!=0) or (year%400==0): print(year,"was a leap year") else: print(year,"was not a leap year") elif(choice == 5) : #assuming the user enters an integer value n=int(input("Enter a number : ")) if(n%2==0): print(n,"is an even number") else: print(n,"is an odd number") else : print("your choice is invalid")
2f234be1a529437d4c7a4e72763c20d5d05c4249
Sayna83/poulstar
/term2/example_if02.py
353
3.734375
4
number01 = int(input("please enter number1")) number02 = int(input("please enter number2")) number03 = int(input("please enter number3")) number04 = int(input("please enter number4")) number05 = int(input("please enter number5")) nn = number01 + number02 + number03 + number04 + number05 nd = nn / 5 if nd >= 10: print("ok") else: print("error")
5d6184c05b15a6c06b915127444d5c20615a6991
laszlokiraly/LearningAlgorithms
/ch05/merge.py
2,339
4
4
""" Merge sort uses auxiliary storage """ def merge_sort(A): """Merge Sort implementation using auxiliary storage.""" aux = [None] * len(A) def rsort(lo, hi): if hi <= lo: return mid = (lo+hi) // 2 rsort(lo, mid) rsort(mid+1, hi) merge(lo, mid, hi) def merge(lo, mid, hi): # copy results of sorted sub-problems into auxiliary storage aux[lo:hi+1] = A[lo:hi+1] left = lo # starting index into left sorted sub-array right = mid+1 # starting index into right sorted sub-array for i in range(lo, hi+1): if left > mid: A[i] = aux[right] right += 1 elif right > hi: A[i] = aux[left] left += 1 elif aux[right] < aux[left]: A[i] = aux[right] right += 1 else: A[i] = aux[left] left += 1 rsort(0, len(A)-1) def merge_sort_counting(A): """Perform Merge Sort and return #comparisons.""" aux = [None] * len(A) def rsort(lo, hi): if hi <= lo: return (0,0) mid = (lo+hi) // 2 (lefts, leftc) = rsort(lo, mid) (rights, rightc) = rsort(mid+1, hi) (nswap, ncomp) = merge(lo, mid, hi) return (lefts+rights+nswap, leftc+rightc+ncomp) def merge(lo, mid, hi): # copy results of sorted sub-problems into auxiliary storage aux[lo:hi+1] = A[lo:hi+1] i = lo # starting index into left sorted sub-array j = mid+1 # starting index into right sorted sub-array numc = 0 nums = 0 for k in range(lo, hi+1): if i > mid: if A[k] != aux[j]: nums += 0.5 A[k] = aux[j] j += 1 elif j > hi: if A[k] != aux[i]: nums += 0.5 A[k] = aux[i] i += 1 elif aux[j] < aux[i]: numc += 1 if A[k] != aux[j]: nums += 0.5 A[k] = aux[j] j += 1 else: numc += 1 if A[k] != aux[i]: nums += 0.5 A[k] = aux[i] i += 1 return (nums, numc) return rsort( 0, len(A)-1)
a7c9226a727e169f6d94134853ae6585e6b37a33
navkant/ds_algo_practice
/datastructures/hash_map/substring.py
661
3.6875
4
class Solution: def get_substring(self, string, start, output, ans, required_length): if len(output) == required_length and output not in ans: # if output not in ans: ans.append(output) if start == len(string): return self.get_substring(string, start+1, output, ans, required_length) output = output + string[start] self.get_substring(string, start+1, output, ans, required_length) return ans if __name__ == "__main__": a = "abcbacabc" obj = Solution() start = 0 output = '' ans = list() x = obj.get_substring(a, 0, output, ans, 3) print(x)
500f95d7a6c68584c19c9539ba6495dd82c23284
Saurabh-12/Python_Learning
/StringManipulation.py
290
4.0625
4
my_string = "Hi Saurabh !" print(my_string) print(my_string*2) print(my_string+"2") print(my_string+"I love python "*2) # reverse the string print(my_string[::-1]) my_list = [1,3,5,7] print(my_list[::-1]) # Word list my_word = ["word", "python", "is", "this"] print(" ".join(my_word[::-1]))
687069cb5b4a38cff82c65576865362f83993369
xyzhangaa/ltsolution
/Triangle.py
513
3.703125
4
###Given a triangle, find the minimum path sum from top to bottom. ###Each step you may move to adjacent numbers on the row below. #O(n*m),O(n) def Triangle(array): if len(array) == 0: return 0 arr = [0 for _ in range(len(array))] arr[0] = array[0][0] for i in range(1,len(array)): for j in range(len(array[i])-1,-1,-1): if j == len(array[i])-1: arr[j] = arr[j-1]+array[i][j] elif j == 0: arr[j] = arr[j]+array[i][j] else: arr[j] = min(arr[j-1],arr[j])+array[i][j] return min(arr)
53c0860eaff2bde75b824df15ae658b0e73ca412
AndreeaParlica/Codewars-Python-Fundamentals-Kata-Solutions
/minim counts.py
562
3.640625
4
# if you start with $1 and, with each move, you can either double your money or add another $1, what is the smallest # number of moves you have to make to get to exactly $200? # Write a program to calculate this and submit the solution with your application. moves = [] def moves_count(n): while n > 1: if n % 2 == 0: n = n // 2 elif n == 3 or n % 4 == 1: n = n - 1 else: n = n + 1 moves.append(n) return "Numbers of moves: {}".format(len(moves)) print(moves_count(200)) print(moves)
7c35114dd755fbdd792a5786f35b4b44fb11023b
tanx-thp/learnselenium-1
/test/07by_css_selector.py
1,417
3.640625
4
# find_element_by_css_selector定位控件中的第7种方式 # 绝对路径:从根节点开始,一层一层往下找到想定位的标签 # css_selector的绝对路径:一般以左斜杠/开头大于号>分隔 html>body>div>div>div>div>form>input # 相对路径: # 1、标签中有id属性时可以写成:标签类型#id属性值,(标签类型可省略)如:i#cart_num # 2、标签中有class属性时可以写成:标签类型.class属性值,如:input.but1 # 3、标签中没有id、class属性时可以写成:标签类型[属性值=""],如:input[placeholder="请输入你要查找的关键字"] # 4、连接多个属性值:input[class="but1"][placeholder="请输入你要查找的关键字"][] # 5、父级找子级:div.schbox>form>input:nth-child(1) :nth-child(?)确定是第几个子级,类似xpath中的[1] # 6、定位第一个子级: :first-child # 7、定位最后一个子级: :last-child # 8、定位倒数第几个子级: :nth-last-child(?) # 9、对于css_selector来说,第几个子级不是指同标签的顺序而是指父级下所有标签排序的顺序;xpath是相同标签的才进行排序 from selenium import webdriver import time time.sleep(2) driver = webdriver.Chrome() driver.get("http://101.133.169.100/yuns/index.php") time.sleep(2) driver.find_element_by_css_selector("html>body>div>div>div>div>form>input").send_keys("测试xpath")
7c82d728193b83ee9bae1fe5461e04753e82c3ae
Kalaikko/Python
/Sample.py
577
4.1875
4
inputList = [1,2,3,4,5,6] sizeOfList = len(inputList) flag = True while(flag): sizeOf1stList = int(input("Enter size of 1st list: ")) sizeOf2ndList = int(input("Enter size of 2nd list: ")) if(sizeOfList >= sizeOf1stList): print('Size of 1st List ',inputList[0:sizeOf1stList]) print('Size of 2nd List ',inputList[sizeOf1stList:sizeOf1stList+sizeOf2ndList]) print('Size of 3rd List ',inputList[sizeOf1stList+sizeOf2ndList:len(inputList)]) break else: print('ERROR: Enter size less than ',sizeOfList)
d9185e3bec7ed67b329c4301ed1575ff1118207a
JDKdevStudio/Taller30Abril
/48.PrintCustonNumberInRangeSum.py
230
3.96875
4
n = int(input("Escriba un número natural")) m = n - 1 sum = 0 while True: m = int(input("Escriba un número natural mayor al anterior")) if m > n: break for x in range(n, m + 1): sum += x print(sum)
1e87086722a7ed8b37fbe08fce4de8bb48ee5857
vandsonlima/Python_30DaysOfCode
/ch_10.py
383
3.828125
4
# receber um numero int #converter para binario #contar o número de 1's print(len(max(bin(int(input())).replace("0b", "").split('0')))) #bin() -> converte o número em binário #split() -> quebra a string e transforma e retorna uma lista de substrings #max(list) -> retorna o maior elemento de uma lista # len() -> retorna o tamanho do elemento (no caso o tamanho da string)
b23bc467a58de58fad4c62592a4c6c00bda1fa3b
oc0de/pyEPI
/16/10.py
443
3.59375
4
def number_of_ways_to_top(top, maximum_step): def helper(h): if h <= 1: return 1 if h not in number_of_ways: number_of_ways[h] = sum( helper(h-i) for i in range(1, min(h, maximum_step) + 1)) return number_of_ways[h] number_of_ways = {} return helper(top) assert 5 == number_of_ways_to_top(4, 2) assert 1 == number_of_ways_to_top(1, 2) assert 1 == number_of_ways_to_top(0, 3)
ca912d83cac4d22b9e62d31fe7d366408cfdb481
Isaiah-Simon/2017Challenges
/challenge_7/python/isaiah/find_missing_number.py
303
4.0625
4
def find_missing_number(list): n = len(list) # Find correct total using summation of first n natural numbers correct_total = (n*(n+1))//2 actual_total = 0 # Count the total in the list for i in list: actual_total += i return correct_total - actual_total
8163c200a06682ecd671df9b6786920472aa94bc
dreddsa5dies/automatePy
/ch1_theory/04_list_1.py
392
3.78125
4
def printList(val): for k in range(len(val)): if k != len(val)-1 and k != len(val)-2: print(val[k], end=', ') elif k == len(val)-2: print(val[k], end=' and ') else: print(val[k]) spam = ['app', 'ban', 'tof', 'cat'] printList(spam) vl = str(input('Введите строку: ')) lis = vl.split(" ") printList(lis)
eb73d7c6b12b721cf4aa03eef49bd123267baacf
stefan1123/newcoder
/二叉树的下一个结点.py
2,097
4
4
""" 题目描述 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中 的结点不仅包含左右子结点,同时包含指向父结点的指针。 代码情况:accepted """ class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: def GetNext(self, pNode): # write code here if pNode == None: return None # 若右子树存在,找右孩子为根结点的子树的最左边的节点 if pNode.right: root_rightTree = pNode.right if root_rightTree.left: node = root_rightTree.left while node.left: node = node.left return node else: return root_rightTree # 右子树不存在 else: # 若该节点是其父亲节点的左节点,则下一节点就是其父节点 if pNode.next and pNode == pNode.next.left: return pNode.next # 若该节点不是其父亲节点的左节点,则,网上遍历父节点,找到某一个节点M,使这个 # 节点M的父节点N的左节点正好是该节点,测试父节点N就是下一节点 else: while pNode.next and pNode != pNode.next.left: pNode = pNode.next return pNode.next # 简洁一点的 # # 若该节点是其父亲节点的左节点,则下一节点就是其父节点 # # 若该节点不是其父亲节点的左节点,则,向上遍历父节点,找到某一个节点M,使这个 # # 节点M的父节点N的左节点正好是该节点,此时父节点N就是下一节点 # while pNode.next: # tmp=pNode.next # if tmp.left==pNode: # return tmp # pNode=tmp
627fa9dbddc84c053207e415df6469d97b09ec9f
edaniels20/python-pacman-project
/pathing.py
1,853
3.671875
4
class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y class Pathfinding(object): walkablePositions = [] nodeParents = {} def __init__(self, nodes): self.walkableNodes = nodes def getShortestPath(self, start, goal): path = self.determineShortestPath(start, goal) if path == start or self.nodeParents[goal] not in self.nodeParents: return None path = [] curr = goal while curr != start: path.append(curr) curr = self.nodeParents[curr] return path def determineShortestPath(self, start, goal): stack = [] exploredNodes = [] stack.append(start) while len(stack) != 0: currentNode = stack.pop() if currentNode == goal: return currentNode nodes = self.getWalkableNodes(currentNode) for node in nodes: if not node in exploredNodes: exploredNodes.append(node) self.nodeParents[node] = currentNode stack.append(node) return start def getWalkableNodes(self, curr): walkableNodes = [] possibleNodes = [ Coordinate(curr.x + 1, curr.y), Coordinate(curr.x - 1, curr.y), Coordinate(curr.x, curr.y + 1), Coordinate(curr.x, curr.y - 1), Coordinate(curr.x + 1, curr.y + 1), Coordinate(curr.x - 1, curr.y - 1), Coordinate(curr.x - 1, curr.y + 1), Coordinate(curr.x + 1, curr.y - 1) ] for node in possibleNodes: if self.canMove(node): walkableNodes.append(node) return walkableNodes def canMove(self, next): return next in self.walkablePositions
c4d1c892959e897259bb4ccfb61c43f4a295204a
aquibjaved/voice-speech-with-face-recognition-in-raspberrypi2
/switch2.py
489
3.546875
4
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17,GPIO.IN) input = GPIO.input(17) import time #initialise a previous input variable to 0 (assume button not pressed last) prev_input = 0 while True: #take a reading input = GPIO.input(17) #if the last reading was low and this one high, print if ((not prev_input) and input): print("Button pressed") execfile('voice.py') #update previous input prev_input = input #slight pause to debounce time.sleep(0.05)
0ebf6e438ccfaa6c55dd3505c2e23c36493145f8
3bdifatah/lab5
/ui.py
376
3.703125
4
def get_name(): name=input('name: ') return name def get_country_and_record(): country = input('country: ') record = int(input('number of chainsaws caught: ')) return country, record def get_new_record(): new_record = int(input('number of chainsaws caught: ')) return new_record def error_message(name): print(f'{name} not in the database')
610625a9a2f1491a86b3738fc0857b811beb95cf
Luni-4/random_works
/python/Exercise3.py
2,001
3.9375
4
import math def def_polygon(name, n, side): class polygon(object): def __init__(self): if side <= 0: raise ValueError("{0} is an inadmissible size for a {1}’s side".format(side, name)) def calculate_area(self): return .25 * n * side**2 * (math.tan(math.pi/n)**-1) def calculate_perimeter(self): return n*side def __lt__(self, other): return self.calculate_area() < other.calculate_area() def __str__(self): return "I’m a {0} and my area is {1}".format(name, self.calculate_area()) return polygon class Rectangle(object): def __init__(self, base, height): self._base = base self._height = height def calculate_area(self): return self._base * self._height def calculate_perimeter(self): return (self._base + self._height) * 2 def __lt__(self,other): return self.calculate_area() < other.calculate_area() def __str__(self): return "I’m a Rectangle!\nMy area is {0}\n".format(self.calculate_area()) class Circle(object): def __init__(self, ray): if ray <= 0: raise ValueError("{0} is an inadmissible size for a circle’s ray".format(ray)) self._ray=ray def calculate_area(self): return self._ray**2*math.pi def calculate_perimeter(self): return 2*self._ray*math.pi def __lt__(self,other): return self.calculate_area() < other.calculate_area() def __str__(self): return "I’m a Circle!\nMy ray is: {0}\nMy area is {1}\n".format(self._ray, self.calculate_area()) if __name__ == "__main__": l = [Rectangle(2,3), Rectangle(1,1), Circle(4)] print(l) print("\nStampa del contenuto della lista") for i in l: print(i) print() p = sorted(l, key = lambda k: k.calculate_perimeter()) m = sorted(l) print("\nStampa degli elementi ordinati") for i in m: print(i) print("\nStampa degli elementi ordinati per perimetro") for i in p: print(i.calculate_perimeter()) print("\nItera sugli elementi a seconda dell'area") for i in l: print(i)
cccb8cc1881f77ccef6a5beb5796ea2e530cb8fe
jang010505/Algorithm
/BOJ/15025.py
132
3.796875
4
a, b=map(int, input().split()) if a==0 and b==0: print("Not a moose") elif a==b: print("Even", a*2) else: print("Odd", max(a, b)*2)
88e7ca0b4f1508439e8f0efc073b4461b84dce14
mateuskienzle/training-python
/ex-030-par-ou-impar.py
173
4.09375
4
numero = int(input('Digite um número: ')) if (numero%2) == 0: print('O número {} é PAR.' .format(numero)) else: print('O número {} é ÍMPAR.' .format(numero))
bec9d002feec7aab91f1123e057b59793f49cd69
VaibhavDhaygonde7/Coding
/Python Projects/P14Dictionary_Functions.py
577
4.1875
4
d1 = {"Vaibhav":"Paneer", "Ritika":"Pani Puri", "Suresh":"Chocolate", "Vaishali":"Manchurian"} d2 = d1 #this is not the copy of d1 del d2["Vaibhav"] # Vaibhav will also be deleted from d1 print(d1) d3 = d1.copy() # d3 is the copy of d3 del d3["Ritika"] # Ritika will not be deleted from d1 print(d1) #Accessing elements from dictionary print(d1.get("Ritika")) #Adding elements using update() d1.update({"Akshay":"Nutritious Food"}) #Akshay will be added to the dictionary d1 at the end print(d1) #keys() function print(d1.keys()) #items() function print(d1)
7efc49b9dfa703d959f81b57f0c806f95cd14083
bukolaxx/hangman-python
/hangman.py
1,668
4.09375
4
import random import string from words import words from hangman_drawing import user_lives def get_valid_word(words): word = random.choice(words) #randomly chooses something from the list while '-' in word or ' ' in word: word=random.choice(words) return word.upper() def hangman(): lives =6 word = get_valid_word(words) word_letters = set(word) #letters in the word alphabet = set(string.ascii_uppercase) used_letters = set() #what the user has guessed while len(word_letters)>0 and lives>0: print('You have', lives, ' lives and you have used these letter: ', ' '.join(used_letters)) word_list=[letter if letter in used_letters else '-' for letter in word] print('Current word: ', ' '.join(word_list)) #getting user input user_letter = input('Guess a letter: ').upper() if user_letter in alphabet - used_letters: used_letters.add(user_letter) if user_letter in word_letters: word_letters.remove(user_letter) else: lives-=1 print('Letter is not in word') user_lives(lives) elif user_letter in used_letters: print('You have already guessed that charcter, try again') else: print('Invalid character') #gets here when len(word_letter) == 0 or when lives ==0 if lives == 0: print('Too bad, you lose the word was',word) else: print('You have guessed the word', word, ' !!') hangman()