blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fd2a85f35be78939583abe8dcd83ef649371b1bb
sangeetha19399/pythonguvipgm
/timemins.py
58
3.578125
4
mins=int(input()) hr=mins//60 mins=mins%60 print(hr,mins)
406f9e9d0073c5720fcc0342f52bcb3ec056a31f
lhr0909/SimonsAlgo
/_peuler/001-100/020.py
83
3.5625
4
from math import factorial print sum(int(digit) for digit in str(factorial(100)))
7f2696741019c7a1633681a3b173c48a8941bb8b
cmkemp52/PythonExercises
/upper.py
55
3.703125
4
st = input("Please enter a string: ") print(st.upper())
4e47aaa602764d1da19fbacf7457c948ff175faf
kooshanfilm/Python
/Exercise/numberof_char.py
408
4.375
4
# # # Write a Python program to count the number of characters (character frequency) # in a string. Go to the editor Sample String : # google.com' Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1} def num_char(str): count = 0 dic = {} for i in str: if i in dic: dic[i] +=1 else: dic[i] = 1 print dic num_char("google.com")
5bef5f08944cc9bca5eacce62820120dc46366bb
crescent-and-sheezer/python_text1
/11.1.py
758
3.515625
4
# _*_ coding:utf-8 # 作者:凡 # @Time: 2021/2/12 17:45 # @File: 11.1.py ''' import unittest from city_function import city_functions class test(unittest.TestCase): def test1(self): city_country = city_functions('santiago','chile') self.assertEqual(city_country,'Santiago Chile') unittest.main() ''' import unittest from city_function import city_functions class test(unittest.TestCase): def test1(self): city_country = city_functions('santiago','chile') self.assertEqual(city_country,'Santiago Chile') def test2(self): city_country_population = city_functions('santiago','chile','population=5000000') self.assertEqual(city_country_population,'Santiago Chile Population=5000000') unittest.main()
6ec8d622f4e070d93d1295e7348cf2203c951d76
danbao571/python-
/64-线程.py
1,011
3.9375
4
# 线程:执行代码的分支,默认程序中只有一个线程 import time import threading def AA(count): for i in range(count): print('aa') time.sleep(0.2) def BB(count): for i in range(count): print('bb') time.sleep(0.2) if __name__ == '__main__': # 创建子线程执行对应的代码 # target表示目标函数 # args:表示以元组方式传参 # kwargs:表示以字典方式传参 # sub_thread = threading.Thread(target=aa, args=(3,)) sub_thread = threading.Thread(target=AA, kwargs={'count': 3}) three_thread = threading.Thread(target=BB, args=(2,), daemon=True ) # 设置守护线程,主线程退出子线程会直接销毁不再执行对应代码 # sub_thread.setDaemon(True) sub_thread.start() three_thread.start() time.sleep(2) print('over') # 主线程执行bb # 主线程会等所有子线程代码执行完再退出 # BB() # 线程执行是无序的,由cpu调度决定
d87c075f626ddf41c62d37b094616e1d7f23d024
monkeylyf/interviewjam
/tree/leetcode_Add_And_Search_Word_Data_Structure_Design.py
3,121
3.6875
4
"""Add and search word data structure design leetcode Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. For example: addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true """ from collections import deque class TrieNode(object): __slots__ = ('val', 'end', 'children') def __init__(self): """ Initialize your data structure here. """ self.val = None self.end = False self.children = {} class Trie(object): def __init__(self): """""" self.root = TrieNode() self.root.val = '' def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root for char in word: try: child = node.children[char] except KeyError: child = TrieNode() child.val = char node.children[char] = child node = child node.end = True def search(self, pattern): """Return all end nodes whose paths fit given pattern. Level order traversal. If current char '.', meaning wild card and all nodes at this level match. Otherwise do exact match. :param pattern: str :param return: list, of nodes """ queue = deque([self.root]) for char in pattern: count = len(queue) while queue and count > 0: node = queue.popleft() count -= 1 if char == '.': queue.extend(node.children.values()) else: try: queue.append(node.children[char]) except: pass return queue class WordDictionary(object): def __init__(self): """initialize your data structure here.""" self._trie = Trie() def addWord(self, word): """Adds a word into the data structure. :type word: str :rtype: void """ self._trie.insert(word) def search(self, word): """Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ end_nodes = self._trie.search(word) # Check any of the end nodes has end node flag. return any(node.end for node in end_nodes) def main(): # Your WordDictionary object will be instantiated and called as such: wordDictionary = WordDictionary() wordDictionary.addWord("word") assert wordDictionary.search("..rd") assert wordDictionary.search("word") assert wordDictionary.search(".o.d") assert wordDictionary.search(".o..") if __name__ == '__main__': main()
c531a0a2748d0aeaceb773c56dcd73fc1e0514e8
gamerwalt/PythonTutorials
/main.py
441
4.0625
4
#day 1 #test = input("What is your name?") #print(f"Length of your name is {len(test)}") #day1 - 1st Challenge #a = input("a:") #b = input("b:") #temp = a #a = b #b = temp #print("a = " + a) #print("b = " + b) #day1 - 2nd Challenge print("Welcome to the Band Name Generator.") city = input("What's the name of the city you grew up in?\n") pet = input("What's your pet's name?\n") print("") print(f"Your band name could be {city} {pet}")
f6bc0f1e20d4fd464862abe9619933de78553626
danieljaouen/dotfiles
/topics/bin/generate_password_hash
1,017
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals import getpass from passlib.hash import sha512_crypt def prompt(): password1, password2 = None, None prompt1 = 'Enter your desired password: ' prompt2 = 'Once more: ' invalid = "Error: your passwords didn't match. Please try again.\n" password1 = getpass.getpass(prompt=prompt1) password2 = getpass.getpass(prompt=prompt2) while password1 != password2: print(invalid) password1 = getpass.getpass(prompt=prompt1) password2 = getpass.getpass(prompt=prompt2) return password1 def hash_password(password, rounds=5000): return sha512_crypt.encrypt(password, rounds=rounds) def main(): password = prompt() print() print('-------------------------------------') print('-- Your password hash is:') print(hash_password(password)) print('-------------------------------------') if __name__ == '__main__': main()
f2490401bf0f1e596887f5a608b14b69e824b69c
andrewnester/python-problem-solutions
/problems/arrays/sum_of_four.py
1,913
3.671875
4
""" Find all four sum numbers Given an array A of size N, find all combination of four elements in the array whose sum is equal to a given value K. For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and K = 23, one of the quadruple is "3 5 7 8" (3 + 5 + 7 + 8 = 23). Input: The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains two lines. The first line of input contains two integers N and K. Then in the next line are N space separated values of the array. Output: For each test case in a new line print all the quadruples present in the array separated by space which sums up to value of K. Each quadruple is unique which are separated by a delimeter "$" and are in increasing order. Constraints: 1<=T<=100 1<=N<=100 -1000<=K<=1000 -100<=A[]<=100 """ from itertools import permutations def get_sum_of_four(arr, K): sums_of_two = {} count = len(arr) for i in range(0, count): for j in range(i + 1, count): sums_of_two.setdefault(arr[i] + arr[j], []).append( (i, j)) possible_sums = set() for s in sums_of_two.keys(): if s * 2 >= K: continue if K - s in sums_of_two: first_pairs = sums_of_two[s] second_pairs = sums_of_two[K - s] for a, b in first_pairs: for c, d in second_pairs: if a != c and a != d and b != c and b != d: need_to_add = True for p in permutations([a, b, c, d]): if p in possible_sums: need_to_add = False break if need_to_add: possible_sums.add((a, b, c, d)) return [(arr[p[0]], arr[p[1]], arr[p[2]], arr[p[3]]) for p in possible_sums]
2ecc3140b883e5a80a0205e522dbc84de439612f
gislaine-a-sa/Python---Estrutura-de-Repeticao
/Estrutura de Repetição 13.py
387
4.0625
4
print ('Estrutura de Repitação - Exercício 13') base=int(input('Informe a base:')) valor_base=base expoente=int(input('\nInforme o expoente:')) if (expoente==1) or (expoente==0): if (expoente==1): print('\nResultado: %s' % (base)) else: print('\nResultado: 1') else: for i in (range(expoente-1)): base*=valor_base print('\nResultado: %s' % (base))
e51ceed79735fbc316380b29db204f056193120c
ekrueger19/crispycode
/final.py
564
4
4
y = 0 x = raw_input("> ") print "Hello. Will you help me? Answer y/n" if x == "y": print "Thank you. I am a genie and can tell your future." print "Do you want to know your future? Answer y/n" if x == "y": print "You will die in approximately thirty seconds." elif x == "n": print "Good choice. You may leave." else: print "You have made a mistake with your answer. Please retry." elif x == "n": print "Dude. You are literally so rude. Omg." else: print "You made a mistake somewhere along the line. Try again."
ba41fb7674ef43c6253102da696332e6a8e0ae98
nervig/Starting_Out_With_Python
/Chapter_2_programming_tasks/task_10.py
576
3.96875
4
#!/usr/bin/python ''' 1,5 glass of sugar } 1 glass of oil } = 48 cookies 2.75 glass of flour } ''' glass_of_sugar = 0.028 glass_of_oil = 0.021 glass_of_flour = 0.057 amount_of_cookies = int(input("Please, enter the amount of cookies: ")) amount_sugar = amount_of_cookies * glass_of_sugar amount_oil = glass_of_oil * amount_of_cookies amount_flour = glass_of_flour * amount_of_cookies print("For maiking {} amount of cookies you need: \n {} glass of sugar\n {} glass of oil\n {} glass of flour".format(amount_of_cookies, amount_sugar, amount_oil, amount_flour, 1))
15e12f2775a5ac2dc968dab50eaeef3e322f2601
nwweber/time_tagging
/aligners.py
4,577
3.671875
4
import re __author__ = 'niklas' """ Containing different classes implementing the align-interface. Writing your own: Recommended method: Make your own class Inherit from AbstractAligner Implement align() method This would look something like this: class MyAlignerWhichDoesCoolStuff(AbstractAligner): def align(self, transcriptions, audio_path=""): [Logic] return words_dicts Then, to use your own aligner: Go into 'annotate_forrest.py' Make your aligner available by adding the following to the top of the file: from aligners import MyAlignerWhichDoesCoolStuff In the if __name__ == "__main__" block: Find the "aligner = ..." line Change it to "aligner = MyAlignerWhichDoesCoolStuff()" However, inheriting from AbstractAligner is not a necessity. As long as your class has an align() class with the right signature you are good to go """ import abc class AbstractAligner(): """ Class defining the align interface. Inherit from this, implement align method in sublcasses """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def align(self, transcriptions, audio_path=""): """ Given a pandas DataFrame with transcriptions (columns: t_start, t_end, text) and possibly a path to a matching audio file, return a list of time-tagged words :param transcriptions: pd data frame, columns: t_start, t_end, text. text can coin multiple sentences per row :param audio_path: possible path to audio data :return: list, each element a dict with t_start, t_end, text, in which 'text' is only one word. words are all lowercase """ return @staticmethod def extract_row_data(row): """ Given a row of transcription data, return the fields and the time difference. Purely for convenience. """ t_start = row["t_start"] t_end = row["t_end"] words = AbstractAligner.sentences2words(row["text"]) timediff = t_end - t_start return t_start, t_end, timediff, words @staticmethod def sentences2words(sentence): """ In: String possibly containing multiple sentences and special characters Out: List of words """ # splits into words, drops all special characters words = re.sub("[^\w]", " ", sentence).split() words = list(words) return words class AbstractRowBasedAligner(AbstractAligner): """Inherit from this if your aligner does things row-by-row""" @abc.abstractmethod def row2words_dicts(self, row): return def align(self, transcriptions, audio_path=""): words_dicts = [] for i in range(transcriptions.shape[0]): row = transcriptions.iloc[i] words_dicts.extend(self.row2words_dicts(row)) for word_dict in words_dicts: word_dict["text"] = word_dict["text"].lower() return words_dicts class UniformAligner(AbstractRowBasedAligner): """ Gives equal time to each word in a text block """ def row2words_dicts(self, row): print("doing uniform row alignment") words_dicts = [] t_start, t_end, timediff, words = self.extract_row_data(row) word_time = timediff / len(words) # idea: each word in a sentence uses the same amount of time, approximately for i, word in enumerate(words): words_dicts.append({"t_start": t_start + i * word_time, "t_end": t_start + (i + 1) * word_time, "text": word}) return words_dicts class WeightedAligner(AbstractRowBasedAligner): """ Time in a block is divided according to word weight """ def row2words_dicts(self, row): words_dicts = [] t_start, t_end, timediff, words = self.extract_row_data(row) weights = [len(word) for word in words] total = sum(weights) weight_fractions = [weight / total for weight in weights] time_fractions = [weight_fraction * timediff for weight_fraction in weight_fractions] offset = t_start for i, word in enumerate(words): words_dicts.append({"t_start": offset, "t_end": offset + time_fractions[i], "text": word}) offset += time_fractions[i] # print("word {}, time fraction: {}".format(word, time_fractions[i])) return words_dicts
fea0c4615381d80d8a6c29ac69bf1cb82b26becc
sakshi72000/PythonPrograms
/Program5.py
199
4
4
# Assignment 1 # Program 5 : Program to display the numbers def Display(): iCnt = 10 while iCnt > 0: print(iCnt) iCnt = iCnt - 1 def main(): Display() if __name__ == "__main__": main()
fa799975c815e8fce239c83696583635b4f2210e
kimmincheol7/ComputerVision
/5.py
816
3.8125
4
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> if x == 3: print "X equals 3." elif x == 2: print "X equals 2." else: print "X equals something else." print "This is outside the ‘if’." SyntaxError: expected an indented block >>> x = 3 >>> while x < 5: print x, "still in the loop" x = x + 1 3 still in the loop 4 still in the loop >>> x = 6 >>> while x < 5: print x, "still in the loop" SyntaxError: multiple statements found while compiling a single statement >>> assert(number_of_players < 5) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> assert(number_of_players < 5) NameError: name 'number_of_players' is not defined >>>
64d438c64084e70477b896a1b6f338e90db3c86f
iso1234/majorwork
/website/templateEngine.py
17,445
3.59375
4
import re import html # Used to stop html injections import copy # Used to make deepcopys of dictionarys def renderTemplate(filename:str, context:dict): """ Renders HTML from a template file """ # Get template string with open("templates/" + filename, encoding='utf-8') as f: template = f.read() template = template.replace('“', '"') # Removes smart quotes template = template.replace('”', '"') # Ditto context = copy.deepcopy(context) # Parse the template string and create node tree tree = parse(template) # Render the node tree and return the result return render(tree, context) def parse(template:str): """ Checks the syntax of the template file 'template' and creates and returns a node tree """ lex = Lexer(template) # Create lexer object and pass it the template string nodeTree = lex.parse() # Call the parse method that will parse the string and return a node tree return nodeTree def render(nodeTree:object, context:dict): """ Calls the .render() method on the head of the node tree """ return nodeTree.render(context) def getNodeType(string:str): """ Returns what type of node 'string' starts with """ if re.match(r'{{.*}}', string) is not None: # Check if is a python expression tag return "python" elif re.match(r'{% *include.*%}', string) is not None: # Check if its an include tag return "include" elif re.match(r'{% *let.*%}', string) is not None: # Check if its an let tag return "let" elif re.match(r'{% *safe.*%}', string) is not None: # Check if its an safe tag return "safe" elif re.match(r'{% *if.*%}.*{% *end *if *%}', string, re.DOTALL) is not None: # Check if its a pair of 'if' tags return "if" elif re.match(r'{% *comment *%}.*{% *end *comment *%}', string, re.DOTALL) is not None: # Check if its a pair of 'if' tags return "comment" elif re.match(r'{% *for.*in.*%}.*{% *end *for *%}', string, re.DOTALL) is not None: # Check if its a pair of 'for' tags return "for" # The following two conditions are used in parseIf() and parseFor() but ignored in parse() elif re.match(r'{% *end *for *%}', string) is not None: # Check if its an 'end for' tag return "endfor" elif re.match(r'{% *end *if *%}', string) is not None: # Check if its an 'end if' tag return "endif" # This is used in parseIf() but ignored in parse() elif re.match(r'{% *else *%}', string) is not None: return "else" # This is used in parseFor() but ignored in parse() elif re.match(r'{% *empty *%}', string) is not None: return "empty" else: return "text" class Lexer: # This checks the syntax and creates a node tree def __init__(self, template:str): self.template = template self.upto = 0 self.nodeTree = GroupNode() # Head node of the tree def peek(self, amt=1): """ Returns the next 'amt' character (Returns none if thats past the end of the string) """ if self.upto+amt-1 < len(self.template): return self.template[self.upto:self.upto+amt] def next(self): self.upto += 1 def parse(self): """ Parses self.template and returns a node tree """ nodeTree = GroupNode() while self.upto < len(self.template): # While there's still input left nodeType = getNodeType(self.template[self.upto:]) if nodeType in ["text", "endif", "endfor", "else", "empty"]: nodeTree.children.append(self.parseText()) elif nodeType == "python": nodeTree.children.append(self.parsePython()) elif nodeType == "include": nodeTree.children.append(self.parseInclude()) elif nodeType == "let": nodeTree.children.append(self.parseLet()) elif nodeType == "safe": nodeTree.children.append(self.parseSafe()) elif nodeType == "comment": self.parseComment() elif nodeType == "if": nodeTree.children.append(self.parseIf()) elif nodeType == "for": nodeTree.children.append(self.parseFor()) return nodeTree def parseText(self, flag=""): """ This parses a text node. This will continue to parse until it finds another node. This function usually treats nodes of type "endif" and "endfor" as plain text. When the flag argument is set to either of these values it will stop pasing when it reaches a node of said type. This is useful when parsing an if or for block. """ start = self.upto # While its not the start of another node or the end of the string nodeType = getNodeType(self.template[self.upto:]) while nodeType == "text" and nodeType != flag and self.peek() is not None: self.next() nodeType = getNodeType(self.template[self.upto:]) # Return text node object return TextNode(self.template[start:self.upto]) def parsePython(self): start = self.upto while self.peek(2) != "}}": # While its not the end of the node self.next() # Skip the ending brackets self.next() self.next() # Return python node object return PythonNode(self.template[start:self.upto]) def parseInclude(self): start = self.upto while self.peek(2) != "%}": # While its not the end of the node self.next() # Skip the ending '%}' self.next() self.next() # Return an include object return IncludeNode(self.template[start:self.upto]) def parseLet(self): start = self.upto while self.peek(2) != "%}": # While its not the end of the node self.next() # Skip the ending '%}' self.next() self.next() # Return a let object return LetNode(self.template[start:self.upto]) def parseSafe(self): start = self.upto while self.peek(2) != "%}": # While its not the end of the node self.next() # Skip the ending '%}' self.next() self.next() # Return a safe object return SafeNode(self.template[start:self.upto]) def parseComment(self): start = self.upto # Look for the start of the {% end comment %} tag while re.match(r'{% *end *comment *%}', self.template[self.upto:]) is not None: self.next() # Look for the end of the {% end comment %} tag while self.peek(2) != "%}": self.next() # Skip the ending '%}' self.next() self.next() def parseIf(self): """ This parses an if node. It uses a version of parse() to parse the inner code block. This is different from the parse function because the flag "endif" is used when calling the parseText() function to stop it treating the end if tag as plain text. This version of parse() also deals with "else" nodes. """ ifNodeObject = IfNode() start = self.upto # Look for the end of the 'if' tag while self.peek(2) != "%}": self.next() self.next() self.next() # Add the 'if' tag to the ifNode object ifNodeObject.ifTag = self.template[start:self.upto] # Create objects and add them to the ifNodeObject's children list while re.match(r'{% *end *if *%}', self.template[self.upto:]) is None and self.peek(): nodeType = getNodeType(self.template[self.upto:]) if nodeType == "python": ifNodeObject.children.append(self.parsePython()) elif nodeType == "include": ifNodeObject.children.append(self.parseInclude()) elif nodeType == "let": ifNodeObject.children.append(self.parseLet()) elif nodeType == "if": ifNodeObject.children.append(self.parseIf()) elif nodeType == "for": ifNodeObject.children.append(self.parseFor()) elif nodeType == "text": ifNodeObject.children.append(self.parseText("endif")) elif nodeType == "safe": ifNodeObject.children.append(self.parseSafe()) elif nodeType == "comment": self.parseComment() elif nodeType == "else": self.parseElse() ifNodeObject.children.append("else") if self.peek() is None: raise SyntaxError("Unexpected EOF while parsing.\n \ This is possibly caused by the absence of an {% end if %} tag") # Look for the end of the {% end if %} tag while self.peek(2) != "%}": self.next() # Skip the ending '%}' self.next() self.next() # Return an if object return ifNodeObject def parseElse(self): # Look for the end of the {% else %} tag while self.peek(2) != "%}": self.next() # Skip the ending '%}' self.next() self.next() def parseEmpty(self): # Look for the end of the {% empty %} tag while self.peek(2) != "%}": self.next() # Skip the ending '%}' self.next() self.next() def parseFor(self): """ This parses an for node. It uses a version of parse() to parse the inner code block. This is different from the parse function because the flag "endfor" is used when calling the parseText() function to stop it treating the end for tag as plain text. This version of parse() also deals with "empty" nodes. """ forNodeObject = ForNode() start = self.upto # Look for the end of the 'for' tag while self.peek(2) != "%}": self.next() self.next() self.next() # Add the 'for' tag to the forNode object forNodeObject.forTag = self.template[start:self.upto] # Create objects and add them to the forNodeObject's children list while re.match(r'{% *end *for *%}', self.template[self.upto:]) is None and self.peek() is not None: nodeType = getNodeType(self.template[self.upto:]) if nodeType == "python": forNodeObject.children.append(self.parsePython()) elif nodeType == "include": forNodeObject.children.append(self.parseInclude()) elif nodeType == "let": forNodeObject.children.append(self.parseLet()) elif nodeType == "if": forNodeObject.children.append(self.parseIf()) elif nodeType == "for": forNodeObject.children.append(self.parseFor()) elif nodeType == "text": forNodeObject.children.append(self.parseText("endfor")) elif nodeType == "safe": forNodeObject.children.append(self.parseSafe()) elif nodeType == "comment": self.parseComment() elif nodeType == "empty": self.parseElse() forNodeObject.children.append("empty") # If it didn't find a closing tag if self.peek() is None: raise SyntaxError("Unexpected EOF while parsing.\n \ This is possibly caused by the absence of an {% end for %} tag") # Look for the end of the {% end for %} tag while self.peek(2) != "%}": self.next() # Skip the ending '%}' self.next() self.next() # Return an for object return forNodeObject class GroupNode: def __init__(self, children=None): if children == None: self.children = [] else: self.children = children self.output = [] def render(self, context:dict): output = [] for child in self.children: output.append(str(child.render(context))) return "".join(output) class PythonNode: def __init__(self, content): self.content = content self.content = self.content[2:-2].strip() def render(self, context): try: return html.escape(str(eval(self.content, {}, context))) except NameError: # If there is an unknown variable return "" class SafeNode: def __init__(self, content): self.content = content def render(self, context): self.content = self.content[2:-2].replace("safe", "").strip() try: return eval(self.content, {}, context) except NameError: # If there is an unknown variable return "" class TextNode: def __init__(self, content): self.content = content def render(self, context): return self.content class IncludeNode: def __init__(self, content): self.content = content def render(self, context): # Create a string for the file name and a string for the arguments (variable assignments) fileName, *argumentString = self.content[2:-2].replace("include", "", 1).strip().split(" ") argumentString = " ".join(argumentString) # Remove any quotation marks fileName = fileName.strip("'").strip('"') # Split the arguments up arguments = [] match = re.match(r'( *\w* *= *\w*)', argumentString) while match is not None: arguments.append(match.group(1).replace(" ", "")) argumentString = argumentString[len(match.group(1)):] match = re.match(r'( *\w* *= *\w*)', argumentString) # Call the file with the new arguments (if there are any) newContext = copy.deepcopy(context) if len(arguments) >= 1: for variable in arguments: key, value = variable.split("=") newContext[key] = eval(value, {}, context) return renderTemplate(fileName, newContext) class LetNode: def __init__(self, content): self.content = content def render(self, context): var, expression = self.content[2:-2].replace("let", "").strip().split("=") context[var.strip()] = eval(expression, {}, context) return "" class IfNode: def __init__(self): self.ifTag = "" self.children = [] def render(self, context): ifTrue = [] # Will be returned if the condition is true ifFalse = []# Will be returned if the condition is false # Evaluate the condition try: condition = eval(self.ifTag[2:-2].replace("if", "").strip(), {}, context) except NameError: # If a variable in the condition isn't defined condition = False # Check for an else node if "else" in self.children: index = self.children.index("else") ifTrue = self.children[:index] ifFalse = self.children[index+1:] else: ifTrue = self.children # Render output = [] if condition: for child in ifTrue: output.append(str(child.render(context))) else: for child in ifFalse: output.append(str(child.render(context))) return "".join(output) class ForNode: def __init__(self): self.forTag = "" self.children = [] def render(self, context): ifNotEmpty = [] ifEmpty = [] # Split the for node into the iterable and the variables variables, iterable = self.forTag[2:-2].replace("for", "").split("in") variables = variables.split(",") try: iterable = eval(iterable, {}, context) except NameError: # If a variable in the iterable isn't defined return "" # Check for tuple/string/list unpacking if len(variables) > 1: for item in iterable: if len(item) != len(variables): return "" # Check for an empty node if "empty" in self.children: index = self.children.index("empty") ifNotEmpty = self.children[:index] ifEmpty = self.children[index+1:] else: ifNotEmpty = self.children # Render output = [] if iterable: for item in iterable: # If tuple/list/string unpacking needs to be dealt with if len(variables) > 1: # Add multiple new variables to the context newContext = copy.deepcopy(context) for index, var in enumerate(variables): newContext[var.strip()] = item[index] # If tuple/list/string unpacking doesn't need to be dealt with else: # Add the new variable to the context newContext = copy.deepcopy(context) newContext[variables[0].strip()] = item # Render each node in the codeblock with the new context for child in ifNotEmpty: output.append(child.render(newContext)) # If the iterable is empty else: for child in ifEmpty: output.append(str(child.render(context))) return "".join(output)
d1c08b7aba6fd22593327cc5ccec7a3fb2324f74
FengZhe-ZYH/CS61A_2020Summer
/debug.py
1,827
3.75
4
# Interactive Debugging # python -i file.py # python ok -q <question name> -i # Visualizer # http://pythontutor.com/composingprograms.html#mode=edit # python ok -q <question name> --trace # doctest # python3 -m doctest file.py # python3 -m doctest file.py -v # Note: prefixing debug statements with the specific string "DEBUG: " # allows them to be ignored by the ok auto grader used by cs61a. # use a global debug variable debug = True def foo(n): i = 0 while i < n: i += func(i) if debug: print('DEBUG: i is', i) def func(i): pass # Python has a feature known as an assert statement, which lets you test that a condition is true, and print an error # message otherwise in a single line. This is useful if you know that certain conditions need to be true at certain # points in your program. For example, if you are writing a function that takes in an integer and doubles it, # it might be useful to ensure that your input is in fact an integer. You can then write the following code def double(x): assert isinstance(x, int), "The input to double(x) must be an integer" return 2 * x # One major benefit of assert statements is that they are more than a debugging tool, you can leave them in code # permanently. A key principle in software development is that it is generally better for code to crash than produce # an incorrect result, and having asserts in your code makes it far more likely that your code will crash if it has a # bug in it. # The reason the error message says "global name" is because Python will start searching for the variable from a # function's local frame. If the variable is not found there, Python will keep searching the parent frames until it # reaches the global frame. If it still can't find the variable, Python raises the error. IndexError
03daefc047af77a8e27364eb145b1a1bcc3ac87e
520Coder/Python-Programming-for-Beginners-Hands-on-Online-Lab-
/Section 7/Student Resources/Assignment Solution Scripts/assignment_tuples_01_basics.py
1,861
4.53125
5
# Tuples # Assignment 1 tuple_numbers = (1, 2, 3, 4, 5) tuple_groceries = ('coconuts', 'bananas', 'onions', 'spinach', 'tomatoes', 'cilantro', 'milk') groceries_inventory = ('coconuts', 'tomatoes', 'onions', 'coconuts', 'bananas', 'onions', 'spinach', 'tomatoes', 'cilantro', 'milk', 'spinach', 'tomatoes', 'cilantro', 'tomatoes') tuple_nested =((1, 2, 3), ["Python", "Database", "System"], 'Coding') tuple_numbers_100s = (100, 200, 300, 400, 500) # Print 3rd item from tuple_groceries print("*" * 50) print("The 3rd item of tuple_groceries :", tuple_groceries[2]) # Print the length of tuple_groceries print("*" * 50) print("The length of tuple_groceries :", len(tuple_groceries)) # Print the reverse of tuple_numbers & tuples_names print("*" * 50) tuple_groceries_rev = tuple(reversed(tuple_groceries)) print("Reverse of tuple_groceries :", tuple_groceries_rev) # Print "Python" from "tuple_nested" print("*" * 50) print(tuple_nested[1][0]) # Unpack tuple_groceries tuple and print them print("*" * 50) print("Unpacking...") g1, g2, g3, g4, g5, g6, g7, = tuple_groceries print(g1) print(g1) print(g2) print(g3) print(g4) print(g5) print(g6) print(g7) # Swap tuple_numbers and tuple_numbers_100s print("*" * 50) print("Swapping...") tuple_numbers, tuple_numbers_100s = tuple_numbers_100s, tuple_numbers print("tuple_numbers_100s :", tuple_numbers_100s) print("tuple_numbers :", tuple_numbers) # Construct a new tuple "tuples_a" by extracting # bananas, onions, spinach from tuples_groceries print("*" * 50) print("Subset items.... bananas, onions, spinach") tuples_a = tuple_groceries[1:4] print("tuples_a :", tuples_a) # Count the number of times coconuts is listed in groceries_inventory tuple print("*" * 50) print("Count the number of times coconuts...") coconut_count = groceries_inventory.count("coconuts") print("coconuts :", coconut_count)
01cc8af42c78b54f2ebe3989904359c29f5015e8
paradigmadigital/hackathon-image-processing
/formacion02.py
889
3.890625
4
import cv2 import numpy as np # Create a black image img = np.zeros((512, 512, 3), np.uint8) # Draw a diagonal blue line with thickness of 5 px # PARAMETERS # img : The image where you want to draw the shapes # color : Color of the shape. for BGR, pass it as a tuple, eg: (255,0,0) for blue. For grayscale, just pass the scalar value. # thickness : Thickness of the line or circle etc. If -1 is passed for closed figures like circles, it will fill the shape. default thickness = 1 # lineType : Type of line, whether 8-connected, anti-aliased line etc. By default, it is 8-connected. cv2.LINE_AA gives anti-aliased line which looks great for curves. cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5) cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3) cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()
bfd843b1547e2d96d87df5fcf36acf426da08b84
SakuraSa/MyLeetcodeSubmissions
/Jump Game/Accepted-13672434.py
1,215
3.5625
4
#Author : [email protected] #Question : Jump Game #Link : https://oj.leetcode.com/problems/jump-game/ #Language : python #Status : Accepted #Run Time : 196 ms #Description: #Given an array of non-negative integers, you are initially positioned at the first index of the array. #Each element in the array represents your maximum jump length at that position. #Determine if you are able to reach the last index. #For example: #A = `[2,3,1,1,4]`, return `true`. #A = `[3,2,1,0,4]`, return `false`. #Show Tags #ArrayGreedy #Code : class Solution: # @param A, a list of integers # @return a boolean def canJump(self, A): if len(A) == 0: return False elif len(A) == 1: return True max_index = 0 max_reach = 0 step = 0 while max_reach < len(A) - 1: old_max_index = max_index max_index = max_reach for i in range(old_max_index, max_reach + 1): max_reach = max(max_reach, i + A[i]) if max_reach >= len(A): return True step += 1 if max_reach <= max_index: return False return True
25ceef79216d5ac68a3d98a724c6f7cad181ae43
20171609/programmers
/printer.py
574
3.53125
4
from collections import deque def solution(priorities, location): answer = 0 que = deque([i for i in priorities]) maxnum = max(que) while (que): if que[0] == maxnum: que.popleft() answer += 1 if location == 0: break maxnum = max(que) location -= 1 else: print(que[0]) if location == 0: location = len(que) location -= 1 que.append(que.popleft()) return answer
239d2cde02bfe97b25ffa67d7cab9fcd05953e47
Aries5522/daily
/2021届秋招/leetcode/哈希表/数组中出现次数超过一半的数字.py
1,118
3.640625
4
''' 数组中出现次数超过一半的数字 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。 ''' from typing import List class Solution: def majorityElement(self, nums: List[int]) -> int: hash_map={} n=len(nums) # if n==0: # return None for i in nums: if i not in hash_map: hash_map[i]=1 if hash_map[i]>int(n/2): return i else: hash_map[i]+=1 if hash_map[i]>int(n/2): return i return None ''' O(1)空间解法 ''' class Solution: def majorityElement(self, nums: List[int]) -> int: n=len(nums) # if n==0: # return None ans=nums[0] t=1 for i in range(1,n): if nums[i] == ans: t+=1 else: t-=1 if t==0: ans=nums[i] t=1 return ans
2016a56b3f902cac5d9e4a88b2b952fd602596bd
ClavinSBU/CSE304
/hw5/codegen.py
18,340
3.953125
4
import ast import absmc # TODO: # ?? #################################################################################################### # Global vars that hold label objects for different expressions / statements label_scope = [] # This holds the label used for a `continue` statement in a loop # For `for` loops, this points to the update expression # For `while` loops, this points to the condition expression current_loop_continue_label = None # This holds the entrance of a loop, or the then part of an if statement current_enter_then_label = None # This holds the loop's exit or the else part of an if statement current_break_out_else_label = None # Examples: # if we're in an if stmt where: # # if (x < y && x == z) { # x++; # } else { # x--; # } # then if x < y BinaryExpr evals to false, we know to jump to the else branch # and use the label called 'current_break_out_else_label' # similarly, if we're in a loop where: # # while (x < y || x < z) { # x++; # } # # if x < y evals to true, jump into the body of the loop # which is the label held by current_enter_then_label non_static_field_offset = 0 current_method = None def push_labels(): global label_scope global current_loop_continue_label, current_enter_then_label, current_break_out_else_label label_scope.append(current_loop_continue_label) label_scope.append(current_enter_then_label) label_scope.append(current_break_out_else_label) def pop_labels(): global label_scope global current_loop_continue_label, current_enter_then_label, current_break_out_else_label current_break_out_else_label = label_scope.pop() current_enter_then_label = label_scope.pop() current_loop_continue_label = label_scope.pop() def calc_nonstatic_offsets(cls): '''Calculates the offsets for all instance fields of a class. Walks up the hierarchy and assigns each instance field a unique offset. At the end, it sets the class's size to number of instance fields.''' global non_static_field_offset if cls.superclass is not None: calc_nonstatic_offsets(cls.superclass) for field in cls.fields.viewvalues(): if field.storage == 'instance': field.offset = non_static_field_offset print '# field {} given {}'.format(field.name, non_static_field_offset) non_static_field_offset += 1 cls.size = non_static_field_offset def calc_static_offsets(cls): for field in cls.fields.viewvalues(): if field.storage == 'static': field.offset = absmc.machine.static_data absmc.machine.add_static_field() def preprocess(cls): global non_static_field_offset calc_static_offsets(cls) non_static_field_offset = 0 calc_nonstatic_offsets(cls) def generate_code(classtable): for cls in classtable.viewvalues(): preprocess(cls) for cls in classtable.viewvalues(): generate_class_code(cls) def setup_registers(method): # block 0 are the formals, which go into args # if static, first arg is a0, # if instance, first arg is a1, as `this` goes in a0 if isinstance(method, ast.Method) and method.storage == 'static': absmc.Register.count = 0 else: absmc.Register.count = 1 for var in method.vars.vars[0].values(): var.reg = absmc.Register('a') print '# var {} given {}'.format(var.name, var.reg) absmc.Register.count = 0 # rest of the vars in the method go into t registers for block in range(1, len(method.vars.vars)): for var in method.vars.vars[block].values(): var.reg = absmc.Register('t') print '# var {} given {}'.format(var.name, var.reg) def generate_class_code(cls): global current_method for method in cls.methods: setup_registers(method) current_method = method method.returned = False absmc.MethodLabel(method.name, method.id) gen_code(method.body) if not method.returned: absmc.ProcedureInstr('ret') for constr in cls.constructors: setup_registers(constr) current_method = constr constr.returned = False absmc.ConstructorLabel(constr.id) gen_code(constr.body) if not constr.returned: absmc.ProcedureInstr('ret') # We assume constrs don't have a return def gen_code(stmt): global current_loop_continue_label, current_enter_then_label, current_break_out_else_label # stmt.end_reg is the destination register for each expression stmt.end_reg = None push_labels() if isinstance(stmt, ast.BlockStmt): for stmt_line in stmt.stmtlist: gen_code(stmt_line) elif isinstance(stmt, ast.ExprStmt): gen_code(stmt.expr) elif isinstance(stmt, ast.AssignExpr): gen_code(stmt.rhs) gen_code(stmt.lhs) if stmt.lhs.type == ast.Type('float') and stmt.rhs.type == ast.Type('int'): conv = absmc.ConvertInstr('itof', stmt.rhs.end_reg) stmt.rhs.end_reg = conv.dst if not isinstance(stmt.lhs, ast.FieldAccessExpr): absmc.MoveInstr('move', stmt.lhs.end_reg, stmt.rhs.end_reg) else: absmc.HeapInstr('hstore', stmt.lhs.base.end_reg, stmt.lhs.offset_reg, stmt.rhs.end_reg) elif isinstance(stmt, ast.VarExpr): stmt.end_reg = stmt.var.reg elif isinstance(stmt, ast.ConstantExpr): reg = absmc.Register() if stmt.kind == 'int': absmc.MoveInstr('move_immed_i', reg, stmt.int, True) elif stmt.kind == 'float': absmc.MoveInstr('move_immed_f', reg, stmt.float, True) elif stmt.kind == 'string': pass elif stmt.kind == 'True': absmc.MoveInstr('move_immed_i', reg, 1, True) elif stmt.kind == 'False': absmc.MoveInstr('move_immed_i', reg, 0, True) elif stmt.kind == 'Null': absmc.MoveInstr('move_immed_i', reg, 'Null', True) stmt.end_reg = reg elif isinstance(stmt, ast.BinaryExpr): if stmt.bop not in ['and', 'or']: gen_code(stmt.arg1) gen_code(stmt.arg2) reg = absmc.Register() flt = ast.Type('float') intg = ast.Type('int') if stmt.arg1.type == flt or stmt.arg2.type == flt: expr_type = 'f' else: expr_type = 'i' if stmt.arg1.type == intg and stmt.arg2.type == flt: conv = absmc.Convert('itof', stmt.arg1.end_reg) stmt.arg1.end_reg = conv.dst elif stmt.arg1.type == flt and stmt.arg2.type == intg: conv = absmc.Convert('itof', stmt.arg2.end_reg) stmt.arg2.end_reg = conv.dst if stmt.bop in ['add', 'sub', 'mul', 'div', 'gt', 'geq', 'lt', 'leq']: absmc.ArithInstr(stmt.bop, reg, stmt.arg1.end_reg, stmt.arg2.end_reg, expr_type) elif stmt.bop == 'eq' or stmt.bop == 'neq': absmc.ArithInstr('sub', reg, stmt.arg1.end_reg, stmt.arg2.end_reg, expr_type) if stmt.bop == 'eq': # check if r2 == r3 # 1. perform sub r1, r2, r3 (done above) # 2. branch to set_one if r1 is zero # 3. else, fall through and set r1 to zero # 4. jump out so we don't set r1 to one by accident ieq_set = absmc.BranchLabel(stmt.lines, 'SET_EQ') ieq_out = absmc.BranchLabel(stmt.lines, 'SET_EQ_OUT') absmc.BranchInstr('bz', ieq_set, reg) absmc.MoveInstr('move_immed_i', reg, 0, True) absmc.BranchInstr('jmp', ieq_out) ieq_set.add_to_code() absmc.MoveInstr('move_immed_i', reg, 1, True) ieq_out.add_to_code() if stmt.bop == 'and': and_skip = absmc.BranchLabel(stmt.lines, 'AND_SKIP') gen_code(stmt.arg1) reg = absmc.Register() absmc.MoveInstr('move', reg, stmt.arg1.end_reg) absmc.BranchInstr('bz', and_skip, stmt.arg1.end_reg) gen_code(stmt.arg2) absmc.MoveInstr('move', reg, stmt.arg2.end_reg) and_skip.add_to_code() if stmt.bop == 'or': or_skip = absmc.BranchLabel(stmt.lines, 'OR_SKIP') gen_code(stmt.arg1) reg = absmc.Register() absmc.MoveInstr('move', reg, stmt.arg1.end_reg) absmc.BranchInstr('bnz', or_skip, stmt.arg1.end_reg) gen_code(stmt.arg2) absmc.MoveInstr('move', reg, stmt.arg2.end_reg) or_skip.add_to_code() stmt.end_reg = reg elif isinstance(stmt, ast.ForStmt): # for-loop: # for (i = 0; i < 10; i++) { # body # } # set i's reg equal to 0 # create a label after this, as this is where we jump back to at end of loop # also create the 'out' label which is what we jump to when breaking out of loop # generate code for the 'cond' (test if i's reg is less than 10's reg) # test if the cond evaluated to false with 'bz', if so, break out of loop # else, fall through into the body of the for-loop # when body is over, generate code to update the var (i++) # jump unconditionally back to the cond_label, where we eval if i is still < 10 gen_code(stmt.init) cond_label = absmc.BranchLabel(stmt.lines, 'FOR_COND') current_enter_then_label = entry_label = absmc.BranchLabel(stmt.lines, 'FOR_ENTRY') current_loop_continue_label = continue_label = absmc.BranchLabel(stmt.lines, 'FOR_UPDATE') current_break_out_else_label = out_label = absmc.BranchLabel(stmt.lines, 'FOR_OUT') cond_label.add_to_code() gen_code(stmt.cond) absmc.BranchInstr('bz', out_label, stmt.cond.end_reg) entry_label.add_to_code() gen_code(stmt.body) continue_label.add_to_code() gen_code(stmt.update) absmc.BranchInstr('jmp', cond_label) out_label.add_to_code() elif isinstance(stmt, ast.AutoExpr): gen_code(stmt.arg) if stmt.when == 'post': tmp_reg = absmc.Register() absmc.MoveInstr('move', tmp_reg, stmt.arg.end_reg) one_reg = absmc.Register() # Load 1 into a register absmc.MoveInstr('move_immed_i', one_reg, 1, True) absmc.ArithInstr('add' if stmt.oper == 'inc' else 'sub', stmt.arg.end_reg, stmt.arg.end_reg, one_reg) if stmt.when == 'post': stmt.end_reg = tmp_reg else: stmt.end_reg = stmt.arg.end_reg elif isinstance(stmt, ast.SkipStmt): pass elif isinstance(stmt, ast.ReturnStmt): current_method.returned = True if stmt.expr is None: absmc.ProcedureInstr('ret') return gen_code(stmt.expr) # Load the result into a0 absmc.MoveInstr('move', absmc.Register('a', 0), stmt.expr.end_reg) # Return to caller absmc.ProcedureInstr('ret') elif isinstance(stmt, ast.WhileStmt): current_loop_continue_label = cond_label = absmc.BranchLabel(stmt.lines, 'WHILE_COND') current_enter_then_label = entry_label = absmc.BranchLabel(stmt.lines, 'WHILE_ENTRY') current_break_out_else_label = out_label = absmc.BranchLabel(stmt.lines, 'WHILE_OUT') cond_label.add_to_code() gen_code(stmt.cond) absmc.BranchInstr('bz', out_label, stmt.cond.end_reg) entry_label.add_to_code() gen_code(stmt.body) absmc.BranchInstr('jmp', cond_label) out_label.add_to_code() elif isinstance(stmt, ast.BreakStmt): absmc.BranchInstr('jmp', current_break_out_else_label) elif isinstance(stmt, ast.ContinueStmt): absmc.BranchInstr('jmp', current_loop_continue_label) elif isinstance(stmt, ast.IfStmt): # if (x == y) # ++x; # else # --x; # generate 2 labels, for the else part, and the out part # test if x == y # if not true, jump to the else part # if true, we're falling through to the then part, then must jump # out right before hitting the else part straight to the out part current_enter_then_label = then_part = absmc.BranchLabel(stmt.lines, 'THEN_PART') current_break_out_else_label = else_part = absmc.BranchLabel(stmt.lines, 'ELSE_PART') out_label = absmc.BranchLabel(stmt.lines, 'IF_STMT_OUT') gen_code(stmt.condition) absmc.BranchInstr('bz', else_part, stmt.condition.end_reg) then_part.add_to_code() gen_code(stmt.thenpart) absmc.BranchInstr('jmp', out_label) else_part.add_to_code() gen_code(stmt.elsepart) out_label.add_to_code() elif isinstance(stmt, ast.FieldAccessExpr): gen_code(stmt.base) cls = ast.lookup(ast.classtable, stmt.base.type.typename) field = ast.lookup(cls.fields, stmt.fname) offset_reg = absmc.Register() ret_reg = absmc.Register() absmc.MoveInstr('move_immed_i', offset_reg, field.offset, True) absmc.HeapInstr('hload', ret_reg, stmt.base.end_reg, offset_reg) stmt.offset_reg = offset_reg stmt.end_reg = ret_reg elif isinstance(stmt, ast.ClassReferenceExpr): stmt.end_reg = absmc.Register('sap') elif isinstance(stmt, ast.NewObjectExpr): recd_addr_reg = absmc.Register() size_reg = absmc.Register() absmc.MoveInstr('move_immed_i', size_reg, stmt.classref.size, True) absmc.HeapInstr('halloc', recd_addr_reg, size_reg) if stmt.constr_id is None: stmt.end_reg = recd_addr_reg return saved_regs = [] saved_regs.append(recd_addr_reg) # add a0 if the current method is not static if current_method.storage != 'static': saved_regs.append(absmc.Register('a', 0)) # for each var in each block of the current method, add to save list for block in range(0, len(current_method.vars.vars)): for var in current_method.vars.vars[block].values(): saved_regs.append(var.reg) # save each reg in the saved list for reg in saved_regs: absmc.ProcedureInstr('save', reg) absmc.MoveInstr('move', absmc.Register('a', 0), recd_addr_reg) arg_reg_index = 1 for arg in stmt.args: gen_code(arg) absmc.MoveInstr('move', absmc.Register('a', arg_reg_index), arg.end_reg) arg_reg_index += 1 absmc.ProcedureInstr('call', 'C_{}'.format(stmt.constr_id)) # restore regs from the now-reversed save list for reg in reversed(saved_regs): absmc.ProcedureInstr('restore', reg) stmt.end_reg = recd_addr_reg elif isinstance(stmt, ast.ThisExpr): stmt.end_reg = absmc.Register('a', 0) elif isinstance(stmt, ast.MethodInvocationExpr): gen_code(stmt.base) cls = ast.lookup(ast.classtable, stmt.base.type.typename) for method in cls.methods: if stmt.mname == method.name: break saved_regs = [] arg_reg_index = 0 # first arg goes into a1 if desired method is not static if method.storage != 'static': arg_reg_index += 1 # add a0 if the current method is not static if current_method.storage != 'static': saved_regs.append(absmc.Register('a', 0)) # for each var in each block of the current method, add to save list for block in range(0, len(current_method.vars.vars)): for var in current_method.vars.vars[block].values(): saved_regs.append(var.reg) # save each reg in the saved list for reg in saved_regs: absmc.ProcedureInstr('save', reg) if method.storage != 'static': absmc.MoveInstr('move', absmc.Register('a', 0), stmt.base.end_reg) for arg in stmt.args: gen_code(arg) absmc.MoveInstr('move', absmc.Register('a', arg_reg_index), arg.end_reg) arg_reg_index += 1 absmc.ProcedureInstr('call', 'M_{}_{}'.format(method.name, method.id)) # Store the result in a temporary register stmt.end_reg = absmc.Register() absmc.MoveInstr('move', stmt.end_reg, absmc.Register('a', 0)) # restore regs from the reversed save list for reg in reversed(saved_regs): absmc.ProcedureInstr('restore', reg) elif isinstance(stmt, ast.UnaryExpr): gen_code(stmt.arg) ret = absmc.Register() if stmt.uop == 'uminus': zero_reg = absmc.Register() if stmt.arg.type == ast.Type('float'): prefix = 'f' else: prefix = 'i' # if uminus, put 0 - <reg> into the return reg absmc.MoveInstr('move_immed_{}'.format(prefix), zero_reg, 0, True) absmc.ArithInstr('sub', ret, zero_reg, stmt.arg.end_reg, prefix) else: # if it's a 0, branch to set 1 # if it's a 1, we're falling through, setting to 0, and jumping out set_one_label = absmc.BranchLabel(stmt.lines, 'SET_ONE') out_label = absmc.BranchLabel(stmt.lines, 'UNARY_OUT') absmc.BranchInstr('bz', set_one_label, stmt.arg.end_reg) absmc.MoveInstr('move_immed_i', ret, 0, True) absmc.BranchInstr('jmp', out_label) set_one_label.add_to_code() absmc.MoveInstr('move_immed_i', ret, 1, True) out_label.add_to_code() stmt.end_reg = ret elif isinstance(stmt, ast.SuperExpr): stmt.end_reg = absmc.Register('a', 0) elif isinstance(stmt, ast.ArrayAccessExpr): # Create fake register. stmt.end_reg = absmc.Register('n', 0) print 'Found an array access. Arrays are not supported.' elif isinstance(stmt, ast.NewArrayExpr): # Create fake register. stmt.end_reg = absmc.Register('n', 0) print 'Found an array creation. Arrays are not supported.' else: print 'need instance ' + str(type(stmt)) pop_labels()
dcf80887bbd12d029d545862ac0d188756aa7da3
WilbertHo/hackerrank
/challenges/algorithms/warmup/maximizing_xor/py/maximizingxor.py
1,537
4.0625
4
#!/usr/bin/env python import fileinput import math def maximize(l, r): """ Return the maximum value of A XOR B, where L <= A <= B <= R log2 of n is the number of times n has to be divided by 2 to be less than or equal to 1, so it can tell us where the most significant bit is. ex: int(log2(1)) == 0 meaning 2 ** 0 int(log2(10)) == 3 (1010) 2 ** 3 + 2 ** 1 int(log2(8)) == 3 (1000) 2 ** 3 Test case: 10, 15 -> 7 10: 1010, 15: 1111 10 ^ 15 == 5, or 1010 ^ 1111 == 0101 The most significant bit of 1010 and 1111 are both 1, so the range between 1010 to 1111 will have a max of 111. Test case: 1, 10 -> 15 1: 0001, 10: 1010 1 ^ 10 == 11, ie 0001 ^ 1010 == 1111 The log2 will give the position of the most significant bit of L ^ R. math.log(10 ^ 15, 2) == 2.3219... 10 ^ 15 == 5 (0101) or (2 ** 2, with the rest being 2 ** 0) Having the most significant bit, we can calculate the max by setting all bits smaller than the most significant to 1. We'll do that by finding the most significant bit's next larger and subtracting 1 from that. int(math.ceil(math.log(10 ^ 15, 2))) == 3 and 2 ** 3 == 8 8 - 1 == 7 (0111) """ return 2 ** int(math.ceil(math.log(l ^ r, 2))) - 1 def main(): input = [line.strip() for line in fileinput.input()] print maximize(*map(int, input)) if __name__ == '__main__': main()
cf91aac116f92f699121576242273a7baca84b18
lelilia/advent_of_code_2020
/day23.py
2,424
3.609375
4
def print_list(head): for _ in range(length): if not head: break print(head.value) head = head.next def print_result(head): while head.value != 1: head = head.next res = "" head = head.next while head.value != 1: res += str(head.value) head = head.next return res cups = list("219347865") length = len(cups) class LinkedList: def __init__(self, value): self.value = value self.next = None head = LinkedList(None) current = head while cups: next_cup = LinkedList(int(cups.pop(0))) current.next = next_cup current = current.next current.next = head.next # pick current current = head.next for _ in range(100): cutout1 = current.next cutout2 = cutout1.next cutout3 = cutout2.next current.next = cutout3.next next_value = current.value - 1 while next_value in [cutout1.value, cutout2.value, cutout3.value]: next_value -= 1 if next_value < 1: next_value = length searching = current.next while searching.value != next_value: if searching == current: next_value -= 1 if next_value == 0: next_value = length searching = searching.next temp = searching.next searching.next = cutout1 cutout3.next = temp current = current.next print(f'Part 1: {print_result(current)}') # Part 2 cups = list("219347865") cup_hash = {} head = LinkedList(None) current = head while cups: value = int(cups.pop(0)) next_cup = LinkedList(value) cup_hash[value] = next_cup current.next = next_cup current = current.next for value in range(10, 1_000_001): next_cup = LinkedList(value) cup_hash[value] = next_cup current.next = next_cup current = current.next current.next = head.next current = head.next for _ in range(10_000_000): cutout1 = current.next cutout2 = cutout1.next cutout3 = cutout2.next current.next = cutout3.next next_value = current.value - 1 while next_value in [cutout1.value, cutout2.value, cutout3.value]: next_value -= 1 if next_value < 1: next_value = 1_000_000 searching = cup_hash[next_value] temp = searching.next searching.next = cutout1 cutout3.next = temp current = current.next res2 = cup_hash[1].next.value * cup_hash[1].next.next.value print(f'Part 2: {res2}')
4fce804681a410b5a58f177ab3382e36476b21ab
stefroes/Programming
/5-control-structures/pe5_1.py
176
3.78125
4
score = int(input('Geef je score: ')) if score > 15: print('Gefeliciteerd!\nMet een score van {} ben je geslaagd!'.format(score)) else: print('Sorry, je bent gezakt')
29b1e05a36678df7b5484bd82bf7134a4e04a6c8
SteephanSteve/Python
/unique.py
329
3.53125
4
#!usr/bin/python n=int(raw_input("Enter the no. of elements :")) a=[] b=[] print "Enter the elements :" for i in xrange(n): x=int(input()) a.append(x) for i in xrange(n): for j in range(i+1,n): if a[i]==a[j]: a[i]=a[j]=0 for i in xrange(n): if not a[i]==0: print a[i]
5b32b0e4e32cb94ac457387f4b282bea1449e983
Cloud-cover/tf_aws_lambda_s3_trigger
/lambda.py
2,258
3.578125
4
"""" A sample implementation of a Lambda function that is expected to be invoked by creation of an *.csv file in a specific S3 bucket. The function compresses it and writes the compressed data into another file in the S3 bucket. The function usess SNAPPY compression https://github.com/google/snappy and https://github.com/andrix/python-snappy. The intent is to demonstrate how to build dependencies and the function into a zip file targeting the AWS Lambda runtime, and deploy it to AWS using Terraform. """ import json import urllib import csv import boto3 import zlib def lambda_handler(event, context): """ Lambda event handler. This function will be invoked by AWS when an object is created in the configured S3 bucket. Parameters ---------- See AWS Lambda documentation for meaning of these parameters. """ # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) # read the content, compress it and write it to another file s3_compress(bucket, key) def s3_compress(bucket, object): """ Sample function that retrieves content of a file in an S3 bucket, compresses it with the snappy compression algorithm, and saves it to another file in the same S3 bucket. Parameters ---------- bucket : str Name of the bucket where the file is located object : str Name of the file to be compressed """ s3 = boto3.resource('s3') fileobj = s3.Object(bucket, object).get()['Body'] archive = '' while True: buffer = fileobj.read(1024) if not buffer: break # TODO add chunking/framing in so that larger files can be compressed archive = archive + buffer archive = zlib.compress(archive) new_name = "%s.zlib" % object client = boto3.client('s3') client.put_object(Bucket=bucket, Key=new_name, ContentType='application/zlib', Body=archive) if __name__ == '__main__': # For local testing and development # It assumes that you have AWS key/secret configured locally s3_compress('my-lambda-test-123', 'mlb-stats.csv')
486de4df17abe8adb91a8bcfe34429523e20813f
lmorales17/cs61a
/trends/find_centroid.py
1,918
4.34375
4
def find_centroid(polygon): """Find the centroid of a polygon. http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon polygon -- A list of positions, in which the first and last are the same Returns: 3 numbers; centroid latitude, centroid longitude, and polygon area Hint: If a polygon has 0 area, return its first position as its centroid >>> p1, p2, p3 = make_position(1, 2), make_position(3, 4), make_position(5, 0) >>> triangle = [p1, p2, p3, p1] # First vertex is also the last vertex >>> find_centroid(triangle) (3.0, 2.0, 6.0) >>> find_centroid([p1, p3, p2, p1]) (3.0, 2.0, 6.0) >>> tuple(map(float, find_centroid([p1, p2, p1]))) # Forces result to be floats (1.0, 2.0, 0.0) """ total_a = 0 total_x = 0 total_y = 0 n = len(polygon) - 1 i = 0 j = 0 k = n area = 0 while k > 0: #calculates the area of the polygon x1 = polygon[k-1][0] y1 = polygon[k][1] x2 = polygon[k][0] y2 = polygon[k-1][1] summation = ((x1*y1)-(x2*y2)) total_a += summation k -= 1 area = (total_a/2) while i < n: #calculates x-coordinate of the centroid z1 = polygon[i][0] w1 = polygon[i+1][1] z2 = polygon[i+1][0] w2 = polygon[i][1] summation1 = (z1+z2)*(z1*w1-z2*w2) total_x += summation1 i += 1 while j < n: #calculates y-coordinate of the centroid v1 = polygon[j][0] n1 = polygon[j+1][1] v2 = polygon[j+1][0] n2 = polygon[j][1] summation2 = (n2+n1)*(v1*n1-v2*n2) total_y += summation2 j += 1 if area == 0: return (polygon[0][0], polygon[0][1], abs(area)) else: area_divider = (1/(6*area)) x_coordinate = total_x*area_divider y_coordinate = total_y*area_divider return (x_coordinate, y_coordinate, abs(area))
b664b6c6205e4f3841045c5b48ddd9f398dfb069
michail82/TestMikl
/MIklTest2_Week2_12_ Chess_board.py
469
3.671875
4
a1 = int( input() ) a2 = int( input() ) b1 = int( input() ) b2 = int( input() ) if (a1 + a2 + b1 + b2) % 2 == 0: print( 'YES' ) else: print( 'NO' ) # Заданы две клетки шахматной доски. # Если они покрашены в один цвет, # то выведите слово YES, а если в разные цвета – то NO. # Формат ввода # Вводятся 4 числа - координаты клеток.
cc85896c949b6bbf1e53492bf4b770fa2e81039a
weyyifoo/FunProjects
/Palindrome-N-Prime/palindrome-n-prime.py
1,096
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 10 10:29:26 2018 @author: Wey Yi """ # code checks to see if the number is a prime number def isPrime(s): s = int(s) d = 0 for n in range(3,s): if s % n == 0: # if there is a remainder from dividing s by the counter, n, then the code adds 1 to d d += 1 else: d += 0 if d == 0: # if d does not clock up any number at the end of the run, it is a prime number return True else: return False # code checks to see if the input is a palindrome: def isPalin(s): rev = s[::-1] if s == rev: return True else: return False s = str(input("Input number to test if Palindrome & Prime: ")) a = isPalin(s) k = isPrime(s) if a == 1 and k == 1: print("Yes. The input is both a Prime Number and a Palindrome") elif (a == 1) and (k == 0): print("The input is only a Palindrome. It is not a Prime") elif (a == 0) and (k == 1): print("The input is only a Prime. It is not a Palindrome") else: print("The input is neither a Prime nor Palindrome")
8aaefd99032365bb59eb8f5507436e6c8b76e9e0
xuliucun/first
/bg-python/base_part/test01_studentManage.py
2,029
4
4
#!/usr/bin/python def showInfo(): # 显示功能列表 print("学生管理系统V1.0") print("1:addInfo") print("2:delInfo") print("3:modifyInfo") print("4:searchInfo") print("5:displayInfo") print("0:quitInfo") def getInfo(): key = input("请选择序号:") return int(key) def addInfo(stuInfoListTemp): name = input("请输入姓名:") idlist = input("请输入ID:") age = input("请输入年龄:") stuInfo = {} stuInfo['name'] = name stuInfo['ID'] = idlist stuInfo['age'] = age stuInfoListTemp.append(stuInfo) def delInfo(stuInfoListTemp): delNum = int(input("请输入要删除的序号:")) del stuInfoListTemp[delNum] def modifyInfo(stuListTemp): modifyNum = int(input("请输入要修改的序号")) modifyname = input("请输入姓名") modifyid = input("请输入ID") modifyage = input("请输入年龄") stuListTemp[modifyNum]['name'] = modifyname stuListTemp[modifyNum]['ID'] = modifyid stuListTemp[modifyNum]['age'] = modifyage def searchInfo(stuListTemp): searchNum = int(input("请输入查找的序号")) print("id name age") print("%s %s %s" % ( stuListTemp[searchNum]['ID'], stuListTemp[searchNum]['name'], stuListTemp[searchNum]['age'])) def quitInfo(): print("退出系统") def displayInfo(students): print("*" * 20) print("接下来遍历所有学生信息") print("id name age") for temp in students: print("%s %s %s" % (temp['ID'], temp['name'], temp['age'])) print("*" * 20) stuInfoList = [] while True: showInfo() key = getInfo() if key == 0: quitInfo() break elif key == 1: addInfo(stuInfoList) elif key == 2: delInfo(stuInfoList) elif key == 3: modifyInfo(stuInfoList) elif key == 4: searchInfo(stuInfoList) elif key == 5: displayInfo(stuInfoList) else: print("错误,请重新输入")
879a265b8da26a7115f34dfec87bde64cfdb6fef
suddenlykevin/cs550library
/Example 1 - Hello World!/helloworld.py
6,742
4.125
4
""" Kivy Example 1: Hello World! Kevin Xie CS550 This example files gives a short introduction to programming Kivy widgets in Python. It uses a number of widgets from popups to sldiers to buttons to Codeinputs. However, it may seem messy! This is because Kivy works best when typed in kv, where widget trees and behavior are easier to follow and edit. Here's a short flow chart: Execute Code > Opens MyFirstButton > builds button and slider widgets in a horizontal Boxlayout (stack) 1. If button > bind behavior (popup) > on_press > opens popup > builds label (text), exit button, and codeinput in GridLayout and BoxLayout a. If exit button > dismiss popup > return to MyFirstButton 2. If slider > bind behavior (recolor) > when value changes > recolors window background color More comments can be found in the code. Sources (applies to all example files): Reference - https://kivy.org/doc/stable/ On my honor, I have neither given nor received unauthorized aid. Kevin Xie '19 """ # core framework and behavior import kivy from kivy.app import App # for creating and opening "App" window cluster of widgets from kivy.core.window import Window # for altering window color # enter your Kivy version to ensure compatibility kivy.require('1.10.1') # import ux elements (widgets -- most titles are self explanatory) from kivy.uix.button import Button from kivy.uix.codeinput import CodeInput # a text box formatted for code from kivy.uix.popup import Popup from pygments.lexers import CythonLexer # used to format the syntax of python text from kivy.uix.boxlayout import BoxLayout # formats the available space as "boxes" stacking either horizontally or vertically from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout # formats available space as a "grid" with rows and columns of widgets from kivy.uix.slider import Slider # content of the popup content = BoxLayout(orientation="vertical") # in vertical stack topbar = GridLayout(cols=2,size_hint=(1,0.2)) # create a grid layout (with 2 columns) topbar/menu bar for dismissing popup etc. btn2 = Button(text='Close Me!',size_hint_x=0.2) # dismiss button with custom text and spacing (size_hint is the fraction of the x axis the widget occupies) topbar.add_widget(Label(text="How does a button and slider work?")) # adds label (text) for title topbar.add_widget(btn2) # adds dismiss button (order matters in boxlayout and gridlayout -- typically left to right, top down) content.add_widget(topbar) # adds topbar to popup # code input widget to explain the code of slider and button content.add_widget(CodeInput(lexer=CythonLexer(),text="""# Button and Slider # # This simple button and slider was built entirely in Python using no Kv. # It uses a box layout to arrange the two separate widgets and just two of Kivy's # many offered widgets. # Take a look at the code. Does it seem tedious or hard to follow? # opens the core functionality of the Kivy framework import kivy # set this to the version of Kivy you are running to ensure compatibility kivy.require('1.10.1') # imports the ability to create "Apps" or groups of widgets to be executed from kivy.app import App # imports the abilities to create Buttons, Sliders, manipulate the window properties (color), and arrange widgets from kivy.uix.button import Button from kivy.uix.slider import Slider from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout # executes this popup # instance is input name (self.btn) def popup(instance): print("Popup opened!") # check the console! code.open() # opens this popup # recolors the background every time the slider is moved # instance2 is the value of the slider def recolor(instance,instance2): val = float(instance2)/100.0 # retrieves a fraction out of 1 (rgba values from 0-1) Window.clearcolor = (val,val,val,1) # sets window color # the "App" or group of widgets that can all be run in one window class MyFirstButton(App): # the widgets to build into the app def build(self): self.content=BoxLayout(orientation="horizontal") # sets the layout of the window -- in this case, box layout indicates that widgets are "stacked" based on the orientation self.slider = Slider(orientation='vertical', min=0, max=100, value = 0) # vertical slider from 0-100 with default 0 self.slider.bind(value=recolor) # binds the "recolor" function to every time the value of the slider changes self.btn = Button(text='Hello World! (this is a button)', font_size = 25) # new button with text property "Hello World!" and font size 25 self.btn.bind(on_press=popup) # sets button behavior (calls function "popup") self.content.add_widget(self.btn) # adds button to box layout (horizontal "stack") self.content.add_widget(self.slider) # adds slider to box layout return self.content # returns the arranged content of the app # if still in original file if __name__ == '__main__': MyFirstButton().run() # runs the "app" in a new window # Open the hellowworld.py file in Sublime to learn more about how this Popup was # created!""",size_hint=(1,0.8))) # size_hint dictates the fraction of the screen across (1) and from top to bottom (0.8) the code should occupy code = Popup(content=content, title="Popup!", auto_dismiss = False) # creates a popup with the aforemmentioned content btn2.bind(on_press=code.dismiss) # binds behavior that dismisses code on_press of dismiss button # function to open popup, first argument is always input name (btn in this case) def popup(instance): print("Popup opened!") # check your console! code.open() # opens popup # function to recolor the background, argument 2 is value of slider def recolor(instance,instance2): val = float(instance2)/100.0 # makes slider value a float between 0 and 1 Window.clearcolor = (val,val,val,1) # sets color in rgba from 0-1 # main cluster in the form of an "App" window that opens on run() class MyFirstButton(App): # sets widgets to build def build(self): self.content=BoxLayout(orientation="horizontal", padding=20) # widgets arranged horizontally, padded with 20% for each widget for visual reasons self.slider = Slider(orientation='vertical', min=0, max=100, value = 0) # vertical slider from 0-100 with default 0 self.btn = Button(text='Hello World! (click me!)',font_size = 25) # button with text and font size 25 self.btn.bind(on_release=popup) # binds popup summoning behavior to button # adds widgets to the arrangement of self.content self.content.add_widget(self.btn) self.content.add_widget(self.slider) self.slider.bind(value=recolor) # binds recoloring behavior to slider return self.content # returns the arranged content to the App if __name__ == '__main__': MyFirstButton().run() # runs widget in an "app" window!
e887e3183209d538db3950888ffee56b20c3ee7f
DipuKP2001/python_for_ds_coursera
/7.1.py
137
4.0625
4
# Use words.txt as the file name fname = input("Enter file name: ") fh = open(fname) for i in fh: i = i.strip().upper() print (i)
8e3a51e563811504a85a113ad5b8bf5b15075c0c
jayjacobs/csmatrix
/ch2/The_Vector-firstpass.py
2,213
3.609375
4
# version code 0d1e4db3d840 # Please fill out this stencil and submit using the provided submission script. from GF2 import one def add2(v, w): return [v[0]+w[0], v[1]+w[1]] def minus2(v, w): return [v[0]-w[0], v[1]-w[1]] def scalar_vector_mult(alpha, v): return [ alpha*v[i] for i in range(len(v)) ] def list_dot(u, v): return sum([a*b for (a,b) in zip(u,v)]) ## 1: (Problem 2.14.1) Vector Addition Practice 1 #Please express each answer as a list of numbers p1_v = [-1, 3] p1_u = [0, 4] p1_v_plus_u = add2(p1_v, p1_u) p1_v_minus_u = minus2(p1_v, p1_u) p1_three_v_minus_two_u = minus2(scalar_vector_mult(3, p1_v), scalar_vector_mult(3, p1_u)) def add(v,w): return [ a+b for (a,b) in zip(v,w) ] def minus(v,w): return [ a-b for (a,b) in zip(v,w) ] ## 2: (Problem 2.14.2) Vector Addition Practice 2 p2_u = [-1, 1, 1] p2_v = [ 2, -1, 5] p2_v_plus_u = add(p2_v, p2_u) p2_v_minus_u = minus(p2_v, p2_u) p2_two_v_minus_u = minus(scalar_vector_mult(2, p2_v), p2_u) p2_v_plus_two_u = add(p2_v, scalar_vector_mult(2, p2_u)) ## 3: (Problem 2.14.3) Vector Addition Practice 3 # Write your answer using GF2's one instead of the number 1 p3v = [0, one, one] p3u = [one, one, one] p3_vector_sum_1 = add(p3v, p3u) p3_vector_sum_2 = add(p3v, add(p3u,p3u)) ## 4: (Problem 2.14.4) GF2 Vector Addition A # Please express your solution as a subset of the letters {'a','b','c','d','e','f'}. # For example, {'a','b','c'} is the subset consisting of: # a (1100000), b (0110000), and c (0011000). # The answer should be an empty set, written set(), if the given vector u cannot # be written as the sum of any subset of the vectors a, b, c, d, e, and f. u_0010010 = ... u_0100010 = ... ## 5: (Problem 2.14.5) GF2 Vector Addition B # Use the same format as the previous problem v_0010010 = ... v_0100010 = ... ## 6: (Problem 2.14.6) Solving Linear Equations over GF(2) #You should be able to solve this without using a computer. x_gf2 = [...] ## 7: (Problem 2.14.7) Formulating Equations using Dot-Product #Please provide each answer as a list of numbers v1 = [...] v2 = [...] v3 = [...] ## 8: (Problem 2.14.9) Practice with Dot-Product uv_a = ... uv_b = ... uv_c = ... uv_d = ...
c8a3a22cc9cb74be75e4477082cf56778d5cc80e
deyukong/pycharm-practice
/practice/list_methods.py
261
3.625
4
a = [1,9,2,10,3,4,4,3,3,3,3,6] b = [100, 101, 102] a.append(100) print(a) a.extend(b) print(a) a.insert(1, 99) print(a) a.remove(100) print(a) a.pop(0) print(a) print(a.count(3)) a.sort(reverse = True) print(a) c = a.copy() print(c) a.clear() print(a)
7a60d9b24e531499d4555936eacd65b836f35aa7
balloonio/algorithms
/leetcode/problems/621_task_scheduler.py
3,608
3.5
4
# 1. Using sorting class Solution: def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ if not tasks: return 0 if not n: return len(tasks) task2freq = collections.defaultdict(int) for task in tasks: task2freq[task] += 1 ordered_tasks = [] for task, freq in task2freq.items(): ordered_tasks.append((-freq, freq, task)) ordered_tasks.sort() task2cool = {} workq = [] while ordered_tasks or task2cool: # pick a task from doable tasks, if no then idel if not ordered_tasks: workq.append("idle") task_done = None else: _, freq, task = ordered_tasks[0] ordered_tasks.pop(0) workq.append(task) task2freq[task] -= 1 # move to cool down task_done = task if task2freq[task] > 0: task2cool[task] = n # check if cooldown finished for task, cool in list(task2cool.items()): if task == task_done: continue task2cool[task] -= 1 if task2cool[task] == 0: task2cool.pop(task) ordered_tasks.append((-task2freq[task], task2freq[task], task)) ordered_tasks.sort() return len(workq) # 2. Using heapq class Solution: # noqa: F811 def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ if not tasks: return 0 if not n: return len(tasks) task2freq = collections.defaultdict(int) for task in tasks: task2freq[task] += 1 freq_heapq = [] for task, freq in task2freq.items(): freq_heapq.append((-freq, freq, task)) heapq.heapify(freq_heapq) task2cool = {} workq = [] while freq_heapq or task2cool: # pick a task from doable tasks, if no then idel if not freq_heapq: workq.append("idle") task_done = None else: _, freq, task = heapq.heappop(freq_heapq) workq.append(task) task2freq[task] -= 1 # move to cool down task_done = task if task2freq[task] > 0: task2cool[task] = n # check if cooldown finished for task, cool in list(task2cool.items()): if task == task_done: continue task2cool[task] -= 1 if task2cool[task] == 0: task2cool.pop(task) heapq.heappush( freq_heapq, (-task2freq[task], task2freq[task], task) ) return len(workq) # 3. (There are faster and more concise solutions which doesn't construct workq) # I'm not bother to write it here, but those should be around the same time complexity """ It is important to realize the key to this question: to optimize the time, we need to assign slots for all occurance for task with highest frequency first, and then in between the idle, assign other lower priority tasks L42 L43 When decrementing cool down cycles, make sure you are not decrementing cooldown for the task that we just completed in the current cycle """
0e9871d7e0a74b069152a790ff4a0c38a1005926
kartik0001/Day7
/Modules/Q5.py
117
3.953125
4
# Q5. from datetime import date x=date(2021,12,24) print("Date is: ",x.day) ''' Output: Date is: 24 '''
cc81033abc8a9b65e417cb532e678e6effb8acc4
gschen/where2go-python-test
/1906101001周茂林/2020寒假/力扣171/1.py
698
3.84375
4
''' 「无零整数」是十进制表示中 不含任何 0 的正整数。 给你一个整数 n,请你返回一个 由两个整数组成的列表 [A, B],满足: A 和 B 都是无零整数 A + B = n 题目数据保证至少有一个有效的解决方案。 如果存在多个有效解决方案,你可以返回其中任意一个。 示例 1: 输入:n = 2 输出:[1,1] 解释:A = 1, B = 1. A + B = n 并且 A 和 B 的十进制表示形式都不包含任何 0 。 示例 2: 输入:n = 11 输出:[2,9] ''' def getNoZeroIntegers(n): for i in range(1, n): if '0' not in str(i) and '0' not in str(n-i): return [i, n-i] n = 1010 print(getNoZeroIntegers(n))
4554a516ff48f666f950e895e46967388d9d0090
nidhiatwork/Python_Coding_Practice
/30DayLeetcodeChallenge_April/Week2/11_diameterOfBinaryTree.py
1,203
4.21875
4
''' Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. ''' import sys class TreeNode(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def depth(self, node, ans): if not node: return 0 L = self.depth(node.left, ans) R = self.depth(node.right, ans) ans[0] = max(ans[0], L+R) print("Node: ",node.val, " L: ", L, " R: ",R," return: ",1 + max(L, R)," ans: ", ans[0]) return 1 + max(L, R) def diameterOfBinaryTree(self, root): ans = [0] self.depth(root, ans) return ans[0] s = Solution() root = TreeNode(1,TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(5, TreeNode(6, TreeNode(8, TreeNode(11, TreeNode(15), TreeNode(16)), TreeNode(12)), TreeNode(9, TreeNode(13))), TreeNode(7, TreeNode(14, TreeNode(17), TreeNode(18)), TreeNode(10, TreeNode(19), TreeNode(20, TreeNode(21)))))) print(s.diameterOfBinaryTree(root))
67990a9cebe259010e180fe74a6149ae651328ef
Treelovah/Colorado-State-University
/Python-164/chapter.5/lab5.33/TextMsgAbbreviation.py
778
3.78125
4
''' /* (1) If a user's input string matches a known text message abbreviation, output the unabbreviated form, else output: Unknown. Support two abbreviations: LOL -- laughing out loud, and IDK -- I don't know. (4 pts) Sample input/output: Input an abbreviation: LOL laughing out loud (2) Expand to also decode these abbreviations. (3 pts) BFF -- best friends forever IMHO -- in my humble opinion TMI -- too much information */ ''' # a hacked version of a python switch statement ^_^ def abbrev(i): switcher = { "LOL":"Laughing out loud", "IDK":"I don't know", "BFF":"best friends forever", "IMHO":"in my humble opinion", "TMI":"too much information" } return switcher.get(i,"Unkown") print(abbrev(input()))
c665b465f0e22ae1d5a2e66a31e32a99b8dc54fd
shreyajarsania/python_training
/git_ass_py_2/question9.py
609
4.1875
4
################################################################################################## # # Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 # it will return 20. # ################################################################################################## # take input from user num1 = input("Enter 1st number") num2 = input("Enter 2nd number") # convert string to float num1 = float(num1) num2 = float(num2) # sum sum_num = num1 + num2 # check if sum is between 15 to 20 if 15 <= sum_num <= 20: print('20') else: print(sum_num)
541093f02de52d797169a02ceaec446a12f89eb9
ResearchInMotion/CloudForce-Python-
/Scrutiny/Dictionary/DictionaryIteration.py
287
3.859375
4
phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781} for name, number in phonebook.items(): print("Phone number of %s is %d" % (name, number)) check = {"sahil":8,"Nikki":9,"Vmal":9} for name,number in check.items(): print("Age of %s is %d"%(name,number))
76f6ac8c9d551eeb40b78e9d15db3f6c5e2fce77
Nathanael-L/pw-calc
/pw.py
1,637
3.640625
4
#!/usr/bin/python import string from random import randint import sys def main(length, passes, mode): pw = [] sz = ['!','$','%','&','?','@','>','<'] for p in range(passes): for i in range(length): r4 = randint(0, mode) if r4 == 0: pw.append(randint(0, 9)) elif r4 == 1: pw.append(string.lowercase[randint(0, 25)]) elif r4 == 2: pw.append(string.uppercase[randint(0, 25)]) elif r4 == 3: pw.append(sz[randint(0, 7)]) for letter in pw: if type(letter) == int: sys.stdout.write(str(letter)) else: sys.stdout.write(letter) sys.stdout.write('\n') pw = [] uniqueness = 10; if mode == 1: uniqueness += 26 elif mode == 2: uniqueness += 52 elif mode == 3: uniqueness += 60 print "Guesability: " + str(uniqueness**length) def usage(): print "password generator:" print "usage: pw.py <number of characters> <number of passes> [<mode>]" print "mode 0: only numbers" print " 1: numbers and lowercase letters" print " 2: numbers and letters" print " 3: numbers, letters and special characters (default)" exit(1) if __name__ == '__main__': for i in range(len(sys.argv)-1): try: int(sys.argv[i+1]) except: print sys.argv[i+1] print type(sys.argv[i+1]) usage() if len(sys.argv) == 3: main(int(sys.argv[1]), int(sys.argv[2]), 3) elif len(sys.argv) == 4 and int(sys.argv[3]) >= 0 and int(sys.argv[3]) <= 3: main(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])) else: usage()
935a2691af5bd1b38bd995201dafe97b09e436e9
ravipapisetti954/pythonkids-beginners
/examples/02-turtle/03-colors/TiltedMultiColoredSquareSpiralWithBgColor.py
389
3.921875
4
# Drawing square # Try changing the range value # Try changing the degrees import turtle t = turtle.Pen() # Visit http://www.tcl.tk/man/tcl8.6/TkCmd/colors.htm for all the supported 03-colors colors = ["red", "green", "blue", "orange"] turtle.bgcolor("black") for x in range(100): t.pencolor(colors[x%4]) t.forward(x) t.left(92) # Excercise - do the same for circle spirals
e26e48b36268550b14f91def4aa32e0a5f2400fe
lmacionis/Exercises
/6. Fruitful_functions/Exercise_7.py
1,056
3.859375
4
""" Write a function to_secs that converts hours, minutes and seconds to a total number of seconds. Here are some tests that should pass: test(to_secs(2, 30, 10) == 9010) test(to_secs(2, 0, 0) == 7200) test(to_secs(0, 2, 0) == 120) test(to_secs(0, 0, 42) == 42) test(to_secs(0, -10, 10) == -590) """ import sys def to_secs(h, m, s): time_in_seconds = h * 3600 + m * 60 + s return time_in_seconds def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def test_suite(): """ Run the suite of tests for code in this module (this file). """ test(to_secs(2, 30, 10) == 9010) test(to_secs(2, 0, 0) == 7200) test(to_secs(0, 2, 0) == 120) test(to_secs(0, 0, 42) == 42) test(to_secs(0, -10, 10) == -590) test_suite() # Here is the call to run the tests print(to_secs(0, 0, 5))
27b7bdedcced86dc1ef16abd4e592a3de52372dc
balajisaikumar2000/python_modules
/OOPS'S IN PYTHON/Property Decorators.py
1,809
4.0625
4
""" when we did this ,it works fine but we have to print like this print(emp_1.email()) but we want email as variable(variable is called "property" in javascript def email(self): return '{} {}@email.com'.format(self.first,self.last) """ class Employee: def __init__(self,first,last): self.first = first self.last = last #we can solve above problem by addingn @property to above the def @property def email(self): return '{} {}@email.com'.format(self.first, self.last) @property def fullname(self): #we can change the fullname to a attribute by adding @property,so we do not have to metionn like this--print(emp_1.fullname()),,,,,,we have to mention like this print(emp_1.fullname) return "{} {}".format(self.first,self.last) @fullname.setter #if we want to alter the function,we have to setter def fullname(self,name): first,last = name.split(' ') self.first = first self.last = last @fullname.deleter #if we want to delete property we have to follow like this def fullname(self): print("Deleted....!") self.first = None self.last = None emp_1 = Employee("Balaji","Sai Kumar") emp_1.first = "Shyam" emp_1.fullname = "swathi munagpati" #we will get error when we do this(AttributeError: can't set attribute) to solve this we have to set @fullname.setter print(emp_1.first) print(emp_1.email) #here on output first property changed ,but email didn't changed ,so we will make some minor changes in the code print(emp_1.fullname) del emp_1.fullname #here fullname will only deleted because we set the deleter to only fullname
36692a4cb3db6f41db9ac7db4547a95a65f3fbc7
techkids-c4e/c4e5
/Nhat Linh/btvn 26.6/Assignment 3/3+4.py
600
4.1875
4
from turtle import* x=int(input('location 1')) y=int(input('location 2')) length=int(input('length')) def draw_star(x,y,length): penup() setposition(x,y) pendown() for x in range(5): forward(length) right(144) draw_star(x,y,length) speed(0) color('blue') for i in range(100): import random x = random.randint(-300, 300) y = random.randint(-300, 300) length = random.randint(3, 10) draw_star(x, y, length) #random.randint(a, b):Return a random integer N such that a <= N <= b. #how to use it: import the random module and use random functions needed.
f36a31066fcb2f99d8d4ad08722b2342bfcc20e4
Neha-bora/Python
/argu_parameter.py
1,688
3.75
4
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> def about(name,age,likes): sentence = "meet{}!they are{}years old and they like {}".format(name,age,likes) return sentence >>> about("neha",22,"hangout") 'meetneha!they are22years old and they like hangout' >>> >>> >>> aboout(age=23,name="jack",likes="python") Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> aboout(age=23,name="jack",likes="python") NameError: name 'aboout' is not defined >>> about(age=23,name="jack",likes="python") 'meetjack!they are23years old and they like python' >>> >>> >>> about("neha",22) Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> about("neha",22) TypeError: about() missing 1 required positional argument: 'likes' >>> >>> >>> def about(name,age,likes): sentence = "meet {}!They are {}years old and they like {}".format(name,age,likes) return sentence >>> >>> def about(name,age,likes= "java"): sentence = "meet{}!they are{}years old and they like {}".format(name,age,likes) return sentence >>> >>> about(anju,22) Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> about(anju,22) NameError: name 'anju' is not defined >>> about("anju",23) 'meetanju!they are23years old and they like java' >>> about("ashu",18,"nothing") 'meetashu!they are18years old and they like nothing' >>> >>> >>> about() Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> about() TypeError: about() missing 2 required positional arguments: 'name' and 'age' >>>
abef0d17164eaf292ce45ff9a8bee32b62404907
yanbinkang/problem-bank
/ik_problems/linked_lists_stacks_queues/pair_wise_swap.py
1,029
4.0625
4
""" solution: http://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list-by-changing-links/ initial: 1->2->3->4->5->6->7->None result: 2->1->4->3->6->5->7->None # 1 -> 2 -> 3 -> 4 => 2 -> 1 -> 4 -> 3 """ from sll import * def pair_wise_swap(head): if head == None or head.next == None: return head prev = head current = head.next head = current while True: next_node = current.next current.next = prev if next_node == None or next_node.next == None: prev.next = next_node break prev.next = next_node.next prev = next_node current = prev.next return head if __name__ == '__main__': a = Node(1) b = Node(2) c = Node(3) d = Node(4) e = Node(5) f = Node(6) g = Node(7) a.next = b b.next = c c.next = d d.next = e e.next = f f.next = g res = pair_wise_swap(a) while res != None: print str(res.data) + "\n" res = res.next
5f2f8f3b9df8f70f5db6690d26e981709a4cf3a6
distractedpen/datastructures
/queue.py
1,454
4.15625
4
#queue implementation class Queue(): def __init__(self, MAXSIZE): self.q = [0] * MAXSIZE self.MAXSIZE = MAXSIZE self.front = 0 self.rear = -1 self.itemCount = 0 def peek(self): return self.q[self.front] def isFull(self): return self.itemCount == self.MAXSIZE def isEmpty(self): return self.itemCount == 0 def enqueue(self, data): if self.isFull(): return 0 else: if self.rear == (self.MAXSIZE - 1): self.rear = -1 self.rear += 1 self.q[self.rear] = data self.itemCount += 1 def dequeue(self): if self.isEmpty(): return "Error" else: if self.front == self.MAXSIZE: self.front = 0 data = self.q[self.front] self.front += 1 self.itemCount -= 1 return data def debug(self): print("Front: {0}".format(self.front)) print("Rear: {0}".format(self.rear)) print("Queue: {0}".format(self.q)) def main(): q = Queue(5) q.enqueue(3) q.enqueue(4) q.enqueue(5) while(not q.isEmpty()): print(q.dequeue(), end=" ") print("\n") i = 10 while(not q.isFull()): q.enqueue(i) i += 1 while(not q.isEmpty()): print(q.dequeue(), end=" ") if __name__ == "__main__": main()
6bf3d331f60bcc04da9739e3cbbfaface350503c
kaushalaneesha/Coding-Practice
/PythonPractice/src/interview_questions/pharm_easy/insert_elem_middle.py
1,681
4.09375
4
""" Insert element at the middle of a circular linked list """ class Node: """ Node of a linked list """ def __init__(self, val: int): self.val = val self.prev = None self.next = None class CircularLinkedList: def __init__(self, h: Node): self.head = h self.last = h if h: self.head.next = h self.last.next = h def append(self, elem): new_node = Node(elem) new_node.next = self.head self.last.next = new_node self.last = new_node def insert_elem_at_middle(self, elem): if not self.head: self.head = Node(elem) self.head.next = self.head return fast = self.head slow = self.head while fast.next != self.head and fast.next.next != self.head: print(slow.val) slow = slow.next fast = fast.next.next # Add new node new_node = Node(elem) new_node.next = slow.next slow.next = new_node if new_node.next == head: # update the last pointer as well self.last = new_node def print(self): if not self.head: return print(self.head.val) h = self.head.next while h != self.head: print(h.val) h = h.next # Test case head = Node(10) l = CircularLinkedList(head) l.append(2) l.append(3) l.append(4) l.print() l.insert_elem_at_middle(6) l.print() l.insert_elem_at_middle(18) l.print() l.insert_elem_at_middle(20) l.print() head = None l = CircularLinkedList(head) l.print() l.insert_elem_at_middle(6) l.print()
a96e3cd4d0a42850413cf4c3540da72f87b5fbfa
rafaelperazzo/cc0003
/codigo/calculadora.py
1,009
4.375
4
''' Escrever uma função que represente uma máquina de calcular, com as opções das operações fundamentais, fatorial, potência e raiz quadrada. ''' def fatorial(n): fat = 1 for i in range(1,n+1,1): fat = fat * i return (fat) def calculadora(operacao,a,b): if (operacao=='+'): return(a+b) elif (operacao=='-'): return(a-b) elif (operacao=='*'): return(a*b) elif (operacao=='/'): return(a/b) elif (operacao=='r'): return(a**(0.5)) elif (operacao=='p'): return(a**b) else: return(fatorial(a)) #PROGRAMA PRINCIPAL #ENTRADA: operação e os números while (True): operacao = input('Digite a operacao (r)aiz, (p)otencia (f)atorial (+,-,*,/) fundamental (s)air: ') if (operacao=='s'): break else: a = float(input('Digite o primeiro numero: ')) b = float(input('Digite o segundo numero (0) se nao houver: ')) print(calculadora(operacao,a,b))
69d251e73e0443cc61908081f589ac5de4ec0dfd
summershaaa/Data_Structures-and-Algorithms
/剑指Offer/剑指24_反转链表.py
798
3.625
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 20 16:57:45 2019 @author: WinJX """ #剑指offer-24 : 反转链表 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): #三指针交换 pReversedHead = None pNode = pHead pPrev = None while pNode: pNext = pNode.next if not pNext: pReversedHead = pNode pNode.next = pPrev pPrev = pNode pNode = pNext return pReversedHead n1 = ListNode(1) tmp = n1 for i in range(2,7): tmp.next = ListNode(i) tmp = tmp.next rst = Solution() print(rst.ReverseList(n1))
96a584c4e016e7f73e9d0e023b74a5be59f147ac
sungwooman91/python_code
/01.jump_to_python/chapter5/5_5 내장함수/234_abs.py
168
3.921875
4
print(abs(-3)) print(abs(3)) int_list=[1,2,3,4,5] for i, name in enumerate(['body','foo','bar']): print(i,name) print(list(filter(lambda x:x>0,[1,-3,2,0,-5,6])))
27211fb2171c086a1e4fce8ac5d583aae209c2bf
claudio-unipv/pvml
/pvml/normalization.py
6,414
3.59375
4
import numpy as np def meanvar_normalization(X, *Xtest): """Normalize features using moments. Linearly normalize each input feature to make it have zero mean and unit variance. Test features, when given, are scaled using the statistics computed on X. Parameters ---------- X : ndarray, shape (m, n) input features (one row per feature vector). Xtest : ndarray, shape (mtest, n) or None zero or more arrays of test features (one row per feature vector). Returns ------- ndarray, shape (m, n) normalized features. ndarray, shape (mtest, n) normalized test features (one for each array in Xtest). """ X = np.asarray(X) Xtest = [np.asarray(XX) for XX in Xtest] _check_all_same_size(X, *Xtest) mu = X.mean(0) sigma = X.std(0) X = X - mu X /= np.maximum(sigma, 1e-15) # 1e-15 avoids division by zero if not Xtest: return X Xtest = tuple((Xt - mu) / np.maximum(sigma, 1e-15) for Xt in Xtest) return (X,) + Xtest def minmax_normalization(X, *Xtest): """Scale features in the [0, 1] range. Linearly normalize each input feature in the [0, 1] range. Test features, when given, are scaled using the statistics computed on X. Parameters ---------- X : ndarray, shape (m, n) input features (one row per feature vector). Xtest : ndarray, shape (mtest, n) or None zero or more arrays of test features (one row per feature vector). Returns ------- ndarray, shape (m, n) normalized features. ndarray, shape (mtest, n) normalized test features (one for each array in Xtest). """ X = np.asarray(X) Xtest = [np.asarray(XX) for XX in Xtest] _check_all_same_size(X, *Xtest) xmin = X.min(0) xmax = X.max(0) X = X - xmin X = X / np.maximum(xmax - xmin, 1e-15) # 1e-15 avoids division by zero if not Xtest: return X Xtest = tuple((Xt - xmin) / np.maximum(xmax - xmin, 1e-15) for Xt in Xtest) return (X,) + Xtest def maxabs_normalization(X, *Xtest): """Scale features in the [-1, 1] range. Linearly normalize each input feature in the [-1, 1] range by dividing them by the maximum absolute value. Test features, when given, are scaled using the statistics computed on X. Parameters ---------- X : ndarray, shape (m, n) input features (one row per feature vector). Xtest : ndarray, shape (mtest, n) or None zero or more arrays of test features (one row per feature vector). Returns ------- ndarray, shape (m, n) normalized features. ndarray, shape (mtest, n) normalized test features (one for each array in Xtest). """ X = np.asarray(X) Xtest = [np.asarray(XX) for XX in Xtest] _check_all_same_size(X, *Xtest) # 1e-15 avoids division by zero amax = np.maximum(np.abs(X).max(0), 1e-15) X = X / amax if not Xtest: return X Xtest = tuple(Xt / amax for Xt in Xtest) return (X,) + Xtest def l2_normalization(X, *Xtest): """L2 normalization of feature vectors. Scale feature vectors to make it have unit Euclidean norm. Test features, when given, are scaled as well. Parameters ---------- X : ndarray, shape (m, n) input features (one row per feature vector). Xtest : ndarray, shape (mtest, n) or None zero or more arrays of test features (one row per feature vector). Returns ------- ndarray, shape (m, n) normalized features. ndarray, shape (mtest, n) normalized test features (one for each array in Xtest). """ X = np.asarray(X) Xtest = [np.asarray(XX) for XX in Xtest] _check_all_same_size(X, *Xtest) q = np.sqrt((X ** 2).sum(1, keepdims=True)) X = X / np.maximum(q, 1e-15) # 1e-15 avoids division by zero if not Xtest: return X Xtest = tuple(l2_normalization(Xt) for Xt in Xtest) return (X,) + Xtest def l1_normalization(X, *Xtest): """L1 normalization of feature vectors. Scale feature vectors to make it have unit L1 norm. Test features, when given, are scaled as well. Parameters ---------- X : ndarray, shape (m, n) input features (one row per feature vector). Xtest : ndarray, shape (mtest, n) or None zero or more arrays of test features (one row per feature vector). Returns ------- ndarray, shape (m, n) normalized features. ndarray, shape (mtest, n) normalized test features (one for each array in Xtest). """ X = np.asarray(X) Xtest = [np.asarray(XX) for XX in Xtest] _check_all_same_size(X, *Xtest) q = np.abs(X).sum(1, keepdims=True) X = X / np.maximum(q, 1e-15) # 1e-15 avoids division by zero if not Xtest: return X Xtest = tuple(l1_normalization(Xt) for Xt in Xtest) return (X,) + Xtest def whitening(X, *Xtest): """Whitening transform. Linearly transform features to make it have zero mean, unit variance and null covariance. Test features, when given, are trandformed using the statistics computed on X. Parameters ---------- X : ndarray, shape (m, n) input features (one row per feature vector). Xtest : ndarray, shape (mtest, n) or None zero or more arrays of test features (one row per feature vector). Returns ------- ndarray, shape (m, n) normalized features. ndarray, shape (mtest, n) normalized test features (one for each array in Xtest). """ X = np.asarray(X) Xtest = [np.asarray(XX) for XX in Xtest] _check_all_same_size(X, *Xtest) mu = X.mean(0) sigma = np.cov(X.T) evals, evecs = np.linalg.eigh(sigma) w = (np.maximum(evals, 1e-15) ** -0.5) * evecs # 1e-15 avoids div. by zero X = (X - mu) @ w if not Xtest: return X Xtest = tuple((Xt - mu) @ w for Xt in Xtest) return (X,) + Xtest def _check_all_same_size(*X): for x in X: if x.ndim != 2: msg = "Features must form a bidimensional array ({} dimension(s) found)" raise ValueError(msg.format(x.ndim)) for x in X[1:]: if x.shape[1] != X[0].shape[1]: msg = "The number of features does not match ({} and {})" raise ValueError(msg.format(X[0].shape[1], x.shape[1]))
c127abb838950cef5942239a4a52504277db7f0d
sneezydwarf2107/Python
/SiebDesEratosthenes/set_up_and_calculation.py
528
3.5
4
def get_List(grenze): my_list = list(range(2, grenze+1)) return(my_list) def calculation(my_list, grenze): for x in range(0, len(my_list)): if x >= len(my_list): break if my_list[x] != 0: term = my_list[x] for y in range(x+1, len(my_list)): if y >= len(my_list): break if (my_list[y] % term) == 0: my_list.pop(y) return(my_list)
89f12ea1a42558a73b536857984ebf39f452b902
SebastianAthul/pythonprog
/DATACOLLECTIONS/list/present_notpresent.py
222
3.765625
4
a=[1,2,3,4,5,6,8,9,10,22] def present(a): user=int(input("enter the element tocheck: ")) for i in a: if i == user: print("present") break else: print("not present") present(a)
ab2712e51dc9c0bf8860050792a3799a6b88d278
senku-kz/cv-pa2
/Canny.py
9,056
3.8125
4
# credit: Juan Carlos Niebles and Ranjay Krishna import numpy as np def conv(image, kernel): """ An implementation of convolution filter. This function uses element-wise multiplication and np.sum() to efficiently compute weighted sum of neighborhood at each pixel. Args: image: numpy array of shape (Hi, Wi) kernel: numpy array of shape (Hk, Wk) Returns: out: numpy array of shape (Hi, Wi) """ Hi, Wi = image.shape Hk, Wk = kernel.shape out = np.zeros((Hi, Wi)) # For this assignment, we will use edge values to pad the images. # Zero padding as used in the previous assignment can make # derivatives at the image boundary very big. pad_width0 = Hk // 2 pad_width1 = Wk // 2 pad_width = ((pad_width0, pad_width0), (pad_width1, pad_width1)) padded = np.pad(image, pad_width, mode='edge') ##################################### # START YOUR CODE HERE # ##################################### kernel = np.fliplr(np.flipud(kernel)) for i in range(Hi): for j in range(Wi): out[i, j] = np.sum(padded[i:i + Hk, j:j + Wk] * kernel) ###################################### # END OF YOUR CODE # ###################################### return out def gaussian_kernel(size, sigma): """ Implementation of Gaussian Kernel. This function follows the gaussian kernel formula, and creates a kernel matrix. Hints: - Use np.pi and np.exp to compute pi and exp Args: size: int of the size of output matrix sigma: float of sigma to calculate kernel Returns: kernel: numpy array of shape (size, size) """ kernel = np.zeros((size, size)) ##################################### # START YOUR CODE HERE # ##################################### k = (size - 1) / 2 for i in range(size): for j in range(size): kernel[i, j] = (1.0 / (2.0 * np.pi * sigma ** 2)) * \ np.exp(-((i - k) ** 2 + (j - k) ** 2) / (2.0 * sigma ** 2)) ###################################### # END OF YOUR CODE # ###################################### return kernel def partial_x(img): """ Computes partial x-derivative of input img. Hints: - You may use the conv function which is defined in this file. Args: img: numpy array of shape (H, W) Returns: out: x-derivative image """ out = None ##################################### # START YOUR CODE HERE # ##################################### d_x = np.array([[0.5, 0.0, -0.5]]) out = conv(img, d_x) ###################################### # END OF YOUR CODE # ###################################### return out def partial_y(img): """ Computes partial y-derivative of input img. Hints: - You may use the conv function which is defined in this file. Args: img: numpy array of shape (H, W) Returns: out: y-derivative image """ out = None ##################################### # START YOUR CODE HERE # ##################################### d_y = np.array([[0.5], [0.0], [-0.5]]) out = conv(img, d_y) ###################################### # END OF YOUR CODE # ###################################### return out def gradient(img): """ Returns gradient magnitude and direction of input img. Args: img: Grayscale image. Numpy array of shape (H, W) Returns: G: Magnitude of gradient at each pixel in img. Numpy array of shape (H, W) theta: Direction(in degrees, 0 <= theta < 360) of gradient at each pixel in img. Numpy array of shape (H, W) """ G = np.zeros(img.shape) theta = np.zeros(img.shape) ##################################### # START YOUR CODE HERE # ##################################### g_x = partial_x(img) g_y = partial_y(img) G = np.sqrt(g_x ** 2 + g_y ** 2) theta = np.arctan2(g_y, g_x) theta = (np.rad2deg(theta) + 180) % 360 ###################################### # END OF YOUR CODE # ###################################### return G, theta def non_maximum_suppression(G, theta): """ Performs non-maximum suppression This function performs non-maximum suppression along the direction of gradient (theta) on the gradient magnitude image (G). Args: G: gradient magnitude image with shape of (H, W) theta: direction of gradients with shape of (H, W) Returns: out: non-maxima suppressed image """ H, W = G.shape out = np.zeros((H, W)) # Round the gradient direction to the nearest 45 degrees theta = np.floor((theta + 22.5) / 45) * 45 ##################################### # START YOUR CODE HERE # ##################################### theta = theta % 360 for i in range(1, H - 1): for j in range(1, W - 1): current_angle = theta[i, j] if current_angle == 0 or current_angle == 180: neighbors = [G[i, j - 1], G[i, j + 1]] elif current_angle == 45 or current_angle == 225: neighbors = [G[i - 1, j - 1], G[i + 1, j + 1]] elif current_angle == 90 or current_angle == 270: neighbors = [G[i - 1, j], G[i + 1, j]] elif current_angle == 135 or current_angle == 315: neighbors = [G[i - 1, j + 1], G[i + 1, j - 1]] else: raise RuntimeError( "Wrong theta value {}- should be one of the following[0,45,90,135,180,225,270,315]".format( current_angle)) if G[i, j] >= np.max(neighbors): out[i, j] = G[i, j] # else: # out[i, j] = 0 ###################################### # END OF YOUR CODE # ###################################### return out def double_thresholding(img, high, low): """ Args: img: numpy array of shape (H, W) representing NMS edge response high: high threshold(float) for strong edges low: low threshold(float) for weak edges Returns: strong_edges: Boolean array representing strong edges. Strong edeges are the pixels with the values above the higher threshold. weak_edges: Boolean array representing weak edges. Weak edges are the pixels with the values below the higher threshould and above the lower threshold. """ strong_edges = np.zeros(img.shape) weak_edges = np.zeros(img.shape) strong_edges = img >= high weak_edges = (img < high) & (img > low) return strong_edges, weak_edges def get_neighbors(y, x, H, W): """ Return indices of valid neighbors of (y, x) Return indices of all the valid neighbors of (y, x) in an array of shape (H, W). An index (i, j) of a valid neighbor should satisfy the following: 1. i >= 0 and i < H 2. j >= 0 and j < W 3. (i, j) != (y, x) Args: y, x: location of the pixel H, W: size of the image Returns: neighbors: list of indices of neighboring pixels [(i, j)] """ neighbors = [] for i in (y - 1, y, y + 1): for j in (x - 1, x, x + 1): if i >= 0 and i < H and j >= 0 and j < W: if (i == y and j == x): continue neighbors.append((i, j)) return neighbors def link_edges(strong_edges, weak_edges): """ Find weak edges connected to strong edges and link them. Iterate over each pixel in strong_edges and perform breadth first search across the connected pixels in weak_edges to link them. Here we consider a pixel (a, b) is connected to a pixel (c, d) if (a, b) is one of the eight neighboring pixels of (c, d). Args: strong_edges: binary image of shape (H, W) weak_edges: binary image of shape (H, W) Returns: edges: numpy array of shape(H, W) """ H, W = strong_edges.shape indices = np.stack(np.nonzero(strong_edges)).T edges = np.zeros((H, W), dtype=np.bool) ##################################### # START YOUR CODE HERE # ##################################### for i, j in indices: neighbors = get_neighbors(i, j, H, W) edges[i, j] = 1.0 viewed = set() while neighbors: y, x = neighbors.pop(0) if (y, x) not in viewed and weak_edges[y, x]: edges[y, x] = 1.0 neighbors.extend(get_neighbors(y, x, H, W)) viewed.add((y, x)) ###################################### # END OF YOUR CODE # ###################################### return edges
5624a9ec0cb14a608cfd4e1dc26ab476a4b79084
korosaiki/pyewq
/strip 用法 isalnum检验字符串.py
196
3.8125
4
user = input("请输入用户名:") 移除前后空格 add = user.strip() print(add) if add.isalnum(): 注意:isalnum = isnum+isalpha print("注册成功") else: print("注册失败")
2c55d1f2f16380739ba6684804d3f77835566a63
Ivaylo-Atanasov93/The-Learning-Process
/Python Advanced/Comprahensions-Exercises/Word Filter.py
79
3.84375
4
string = input().split() [print(word) for word in string if len(word) % 2 == 0]
a3f18d464a1c66146d1064969a4c701968475e59
michelejolie/PDX-Code-Guild
/bankaccount_3.py
421
3.796875
4
class BankAccount: def __init__(self, f_name, l_name, balance): self.f_name = f_name self.l_name = l_name self.full_name = self.f_name + ' ' + self.l_name self.balance = balance self.setup() def setup(self): print('You have create an account for {}.'.format(self.full_name)) account1 = BankAccount('Chris', 'Jones',60) account2 = BankAccount('No', 'Name',5000)
85c181bf96bf6e0b52638c61657966b43e0ae850
Ilhamw/practicals
/prac_03/that_name_thing.py
312
3.84375
4
def main(): """Get name thing, without functions.""" name = get_name() print_name(name, 3) def print_name(name, step=2): print(name[::step]) def get_name(): name = input("Name: ") while name == "": print("Invalid name.") name = input("Name: ") return name main()
71c027aab9ffc237127e8102a13e1aad5f9bcdb4
zchenkui/MySimpleDNNLib-v1.0
/time_series.py
41,469
3.765625
4
import numpy as np import sys, os from word2vector import Embedding from basic_functions import softmax, sigmoid from basic_layers import Softmax class RNN: """ Recurrent Neural Network model (single block) A single block of RNN, which is the base of time series nerual network. """ def __init__(self, Wx, Wh, b): """ Initialize RNN Parameters: Wx: affine matrix for x(t) Wh: affine matrix for h(t-1) b: bias vector """ self.params = [Wx, Wh, b] self.grads = [np.zeros_like(Wx), np.zeros_like(Wh), np.zeros_like(b)] self.cache = None def forward(self, x, h_prev): """ Forward propagation of RNN Parameters: x: x(t) is the tth item in time series. The size of x(t) is (1 * D) (a vector) or (N * D) (a mini-batch) h_pre: h(t-1) is the previous output of RNN. The size of h(t-1) is (1 * H) (a vector) or (N * H) (a mini-batch) Note that N is the batch size. Size of weights matrices: Wx: (D * H) Wh: (H * H) b: (1 * H) Return: h_next: h(t) is the output of the current RNN block, which will be sent to the next RNN block. the size of h_next: (1 * H) (a vector) or (N * H) (a mini-batch) how to calculate h_next: h(t) = tanh(h(t-1).Wh + x(t).Wx + b) """ Wx, Wh, b = self.params t = np.dot(h_prev, Wh) + np.dot(x, Wx) + b h_next = np.tanh(t) self.cache = (x, h_prev, h_next) return h_next def backward(self, dh_next): """ Back propagation of RNN Parameter dh_next: the derivative matrix of h_next (i.e. h(t)). The size of dh_next is (N * H), which is identical to h_next. The size of matrices in each step: dt: (N * H) db: (1 * H) dWh: (H * H) dh_prev: (N * H) dWx: (D * H) dx: (N * D) Procedure: step 1. dt = dh_next * (1 - h_next^2). Note that [tanh(x)]' = 1 - [tanh(x)]^2 step 2. db = np.sum(dt, axis=0). Add all rows togethor, dt (N * H) ---> db (1 * H) step 3. dWh = transpose(h_prev).dt. h_prev (N * H) ---> transpose(h_prev) (H * N) ---> (H * N).(N * H) ---> (H * H) step 4. dh_prev = dt.transpose(Wh). transpose(Wh) (H * H) ---> dt (N * H) ---> (N * H).(H * H) ---> (N * H) step 5. dWx = transpose(x).dt. x (N * D) ---> transpose(x) (D * N) ---> dt (N * H) ---> (D * N).(N * H) ---> (D * H) step 6. dx = dt.transpose(Wx). dt (N * H) ---> transpose(Wx) (H * D) ---> (N * H).(H * D) ---> (N * D) """ Wx, Wh, _ = self.params x, h_prev, h_next = self.cache dt = dh_next * (1 - h_next**2) db = np.sum(dt, axis=0) dWh = np.dot(np.transpose(h_prev), dt) dh_prev = np.dot(dt, np.transpose(Wh)) dWx = np.dot(np.transpose(x), dt) dx = np.dot(dt, np.transpose(Wx)) self.grads[0][...] = dWx self.grads[1][...] = dWh self.grads[2][...] = db return dx, dh_prev class TimeRNN: """ Time RNN combines RNN blocks and learns time series """ def __init__(self, Wx, Wh, b, stateful=False): """ Initialize TimeRNN Parameters: Wx: (D * H) matrix Wh: (H * H) matrix b: (1 * H) vector stateful: use h_prev or not (if not, set h_prev to 0) """ self.params = [Wx, Wh, b] self.grads = [np.zeros_like(Wx), np.zeros_like(Wh), np.zeros_like(b)] self.layers = None self.h, self.dh = None, None self.stateful = stateful def set_state(self, h): """ Set hidden state to h Paramter: h: a hidden state matrix (size: (N * H)) Return: None """ self.h = h def reset_state(self): """ Reset hidden state to None """ self.h = None def forward(self, xs): """ Forward propagation of TimeRNN Parameter: xs: a time series input. The size of xs is (N * T * D) where N is the batch size, T is the time, and D is the length of word vector Return: hs: a time series hidden state. The size of hs is (N * T * H) where H is the length of hidden vector Note: if stateful is False or h is None, the input h is set to an (N * H) zero matrix. """ Wx, _, _ = self.params N, T, _ = np.shape(xs) _, H = np.shape(Wx) self.layers = [] hs = np.empty((N, T, H), dtype="f") if not self.stateful or self.h is None: self.h = np.zeros((N, H), dtype="f") for t in range(T): layer = RNN(*self.params) self.h = layer.forward(xs[:, t, :], self.h) hs[:, t, :] = self.h self.layers.append(layer) return hs def backward(self, dhs): """ Back propagation of TimeRNN Parameter: dhs: the derivative matrix of hs. dhs has the same size with hs (N * T * H) Return: dxs: the derivative matrix of xs. dxs has the same size with xs (N * T * D) Note that the initial dh is always 0. """ Wx, _, _ = self.params N, T, _ = np.shape(dhs) D, _ = np.shape(Wx) dxs = np.empty((N, T, D), dtype="f") dh = 0 grads = [0, 0, 0] for t in reversed(range(T)): layer = self.layers[t] dx, dh = layer.backward(dhs[:, t, :] + dh) dxs[:, t, :] = dx for i, grad in enumerate(layer.grads): grads[i] += grad for i, grad in enumerate(grads): self.grads[i][...] = grad self.dh = dh return dxs class TimeEmbedding: """ Extend Embedding layer to time series """ def __init__(self, W): """ Initialize TimeEmbedding class Parameter: W: an embedding matrix with size (V * D) where V is the vocabulary size """ self.params = [W] self.grads = [np.zeros_like(W)] self.layers = None self.W = W def forward(self, xs): """ Forward propagation of TimeEmbedding Parameter: xs: a time series batch with size (N * T) and each element is a word id. If N = 2 and T = 5, xs may look like: [ batch 0: [0, 1, 4, 8, 35], batch 1: [3, 6, 15, 7, 6], ] Return: out: convert each element in xs to a word vector with fixed length D. The size of out is (N * T * D) """ N, T = np.shape(xs) _, D = np.shape(self.W) out = np.empty((N, T, D)) self.layers = [] for t in range(T): layer = Embedding(self.W) out[:, t, :] = layer.forward(xs[:, t]) self.layers.append(layer) return out def backward(self, dout): """ Back propagation of TimeEmbedding Paramter: dout: the derivative matrix of out (see forward function). The size of dout is (N * T * D) Return: None Note that we add all grads togethor """ T = np.shape(dout)[1] grad = 0 for t in range(T): layer = self.layers[t] layer.backward(dout[:, t, :]) grad += layer.grads[0] self.grads[0][...] = grad class TimeAffine: """ Extend Affine layer to time series """ def __init__(self, W, b): """ Initialize TimeAffine class Paramters: W: an affine matrix with size (H * V) where H is the length of hidden vector and V is the vocabulary size b: a bias vector with V elements. """ self.params = [W, b] self.grads = [np.zeros_like(W), np.zeros_like(b)] self.x = None def forward(self, x): """ Forward propagation of TimeAffine Parameter: x: in RNN, x is identical to hs (see TimeRNN class). The size of x is (N * T * H) Return: out: a time series "score" matrix with size (N * T * V) """ N, T, _ = np.shape(x) W, b = self.params rx = np.reshape(x, newshape=(N * T, -1)) out = np.dot(rx, W) + b out = np.reshape(out, newshape=(N, T, -1)) self.x = x return out def backward(self, dout): """ Backward propagation of TimeAffine Parameter: dout: the derivative matrix of out (i.e. the score matrix, see forward function) with size (N * T * V) Return: dx: the derivative matrix of x. Here dx and x are dhs and hs respectively (see TimeRNN class). The size of x (hs) and dx (dhs) is (N * T * H) """ x = self.x N, T, H = np.shape(x) W, _ = self.params dout = np.reshape(dout, newshape=(N * T, -1)) rx = np.reshape(x, newshape=(N * T, -1)) db = np.sum(dout, axis=0) dW = np.dot(np.transpose(rx), dout) dx = np.dot(dout, np.transpose(W)) dx = np.reshape(dx, newshape=(N, T, H)) self.grads[0][...] = dW self.grads[1][...] = db return dx class TimeSoftmaxWithLoss: """ TimeSoftmaxWithLoss class We combine softmax layer and loss layer togethor and then convert them to time series version """ def __init__(self): """ Initialize TimeSoftmaxWithLoss class There is no input argument self.ingore_label is used in dropout algorithm """ self.params, self.grads = [], [] self.cache = None self.ignore_label = -1 def forward(self, xs, ts): """ Forward propagation of TimeSoftmaxWithLoss Parameters: xs: a score matrix from TimeAffine layer. The size of xs is (N * T * V), where V is the vocabulary size. ts: a label matrix. ts may have two various sizes: 1. (N * T * V), each label is given as a one-hot vector with length V 2. (N * T), each label is given as the target word id (a scalar) Return: loss: the loss of xs (a scalar) Note: how to calculate the loss of time series. batch N-1 batch N-2 ...... batch 0 t = 0 score_vec(N-1, 0) score_vec(N-2, 0) ...... score_vec(0, 0) ---> ts(0, 0) ---> Softmax and Cross Entropy Layer ---> loss 0 ---| t = 1 score_vec(N-1, 1) score_vec(N-2, 1) ...... score_vec(0, 1) ---> ts(0, 1) ---> Softmax and Cross Entropy Layer ---> loss 1 ---| . . . . . . | . . . . . . | ---> Average ---> loss . . . . . . | . . . . . . | t = T-1 score_vec(N-1, T-1) score_vec(N-2, T-1) ...... score_vec(0, T-1) ---> ts(0, T-1) ---> Softmax and Cross Entropy Layer ---> loss T-1 ---| Size of matrices: xs: (N * T * V) ---> ((N * T) * V) (3D to 2D) ts: (N * T * V) ---> (N * T) ---> (1 * (N * T)) (3D (argmax)---> 2D (reshape) ---> 1D vector) ys: ((N * T) * V) (2D) ls: (1 * (N * T)) (1D vector) loss: scalar """ N, T, V = np.shape(xs) if np.ndim(ts) == 3: ts = np.argmax(ts, axis=2) mask = (ts != self.ignore_label) xs = np.reshape(xs, newshape=(N * T, V)) ts = np.reshape(ts, newshape=(N * T)) mask = np.reshape(mask, newshape=(N * T)) ys = softmax(xs) ls = np.log(ys[np.arange(N * T), ts]) ls *= mask loss = -1 * np.sum(ls) loss /= np.sum(mask) self.cache = (ts, ys, mask, (N, T, V)) return loss def backward(self, dout=1): """ Back propagation of TimeSoftmaxWithLoss Parameter: dout: the derivative of loss (a scalar) Return: dx: the derivative matrix of xs (see forward function). Size of dx is (N * T * V) """ ts, ys, mask, (N, T, V) = self.cache dx = ys dx[np.arange(N * T), ts] -= 1 dx *= dout dx /= np.sum(mask) dx *= mask[:, np.newaxis] dx = np.reshape(dx, newshape=(N, T, V)) return dx class LSTM: """ LSTM single block """ def __init__(self, Wx, Wh, b): """ Initialize LSTM class Parameters: Wx: (D * 4H) matrix Wh: (H * 4H) matrix b: a vector with length 4H """ self.params = [Wx, Wh, b] self.grads = [np.zeros_like(Wx), np.zeros_like(Wh), np.zeros_like(b)] self.cache = None def forward(self, x, h_prev, c_prev): """Forward propagation of LSTM Parameters: x: (N * D) matrix h_prev: (N * H) matrix c_prev: (N * H) matrix Return: h_next: (N * H) matrix c_next: (N * H) matrix Steps of forward propagation: Sizes of matrices: x: (N * D) Wx: (D * 4H) h_prev: (N * H) Wh: (H * 4H) b: a vector with length 4H f, g, i, o: (N * H) c_next, h_next: (N * H) Step 1. A = x.Wx + h_prev.Wh + b Step 2. f = A[:, 0:H], g = A[:, H:2H], i = A[:, 2H:3H], o = A[:, 3H:] step 3. f = sigmoid(f) (forget gate) g = tanh(g) i = sigmoid(i) (input gate) o = sigmoid(o) (output gate) step 4. c_next = c_prev * f + g * i h_next = o * tanh(c_next) """ Wx, Wh, b = self.params _, H = np.shape(h_prev) A = np.dot(x, Wx) + np.dot(h_prev, Wh) + b f = A[:, 0 : H] g = A[:, H : 2 * H] i = A[:, 2 * H : 3 * H] o = A[:, 3 * H : ] f = sigmoid(f) g = np.tanh(g) i = sigmoid(i) o = sigmoid(o) c_next = c_prev * f + g * i h_next = np.tanh(c_next) * o self.cache = (x, h_prev, c_prev, i, f, g, o, c_next) return h_next, c_next def backward(self, dh_next, dc_next): """ Back propagation of LSTM Parameters: dh_next: the derivative matrix of h_next (size: (N * H)) dc_next: the derivative matrix of c_next (size: (N * H)) Return: dx: the derivative matrix of x (size: (N * D)) dh_prev: the derivative matrix of h_prev (size: (N * H)) dc_prev: the derivative matrix of c_prev (size: (N * H)) """ Wx, Wh, _ = self.params x, h_prev, c_prev, i, f, g, o, c_next = self.cache ds = dc_next + dh_next * o * (1 - np.tanh(c_next)**2) dc_prev = ds * f do = dh_next * np.tanh(c_next) di = ds * g dg = ds * i df = c_prev * ds do *= o * (1 - o) di *= i * (1 - i) dg *= (1 - g**2) df *= f * (1 - f) dA = np.hstack((df, dg, di, do)) db = np.sum(dA, axis=0) dWh = np.dot(np.transpose(h_prev), dA) dh_prev = np.dot(dA, np.transpose(Wh)) dWx = np.dot(np.transpose(x), dA) dx = np.dot(dA, np.transpose(Wx)) self.grads[0][...] = dWx self.grads[1][...] = dWh self.grads[2][...] = db return dx, dh_prev, dc_prev class TimeLSTM: """ Apply LSTM to time series data """ def __init__(self, Wx, Wh, b, stateful=False): """ Initialize TimeLSTM class Parameters: Wx: (D * 4H) matrix Wh: (H * 4H) matrix b: a vector with length 4H stateful: set False so that c and h are initialize with 0 (see forward function of LSTM to get for information) """ self.params = [Wx, Wh, b] self.grads = [np.zeros_like(Wx), np.zeros_like(Wh), np.zeros_like(b)] self.layers = None self.h, self.c = None, None self.dh = None self.stateful = stateful def forward(self, xs): """ Forward propagation of TimeLSTM Parameter: xs: (N * T * D) matrix Return: hs: (N * T * H) matrix """ Wx, Wh, b = self.params N, T, _ = np.shape(xs) H = np.shape(Wh)[0] self.layers = [] hs = np.empty(shape=(N, T, H), dtype="f") if (not self.stateful) or (self.h is None): self.h = np.zeros(shape=(N, H), dtype="f") if (not self.stateful) or (self.c is None): self.c = np.zeros(shape=(N, H), dtype="f") for t in range(T): layer = LSTM(Wx, Wh, b) self.h, self.c = layer.forward(xs[:, t, :], self.h, self.c) hs[:, t, :] = self.h self.layers.append(layer) return hs def backward(self, dhs): """ Back propagation of TimeLSTM Parameter: dhs: the derivative matrix of hs (size: (N * T * H)) Return: dxs: the derivative matrix of xs (size: (N * T * D)) """ Wx, _, _ = self.params N, T, _ = np.shape(dhs) D = np.shape(Wx)[0] dxs = np.empty(shape=(N, T, D), dtype="f") dh, dc = 0, 0 grads = [0, 0, 0] for t in reversed(range(T)): layer = self.layers[t] dx, dh, dc = layer.backward(dh + dhs[:, t, :], dc) dxs[:, t, :] = dx for i, grad in enumerate(layer.grads): grads[i] += grad for i, grad in enumerate(grads): self.grads[i][...] = grad self.dh = dh return dxs def set_state(self, h, c=None): self.h, self.c = h, c def reset_state(self): self.h, self.c = None, None class TimeDropout: """ Dropout layer used in time series """ def __init__(self, dropout_rate=0.5): """ Initialize TimeDropout class Parameter: dropout_rate: the proportion of nodes that will be dropout """ self.params, self.grads = [], [] self.dropout_rate = dropout_rate self.mask = None self.train_flag = True def forward(self, xs): """ Forward propagation of TimeDropout Parameter: xs: (N * T * D) matrix Return: xs: some elements are set to 0 (i.e. dropout) Note: Dropout is only used in training process but NOT used in evaluating process. """ if self.train_flag: flag = np.random.randn(*xs.shape) > self.dropout_rate scale = 1 / (1.0 - self.dropout_rate) self.mask = flag.astype("f") * scale return xs * self.mask else: return xs def backward(self, dout): """ Backward propagation of TimeDropout Parameter: dout: a derivative matrix of xs (size: (N * T * D)) Return: dout * mask: (N * T * D) matrix Note: In the returned matrix, the (elements) nodes that are dropout in forward propagation will also be set to 0. """ return dout * self.mask class Encoder: """ Encoder part (seq2seq) """ def __init__(self, vocab_size, wordvec_size, hidden_size): """ Building Encoder block of seq2seq Parameters: vocab_size: vocabulary size of a given corpus wordvec_size: the length of word vector (embedding layer) hidden_size: the length of hidden vector (LSTM layer) Matrices and their sizes: 1. Used in TimeEmbedding layer embed_W: (V * D) 2. Used in TimeLSTM layer lstm_Wx: (D * 4H) lstm_Wh: (H * 4H) lstm_b: a vector with length 4H Model: xs (N * T) ---> TimeEmbedding layer --- xs (N * T * D) ---> TimeLSTM layer --- hs (N * T * H) | | | v hs[:, -1, :] (The last result will be sent to Decode part) """ V, D, H = vocab_size, wordvec_size, hidden_size embed_W = (np.random.randn(V, D) / 100).astype("f") lstm_Wx = (np.random.randn(D, 4 * H) / np.sqrt(D)).astype("f") lstm_Wh = (np.random.randn(H, 4 * H) / np.sqrt(H)).astype("f") lstm_b = np.zeros(4 * H).astype("f") self.embed = TimeEmbedding(embed_W) self.lstm = TimeLSTM(lstm_Wx, lstm_Wh, lstm_b, stateful=False) self.params = self.embed.params + self.lstm.params self.grads = self.embed.grads + self.lstm.grads self.hs = None def forward(self, xs): """ Forward propagation of Encoder Parameters: xs: the input mini-batch with size (N * T) Return: hs[:, -1, :]: the last hidden result will be sent to Decoder part (size: (N * H)) (see the comment of __init__ function) """ xs = self.embed.forward(xs) hs = self.lstm.forward(xs) self.hs = hs return hs[:, -1, :] def backward(self, dh): """ Back propagation of Encoder Parameter: dh: the derivative matrix of hs[:, -1, :] (size: (N * H)) """ dhs = np.zeros_like(self.hs) dhs[:, -1, :] = dh dout = self.lstm.backward(dhs) self.embed.backward(dout) class Decoder: """ Decoder part (seq2seq) """ def __init__(self, vocab_size, wordvec_size, hidden_size): """ Initialize Decoder class Parameter: vocab_size: vocabulary size of a given corpus wordvec_size: the length of word vector (embedding layer) hidden_size: the length of hidden vector (LSTM layer) Matrices and their sizes: 1. Used in TimeEmbedding layer embed_W: (V * D) 2. Used in TimeLSTM layer lstm_Wx: (D * 4H) lstm_Wh: (H * 4H) lstm_b: a vector with length 4H 3. Used in Affine layer affine_W: (H * V) affine_b: a vector with length V Model: xs (mini-batch of output, size: (N * T)) ---> TimeEmbedding layer --- xs (N * T * D)--| |--> TimeLSTM --- hs (N * T * H) ---> TimeAffine ---> score (N * T * V) h (N * H, from Encoder part)--| """ V, D, H = vocab_size, wordvec_size, hidden_size embed_W = (np.random.randn(V, D) / 100).astype("f") lstm_Wx = (np.random.randn(D, 4 * H) / np.sqrt(D)).astype("f") lstm_Wh = (np.random.randn(H, 4 * H) / np.sqrt(H)).astype("f") lstm_b = np.zeros(4 * H).astype("f") affine_W = (np.random.randn(H, V) / np.sqrt(H)).astype("f") affine_b = np.zeros(V).astype("f") self.embed = TimeEmbedding(embed_W) self.lstm = TimeLSTM(lstm_Wx, lstm_Wh, lstm_b, stateful=True) self.affine = TimeAffine(affine_W, affine_b) self.params, self.grads = [], [] for layer in (self.embed, self.lstm, self.affine): self.params += layer.params self.grads += layer.grads def forward(self, xs, h): """ Forward propagation of Decoder Parameters: xs: mini-batch of output (size: (N * T)) h: hidden matrix from Encoder (size: (N * H)) Return: score: score matrix with size (N * T * V) Note that we do not calculate loss here. Loss value will be calculate in seq2seq class. See Example06 to get more detail. """ self.lstm.set_state(h) out = self.embed.forward(xs) out = self.lstm.forward(out) score = self.affine.forward(out) return score def backward(self, dscore): """ Back propagation of Decoder Parameter: dscore: the derivative matrix of score (size: (N * T * V)) Return: dh: the derivative matrix of h (size: (N * H)). Note that dh will be used in back propagation of Encoder part (See backward function of Encoder class) """ dout = self.affine.backward(dscore) dout = self.lstm.backward(dout) self.embed.backward(dout) dh = self.lstm.dh return dh def generate(self, h, start_id, sample_size): """ Generate text automatically with trained model Paramters: h: hidden matrix (size: (N * H)) start_id: the start word id sample_size: the size that how many words will be selected Return: sample: an automatically generated text """ sample = [] sample_id = start_id self.lstm.set_state(h) for _ in range(sample_size): x = np.array(sample_id).reshape((1, 1)) out = self.embed.forward(x) out = self.lstm.forward(out) score = self.affine.forward(out) sample_id = np.argmax(score.flatten()) sample.append(int(sample_id)) return sample class PeekyDecoder: """ PeekyDecoder is an improved Decoder class The difference between Decoder and PeekyDecoder is as follows: Decoder: h, the hidden matrix with size (N * H) from Encoder part, is only used by the first LSTM block. PeekyDecoder: h is used in all LSTM block and all Affine block See this paper to get more detail: Kyunghyun Cho, et al: "Learning Phrase Representations Using RNN Encoder-Decoder for Statistical Mochine Translation", arXiv: 1406.1078v3, 2014 (link: https://arxiv.org/abs/1406.1078) """ def __init__(self, vocab_size, wordvec_size, hidden_size): """ Initialize Parameters: vocab_size: vocabulary size of a given corpus wordvec_size: the length of word vector (embedding layer) hidden_size: the length of hidden vector (LSTM layer) Matrices and their sizes: 1. Used in Embedding layer embed_W: (V * D) 2. Used in LSTM layer lstm_Wx: ((H + D) * (4H)) lstm_Wh: (H * 4H) lstm_b: a vector with length 4H 3. Used in Affine layer affine_W: ((H + H) * V) affine_b: a vector with length V Note: 1. The size of lstm_Wx in Decoder is (D * 4H) while the size of lstm_Wx in PeekyDecoder is ((H + D) * 4H). This is because in PeekyDecoder, we conbime xs and h together as the input of LSTM 2. h is not only used in LSTM layer but is also used in Affine layer. The size of input of Affine layer in Decoder is (H * V) while it is ((H + H) * V) in PeekyDecoder Model: The PeekyDecoder model is identical to Decoder model. """ V, D, H = vocab_size, wordvec_size, hidden_size embed_W = (np.random.randn(V, D) / 100).astype("f") lstm_Wx = (np.random.randn(H + D, 4 * H) / np.sqrt(H + D)).astype("f") lstm_Wh = (np.random.randn(H, 4 * H) / np.sqrt(H)).astype("f") lstm_b = np.zeros(4 * H).astype("f") affine_W = (np.random.randn(H + H, V) / np.sqrt(H + H)).astype("f") affine_b = np.zeros(V).astype("f") self.embed = TimeEmbedding(embed_W) self.lstm = TimeLSTM(lstm_Wx, lstm_Wh, lstm_b, stateful=True) self.affine = TimeAffine(affine_W, affine_b) self.params, self.grads = [], [] for layer in (self.embed, self.lstm, self.affine): self.params += layer.params self.grads += layer.grads self.cache = None def forward(self, xs, h): """ Forward propagation of PeekyDecoder Parameters: xs: (N * T) matrix (input mini-batch) h: (N * H) matrix (from Encoder part) Return: score: the score matrix with size (N * T * V) """ N, T = np.shape(xs) N, H = np.shape(h) self.lstm.set_state(h) out = self.embed.forward(xs) hs = np.repeat(h, T, axis=0).reshape((N, T, H)) out = np.concatenate((hs, out), axis=2) out = self.lstm.forward(out) out = np.concatenate((hs, out), axis=2) score = self.affine.forward(out) self.cache = H return score def backward(self, dscore): """ Back propagation of PeekyDecoder Parameter: dscore: the derivative matrix of score (size: (N * T * V)) Return: dh: the derivative matrix of h (size: (N * H)) """ H = self.cache dout = self.affine.backward(dscore) dout, dhs0 = dout[:, :, H:], dout[:, :, :H] dout = self.lstm.backward(dout) dembed, dhs1 = dout[:, :, H:], dout[:, :, :H] self.embed.backward(dembed) dhs = dhs0 + dhs1 dh = self.lstm.dh + np.sum(dhs, axis=1) return dh def generate(self, h, start_id, sample_size): """ Generate text automatically with trained model Paramters: h: hidden matrix (size: (N * H)) start_id: the start word id sample_size: the size that how many words will be selected Return: sample: an automatically generated text """ sample = [] char_id = start_id self.lstm.set_state(h) H = np.shape(h)[1] peeky_h = np.reshape(h, newshape=(1, 1, H)) for _ in range(sample_size): x = np.array([char_id]).reshape((1, 1)) out = self.embed.forward(x) out = np.concatenate((peeky_h, out), axis=2) out = self.lstm.forward(out) out = np.concatenate((peeky_h, out), axis=2) score = self.affine.forward(out) char_id = np.argmax(score.flatten()) sample.append(char_id) return sample class WeightSum: """ WeightSum class (part of Attention) WeightSum class is used to calculate the weigh sum of hidden matrix given by LSTM and probability vector a. For a single input time series: hs: (T * H) hidden matrix given by TimeLSTM layer a: a weight vector with length T Then, the calculation is as follows: a (length T) ----> ar (T * 1) matrix (reshape) ----> t = hs * ar (numpy broadcast) ----> c = sum(t, axis=0) (c is a content vector with lengyth H) For a mini-batch: hs: (N * T * H) a: (N * T) The calculation is identical to above one and the result c is an (N * H) content matrix """ def __init__(self): """ Initialize WeightSum class There is no parameter """ self.params, self.grads = [], [] self.cache = None def forward(self, hs, a): """ Forward propagation of WeightSum class Parameters: hs: (N * T * H) hidden matrix a: (N * T) weight matrix Return: c: (N * H) content matrix """ N, T, _ = np.shape(hs) ar = np.reshape(a, newshape=(N, T, 1)) t = hs * ar c = np.sum(t, axis=1) self.cache = (hs, ar) return c def backward(self, dc): """ Back propagation of WeightSum class Parameter: dc: the derivative matrix of content matrix c (size: (N * H)) Return: dhs: the derivative matrix of hs (size: (N * T * H)) da: the derivative matrix of a (size: (N * T)) """ hs, ar = self.cache N, T, H = np.shape(hs) dt = np.reshape(dc, newshape=(N, 1, H)) dt = np.repeat(dt, repeats=T, axis=1) dar = dt * hs dhs = dt * ar da = np.sum(dar, axis=2) return dhs, da class AttentionWeight: """ AttentionWeight class AttentionWeight is used to calculate the weight matrix a. Given the matrix hs from TimeLSTM in Encoder and the matrix h from TimeLSTM in Decoder, weight matrix a is calculated by: Step 1. Reshape h to hr (size: h (N * H), hr (N * 1 * H)) Step 2. hr is reshaped to (N * T * H) Step 3. t = hr * hs (element-wise product) Step 4. s = sum(t, axis=2) (s: (N * T)) Step 5. a = softmax(s) (convert score s to weight a) (a: (N * T)) """ def __init__(self): """ Initialize AttentionWeight class There is no parameter """ self.params, self.grads = [], [] self.softmax = Softmax() self.cache = None def forward(self, hs, h): """ Forward propagation of AttentionWeight Parameters: hs: (N * T * H) matrix h: (N * H) matrix Return: a: (N * T) weight matrix """ N, T, H = np.shape(hs) hr = np.reshape(h, newshape=(N, 1, H)) hr = np.repeat(hr, repeats=T, axis=1) t = hs * hr s = np.sum(t, axis=2) a = self.softmax.forward(s) self.cache = (hs, hr) return a def backward(self, da): """ Back propagation of AttentionWeight class Paramter: da: the derivative matrix of weight matrix a (size: (N * T)) Return: dhs: the derivative matrix of hs (size: (N * T * H)) dh: the derivative matrix of h (size: (N * H)) """ hs, hr = self.cache N, T, H = np.shape(hs) ds = self.softmax.backward(da) dt = np.reshape(ds, newshape=(N, T, 1)) dt = np.repeat(dt, repeats=H, axis=2) dhr = dt * hs dhs = dt * hr dh = np.sum(dhr, axis=1) return dhs, dh class Attention: """ Single Attention block A single Attention block is just constructed by AttentionWeight block and WeightSum block. """ def __init__(self): """ Initialize Attention class """ self.params, self.grads = [], [] self.attention_weight_layer = AttentionWeight() self.weight_sum_layer = WeightSum() self.attention_weight = None def forward(self, hs, h): """ Forward propagation of Attention Parameters: hs: (N * T * H) matrix (from Encoder TimeLSTM block) h: (N * H) matrix (from Decoder LSTM block) Return: out: (N * H) content matrix """ a = self.attention_weight_layer.forward(hs, h) out = self.weight_sum_layer.forward(hs, a) self.attention_weight = a return out def backward(self, dout): """ Back propagation of Attention Parameter: dout: the derivative matrix of content matrix out (size: (N * H)) Return: dhs: the derivative matrix of hs (size: (N * T * H)) dh: the derivative matrix of h (size: (N * H)) """ dhs0, da = self.weight_sum_layer.backward(dout) dhs1, dh = self.attention_weight_layer.backward(da) dhs = dhs0 + dhs1 return dhs, dh class TimeAttention: """ TimeAttention class TimeAttention class convert single Attention block to time series """ def __init__(self): self.params, self.grads = [], [] self.layers = None self.attention_weights = None def forward(self, hs_enc, hs_dec): _, T, _ = np.shape(hs_dec) out = np.empty_like(hs_dec) self.layers = [] self.attention_weights = [] for t in range(T): layer = Attention() out[:, t, :] = layer.forward(hs_enc, hs_dec[:, t, :]) self.layers.append(layer) self.attention_weights.append(layer.attention_weight) return out def backward(self, dout): _, T, _ = np.shape(dout) dhs_enc = 0 dhs_dec = np.empty_like(dout) for t in range(T): layer = self.layers[t] dhs, dh = layer.backward(dout[:, t, :]) dhs_enc += dhs dhs_dec[:, t, :] = dh return dhs_enc, dhs_dec def eval_perplexity(model, corpus, batch_size=10, time_size=35): """ Evaluate perplexity of current model Perplexity is used to evaluate a language model. It is defined as perplexity = exp(L) where L is the average loss of model. The smaller the perplexity is, the better the model is Parameters: model: a given language model corpus: a given corpus batch_size: the batch size time_size: time size Return: ppl: perplexity """ print("evaluating perplexity ... ") corpus_size = len(corpus) total_loss = 0 max_iters = (corpus_size - 1) // (batch_size * time_size) jump = (corpus_size - 1) // batch_size for iters in range(max_iters): xs = np.zeros(shape=(batch_size, time_size), dtype=np.int32) ts = np.zeros(shape=(batch_size, time_size), dtype=np.int32) time_offset = iters * time_size offsets = [time_offset + (i * jump) for i in range(batch_size)] for t in range(time_size): for i, offset in enumerate(offsets): xs[i, t] = corpus[(offset + t) % corpus_size] ts[i, t] = corpus[(offset + t + 1) % corpus_size] try: loss = model.forward(xs, ts, train_flag=False) except TypeError: loss = model.forward(xs, ts) total_loss += loss sys.stdout.write('\r%d / %d' % (iters, max_iters)) sys.stdout.flush() print("") ppl = np.exp(total_loss / max_iters) return ppl def eval_seq2seq(model, question, correct, id_to_char, verbos=False, is_reverse=False): correct = correct.flatten() start_id = correct[0] correct = correct[1:] guess = model.generate(question, start_id, len(correct)) question = "".join([id_to_char[int(c)] for c in question.flatten()]) correct = "".join([id_to_char[int(c)] for c in correct]) guess = "".join([id_to_char[int(c)] for c in guess]) if verbos: if is_reverse: question = question[::-1] colors = {"ok": "\033[92m", "fail": "\033[91m", "close": "\033[0m"} print("Q", question) print("T", correct) is_windows = os.name == "nt" if correct == guess: mark = colors["ok"] + "☑" + colors["close"] if is_windows: mark = "O" print(mark, " ", guess) else: mark = colors["fail"] + "☒" + colors["close"] if is_windows: mark = "X" print(mark, " ", guess) print("----") return 1 if guess == correct else 0
48e188ba605cb201653ac47f2d4d297f142dcb5f
Yelimbert/Registro
/registrov2.py
1,823
3.65625
4
import os nombreArchivo = "registro.txt" def agregar(): print("Ingrese los siguientes datos") nombre = input("Nombre: ") ape = input("Apellido: ") edad = input("Edad: ") cedula = input("Cedula: ") registro = nombre + ", " + ape + ", " + edad + ", " + cedula y = input("Desea guardar los datos/(si/no): ") if y == "si": with open(nombreArchivo, "a") as reg: datos = "\n" + registro reg.write(datos) def header(): reg = open(nombreArchivo, "w+") escribir = False primera_linea= "Nombre, Apellido, Edad, Cedula" if not os.path.isfile(nombreArchivo): escribir = True else: print(reg.read()) escribir = len(reg.readlines()) == 0 if escribir: reg.write(primera_linea) reg.close() def buscar(): with open(nombreArchivo, "r") as reg: texto = input("Por favor, inserta la cedula: ") for linea in reg.readlines(): if linea.find(texto) > -1: print("Encontrado: " + linea) def inicio(): header() agregar() preg = input( "(y) Deseo ingresar mas datos\n(n) No deseo ingresar mas datos\n") if preg == "y": while preg == "y": agregar() preg = input( "(y) Deseo ingresar mas datos\n(n) No deseo ingresar mas datos: ") print(preg) elif preg == "n": print("No se almacenaran mas datos") interfaz() def interfaz(): print("Que desea realizar?") q = input("(1) Deseo ingresar datos\n(2) Deseo realizar una busqueda\n(3) No deseo hacer nada\n") if q == "1": inicio() elif q == "2": buscar() else: print("Ha salido del programa") interfaz()
bf1d745241860c52b9ebf11db521c4ea1851bd3a
danqiye1/bandit
/bandits/epsilon_greedy.py
3,542
3.578125
4
import random from bandits import BernoulliBandit class EpsilonGreedy: def __init__(self, bandits: list, epsilon=0.05): """ Constructor for the epsilon-greedy algorithm :param bandits: A list of bandits to play :type bandits: list :param epsilon: Exploration vs exploitation tradeoff parameter :type epsilon: float """ self.bandits = bandits self.epsilon = epsilon # Container for sample mean of each bandit self.sample_means = [0] * len(bandits) # Container for the number of plays of each bandit self.counts = [0] * len(bandits) # Internally track the number of steps run self.num_steps = 0 def run(self, num_steps=10000): """ Run the epsilon-greedy algorithm """ total_rewards = 0 for _ in range(num_steps): p = random.random() if p < self.epsilon: # Exploration. Select a random bandit. j = random.randint(0, len(self.bandits)-1) else: # Exploitation. Select the bandit with largest sample mean j = self._argmax(self.sample_means) bandit = self.bandits[j] reward = bandit.pull() total_rewards += reward # Update sample mean self._update_means(j, reward) self.num_steps += 1 return total_rewards def recommend_bandit(self): """ Recommend the best bandit to play with the best reward """ bandit_idx = self._argmax(self.counts) return self.counts[bandit_idx], bandit_idx def _argmax(self, l: list): """ Helper function for finding argmax of list l """ max_i, max_v = 0, 0 for i, v in enumerate(l): if v > max_v: max_i = i max_v = v return max_i def _update_means(self, idx: int, reward: float): """ Update the sample mean and counts of the i_th bandit """ self.counts[idx] += 1 self.sample_means[idx] = self.sample_means[idx] + 1 / \ self.counts[idx] * (reward - self.sample_means[idx]) if __name__ == "__main__": # Do a 3 bandit experiment bandits = [BernoulliBandit(0.2), BernoulliBandit(0.6), BernoulliBandit(0.8)] algo = EpsilonGreedy(bandits) # Run 10 times rewards = algo.run(num_steps=10) count, i = algo.recommend_bandit() print("Total rewards is {} after {} steps".format(rewards, algo.num_steps)) print("Bandit {} is played {} times after {} steps".format( i, count, algo.num_steps)) print('') # Run 100 times rewards = algo.run(num_steps=90) count, i = algo.recommend_bandit() print("Total rewards is {} after {} steps".format(rewards, algo.num_steps)) print("Bandit {} is played {} times after {} steps".format( i, count, algo.num_steps)) print('') # Run 1000 times rewards = algo.run(num_steps=900) count, i = algo.recommend_bandit() print("Total rewards is {} after {} steps".format(rewards, algo.num_steps)) print("Bandit {} is played {} times after {} steps".format( i, count, algo.num_steps)) print('') # Run 10000 times rewards = algo.run(num_steps=9000) count, i = algo.recommend_bandit() print("Total rewards is {} after {} steps".format(rewards, algo.num_steps)) print("Bandit {} is played {} times after {} steps".format( i, count, algo.num_steps)) print('')
c77b1236b87919920a769469b80a6f085c27c30a
reviakin/SICP
/coins_exchange.py
540
3.609375
4
def first_denomination(kinds_of_coins): if kinds_of_coins == 1: return 1 if kinds_of_coins == 2: return 5 if kinds_of_coins == 3: return 10 if kinds_of_coins == 4: return 25 if kinds_of_coins == 5: return 50 return 0 def cc(amount, kinds_of_coins): if amount == 0: return 1 if amount < 0 or kinds_of_coins == 0: return 0 return cc(amount, kinds_of_coins - 1) + cc(amount - first_denomination(kinds_of_coins), kinds_of_coins) def count_change(amount): return cc(amount, 5) print(count_change(100))
8de599c8c16b4c629e12543cd0d8a4003285afcd
wangxiao4/programming
/Num5/5.3_GuessNumber.py
291
3.921875
4
import random rand_number=random.randint(1,100) guess_number=-1 while guess_number != rand_number: guess_number=eval(input("enter your number\n")) if guess_number>rand_number: print("too high\n") elif guess_number<rand_number: print("too low\n") print("you win")
26ea01e211cc0a6d69cb4f07a77fa39cc9b7eaa9
kingking888/2019-
/python学习/实训/nine/c1.py
2,066
4
4
class Student(): # name='aaa' # age=0 sum1=0 # name='s' def __init__(self,name11,age): self.name=name11 self.age=age self.__score=0 # print(self.__dict__) # print(name) 访问的是形参的name,所以将形参的名字改了之后就会报错 # self.__class__.sum1+=1 # print(Student.sum1) # print('当前班级学生总数为:'+str(self.__class__.sum1)) # print(age) # print('student:',name,age) # print(score) def do_homework(self): print('homework') print(self.name) @classmethod def plus_sum(cls): cls.sum1+=1 # print(cls.sum1) # print(self.name) print(self.name) @staticmethod def add(x,y): print('This is a static method') print(x+y) print(self.name) def __scoring__(self,score): if score<0: return '不能够给别人打负分' self.__score=score print(self.name+"同学本次考试分数为:"+str(self.__score)) class Printer(): def print_file(self): print('name:'+self.name) print('age:'+str(self.age)) class StudentHomework(): homework_name='' student1= Student('石敢当',18) student2=Student('dfd',90) # result=student1.__scoring__(59) # print(result) # result=student1.__scoring__(-1) # print(result) # student1.__score=-1 # student2.__score=-2 # print(student1.__score) print(student2._Student__score) # r=student1.__score # print(r) # print(student1.__dict__) # student1.do_homework() # student1.plus_sum() # Student.plus_sum() # print(student1.__dict__) # print(student1.age) # print(student1.name) # print(Student.__dict__) # student2=Student('dhdshg',15) # Student.plus_sum() # student3=Student('sdfassdf',45) # Student.plus_sum() # student.print_file() # student1.plus_sum() # student2.plus_sum() # student3.plus_sum() # student1.add(1,2) # print(id(student1)) # print(id(student2)) # print(id(student3)) # a=student1.__init__() # print(a) # print(type(a))
0c282384e4d79b96af8cf505e6cf441655d341ab
SNBhushan/BASICS-OF-PYTHON
/py2.py
282
3.953125
4
#palimdrome # def ispalindrome(s): # s=s.lower() # for item in range(len(s)//2): # if s[item]!=s[len(s)-item-1]: # return False # return True def ispalindrome(s): s=s.lower() return s==s[::-1] s="madam" print(ispalindrome(s))
42c6e46eae1222ca6332c52353ee7dfbafd5a512
aaron6347/leetcode_April30Days
/venv/day10_min_stack.py
1,684
3.6875
4
"""day10_min_stack.py Created by Aaron at 10-Apr-20""" class MinStack: # app1 # def __init__(self): # """ # initialize your data structure here. # """ # self.ar = [] # def push(self, x: int) -> None: # self.ar.append(x) # def pop(self) -> None: # self.ar.pop() # def top(self) -> int: # return self.ar[-1] # def getMin(self) -> int: # return min(self.ar) # app2 def __init__(self): """ initialize your data structure here. """ self.ar = [] def push(self, x: int) -> None: # min = self.getMin() # if min == None or min > x: # min = x # self.ar.append((x, min)) if len(self.ar)==0: self.ar.append((x,x)) else: self.ar.append((x, min(self.ar[-1][1], x))) def pop(self) -> None: self.ar.pop() def top(self) -> int: if len(self.ar) == 0: return None return self.ar[-1][0] def getMin(self) -> int: if len(self.ar) == 0: return None return self.ar[-1][1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin() a=["MinStack","push","push","push","getMin","pop","top","getMin"] b=[[None],[-2],[0],[-3],[None],[None],[None],[None]] run=MinStack() x=1 ar=[] while x<len(a): if b[x][0]!= None: ar.append(eval('run.{0}({1})'.format(a[x], b[x][0]))) else: ar.append(eval('run.{0}()'.format(a[x]))) x+=1 print(ar) # app1 using list with min O(n k) # app2 using tuple in list O(n)
9a4838ccabcbd419526d9cc5efbfd83e7101607b
meher1087/learn_ros_python
/ros_ws/src/jarvis/Calendar/archive/w2n_full_text.py
6,489
3.703125
4
# a mapping of digits to their names when they appear in the # relative "ones" place (this list includes the 'teens' because # they are an odd case where numbers that might otherwise be called # 'ten one', 'ten two', etc. actually have their own names as single # digits do) class my_w2n: __ones__ = { 'one': 1, 'eleven': 11, 'two': 2, 'twelve': 12, 'three': 3, 'thirteen': 13, 'four': 4, 'fourteen': 14, 'five': 5, 'fifteen': 15, 'six': 6, 'sixteen': 16, 'seven': 7, 'seventeen': 17, 'eight': 8, 'eighteen': 18, 'nine': 9, 'ten':10 , 'nineteen': 19, 'half':0.5 } # a mapping of digits to their names when they appear in the 'tens' # place within a number group __tens__ = { 'nhalf': 30, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90 } # an ordered list of the names assigned to number groups __groups__ = { 'hundred':100, 'thousand': 1000, 'million': 1000000, 'billion': 1000000000, 'trillion': 1000000000000 } def __init__(self): self.info = "This will convert words to numbers" # find def find_grands(self,s): if type(s) is str: words = s.split() elif type(s) is list: words=s words.append('d') new_value=0 count=0 # count to know starta and end of numbers old_value=0 start = None got_and = False try: while(count<len(words)): not_one = True not_ten = True not_grand = True if words[count] in self.__ones__.keys(): if start is None: start = count not_one=False new_value = self.__ones__.get(words[count]) count+=1 if count==len(words): if old_value>new_value: old_value = old_value+new_value # else: # non_currency = True # #old_value = old_value*100 + new_value # old_value = str(old_value)+' h '+str(new_value)+' m ' # end = count # break if words[count] in self.__groups__.keys(): if start is None: start = count not_grand = False new_value *= self.__groups__.get(words[count]) count+=1 old_value=old_value+new_value elif words[count] in self.__groups__.keys(): if start is None: start = count not_grand = False start = count new_value =self.__groups__.get(words[count]) count+=1 old_value=old_value+new_value if words[count] in self.__tens__.keys(): if start is None: start = count not_ten = False if new_value>99: old_value = old_value + self.__tens__.get(words[count]) count+=1 else: non_currency = True #old_value = old_value+new_value*100 + self.__tens__.get(words[count]) old_value = str(new_value)+' h '+str(self.__tens__.get(words[count]))+' m ' count+=1 if not_grand and not_ten and not not_one: if got_and: old_value = old_value+new_value got_and = False else: old_value = new_value not_one = True # if not_grand and not_ten and not not_one: # old_value = old_value+new_value if not_grand and not_ten and not_one: if start is not None and words[count]!='and': end = count words = words[:start] + [str(old_value)] + words[end:] new_value = 0 start = None old_value=0 elif words[count]=='and': got_and=True count+=1 else: count+=1 if start is not None: end = count words = words[:start] + [str(old_value)] + words[end:] return words[:-1] except IndexError: end = count words = words[:start] + [str(old_value)] + words[end:] return words[:-1] def find_time(self,s): short = False ''' Three hour twenty minutes - 3h20m three and half hour- 3h30m three hours - 3h an hour - 1h half an hour - 30m ''' if type(s) is list: n = ' ' s = n.join(s) if 'half an hour' in s: s = s.replace('half an hour','0 h 30 m') short = True if 'in an hour' in s: s = s.replace('an hour','1 h') short = True if 'and half' in s: s = s.replace('and half', 'nhalf') short=True if ' hours' in s or 'minutes' in s: short = True # if 'half hour' in s or 'half hours' in s: # s = s.replace('half hour','halfhour') new_value = self.find_grands(s) found=True if new_value is None: found = False return new_value,found,short # a = my_w2n() # s = "let check if this works for remind me in ten to pay three hundred" # new_value=a.find_time(s) # new_value = a.find_grands(new_value) # if new_value is not None: # print(new_value) # else: print("No numbers found") # print(" ") # print(s) # print(" ")
0dd552d23bf21038145704d58045d6a3f1a66705
CoderJuan21/C-106
/codeIcecream.py
697
3.53125
4
import csv import numpy as np import plotly.express as px def getData(): icecream_sales = [] colddrink_sales = [] with open ("dataIce.csv") as f: csv_reader = csv.DictReader(f) for row in csv_reader : icecream_sales.append(float(row["Temperature"])) colddrink_sales.append(float(row["Ice-cream Sales"])) return {"x":icecream_sales, "y": colddrink_sales} def findCorrelation(dataSource): correlation = np.corrcoef(dataSource["x"],dataSource["y"]) print("Correlation between tempeture and icecream sales ==>", correlation[0,1]) def setup(): dataSource = getData() findCorrelation(dataSource) setup()
c3146fd800333020f7521454c247b010330784c8
chayankathuria/Feature_Engineering-
/Categorical.py
5,820
3.546875
4
import pandas as pd import numpy as np # Transforming Nominal Data ''' Nominal data consists of names as labels and we need to transform these labels into numbers so that the algortithm can understand. One such technique is Label Encoding which converts labels into integers starting from 1. ''' vg_df = pd.read_csv('datasets/vgsales.csv', encoding='utf-8') vg_df[['Name', 'Platform', 'Year', 'Genre', 'Publisher']].iloc[1:7] # Preparing dataframe for label encoding genres = np.unique(vg_df['Genre']) genres from sklearn.preprocessing import LabelEncoder gle = LabelEncoder() genre_labels = gle.fit_transform(vg_df['Genre']) genre_mappings = {index: label for index, label in enumerate(gle.classes_)} # Dsiplaying all the categories and their labels genre_mappings vg_df['GenreLabel'] = genre_labels vg_df[['Name', 'Platform', 'Year', 'Genre', 'GenreLabel']].iloc[1:7] # Adding the Label Encoded column to the DF # Transforming Ordinal Data ''' Ordinal Data is another type of categorical data where the labels cannot be quantized but an order can be set. For ex. Unhappy < OK < Happy < Verry Happy , but we cannot quantize how much. ''' poke_df = pd.read_csv('datasets/Pokemon.csv', encoding='utf-8') poke_df = poke_df.sample(random_state=1, frac=1).reset_index(drop=True) np.unique(poke_df['Generation']) # array(['Gen 1', 'Gen 2', 'Gen 3', 'Gen 4', 'Gen 5', 'Gen 6'], dtype=object) gen_ord_map = {'Gen 1': 1, 'Gen 2': 2, 'Gen 3': 3, 'Gen 4': 4, 'Gen 5': 5, 'Gen 6': 6} poke_df['GenerationLabel'] = poke_df['Generation'].map(gen_ord_map) poke_df[['Name', 'Generation', 'GenerationLabel']].iloc[4:10] ''' Using map function is just another way to label encode categorical features, ordinal or nominal. But it is recommended only when the number of features is less because it requires hard-coding. Name Generation GenerationLabel 4 Octillery Gen 2 2 5 Helioptile Gen 6 6 6 Dialga Gen 4 4 7 DeoxysDefense Forme Gen 3 3 8 Rapidash Gen 1 1 9 Swanna Gen 5 5 ''' # One-Hot Encoding ''' Label Encoding Encodes labels with value between 0 and n_classes-1. OHE, on the other hand, Encodes categorical integer features using a one-hot aka one-of-K scheme. The input to the transformer should be a matrix of integers, denoting the values taken on by categorical (discrete) features. The output will be a sparse matrix where each column corresponds to one possible value of one feature. It is assumed that input features take on values in the range [0, n_values). ''' # Let's take a look at our df poke_df[['Name', 'Generation', 'Legendary']].iloc[4:10] ''' Name Generation Legendary 4 Octillery Gen 2 False 5 Helioptile Gen 6 False 6 Dialga Gen 4 True 7 DeoxysDefense Forme Gen 3 True 8 Rapidash Gen 1 False 9 Swanna Gen 5 False ''' # Running label encoder first from sklearn.preprocessing import OneHotEncoder, LabelEncoder # transform and map pokemon generations gen_le = LabelEncoder() gen_labels = gen_le.fit_transform(poke_df['Generation']) poke_df['Gen_Label'] = gen_labels # transform and map pokemon legendary status leg_le = LabelEncoder() leg_labels = leg_le.fit_transform(poke_df['Legendary']) poke_df['Lgnd_Label'] = leg_labels poke_df_sub = poke_df[['Name', 'Generation', 'Gen_Label', 'Legendary', 'Lgnd_Label']] poke_df_sub.iloc[4:10] ''' Name Generation Gen_Label Legendary Lgnd_Label 4 Octillery Gen 2 1 False 0 5 Helioptile Gen 6 5 False 0 6 Dialga Gen 4 3 True 1 7 DeoxysDefense Forme Gen 3 2 True 1 8 Rapidash Gen 1 0 False 0 9 Swanna Gen 5 4 False 0 ''' # encode generation labels using one-hot encoding scheme gen_ohe = OneHotEncoder() gen_feature_arr = gen_ohe.fit_transform(poke_df[['Gen_Label']]).toarray() gen_feature_labels = list(gen_le.classes_) gen_features = pd.DataFrame(gen_feature_arr, columns=gen_feature_labels) # encode legendary status labels using one-hot encoding scheme leg_ohe = OneHotEncoder() leg_feature_arr = leg_ohe.fit_transform(poke_df[['Lgnd_Label']]).toarray() leg_feature_labels = ['Legendary_'+str(cls_label) for cls_label in leg_le.classes_] leg_features = pd.DataFrame(leg_feature_arr, columns=leg_feature_labels) # Next we have to concatenate the new dfs into the original df poke_df_ohe = pd.concat([poke_df_sub, gen_features, leg_features], axis=1) columns = sum([['Name', 'Generation', 'Gen_Label'],gen_feature_labels, ['Legendary', 'Lgnd_Label'],leg_feature_labels], []) poke_df_ohe[columns].iloc[4:10] # Dummy Coding Scheme ''' Another way of one hot encoding the categorical data is by dummy encoding. ''' gen_dummy_features = pd.get_dummies(poke_df['Generation'], drop_first=True) pd.concat([poke_df[['Name', 'Generation']], gen_dummy_features], axis=1).iloc[4:10] # Feature Hashing scheme unique_genres = np.unique(vg_df[['Genre']]) print("Total game genres:", len(unique_genres)) print(unique_genres) from sklearn.feature_extraction import FeatureHasher fh = FeatureHasher(n_features=6, input_type='string') hashed_features = fh.fit_transform(vg_df['Genre']) hashed_features = hashed_features.toarray() pd.concat([vg_df[['Name', 'Genre']], pd.DataFrame(hashed_features)], axis=1).iloc[1:7] ''' Name Genre 0 1 2 3 4 5 1 Super Mario Bros. Platform 0.0 2.0 2.0 -1.0 1.0 0.0 2 Mario Kart Wii Racing -1.0 0.0 0.0 0.0 0.0 -1.0 3 Wii Sports Resort Sports -2.0 2.0 0.0 -2.0 0.0 0.0 4 Pokemon Red/Pokemon Blue Role-Playing -1.0 1.0 2.0 0.0 1.0 -1.0 5 Tetris Puzzle 0.0 1.0 1.0 -2.0 1.0 -1.0 6 New Super Mario Bros. Platform 0.0 2.0 2.0 -1.0 1.0 0.0 '''
e9aabe0b86722a82aa5836d9d50cb4063613be9b
JoaquinRodriguez2006/Roboliga_2021
/Robot_movement.py
1,892
3.578125
4
from controller import Robot import time timeStep = 32 # Set the time step for the simulation max_velocity = 6.28 # Set a maximum velocity time constant nothing = 0 # Make robot controller instance robot = Robot() # Define the wheels wheel1 = robot.getDevice("wheel1 motor") # Create an object to control the left wheel wheel2 = robot.getDevice("wheel2 motor") # Create an object to control the right wheel # Set the wheels to have infinite rotation wheel1.setPosition(float("inf")) wheel2.setPosition(float("inf")) # Define distance sensors s5 = robot.getDevice("ps5") # adelante izquierda s7 = robot.getDevice("ps7") # costado izquierda s0 = robot.getDevice("ps0") # adelante derecha s2 = robot.getDevice("ps2") # costado derecha # Enable distance sensors N.B.: This needs to be done for every sensor s5.enable(timeStep) s7.enable(timeStep) s0.enable(timeStep) s2.enable(timeStep) def avanzar(vel): speed1 = vel speed2 = vel def girar_derecha(vel): speed1 = vel speed2 = -vel def girar_izquierda(vel): speed1 = -vel speed2 = vel def quieto(seg): time.sleep(seg) start = robot.getTime() while robot.step(timeStep) != -1: speed1 = max_velocity speed2 = max_velocity if (s7.getValue() > 0.1 and s0.getValue() > 0.1): # Pregunta si ve algo con alguno de los sensores de adelante. En ese caso, avanza. avanzar(max_velocity) print("avanzar") else: quieto(5) print("Quieto") # if (s7.getValue() < 0.1 and s0.getValue() < 0.1): # Si detecta algo con los sensores de adelante, pregunta si ve algo con los sensores de los costados # if (s2.getValue() < 0.1): # girar_derecha(vel) # if (s5.getValue() < 0.1): # girar_izquierda(vel) # Set the wheel velocity wheel1.setVelocity(speed1) wheel2.setVelocity(speed2)
a65617a5d14ea6e61b6a55bc01ca2b3f23d91ea3
kodsnack/advent_of_code_2019
/machalvan-python/utils.py
689
3.59375
4
def read_input(): input_file = open("../../input.txt", "r") lines = input_file.readlines() input_file.close() return lines def write_output(result): output_file = open("../../output.txt", "w") output_file.write(result) output_file.close() def check_result(result): answer_file = open("../../answer.txt", "r") answer = answer_file.read() if result == answer: print('CORRECT') else: if answer: print('EXPECTED') print(answer) print('ACTUAL') print(result) else: print('GUESS') print(result) answer_file.close()
ca0948d560615339cf62c20f98c87f875c3cc46f
596050/DSA-Udacity
/practice/data-structures/stacks/stack.py
378
3.71875
4
class Stack: def __init__(self): self.items = [] def size(self): return len(self.items) def push(self, value): self.items.append(value) def pop(self): return self.items and self.items.pop() def top(self): if self.items: return self.items[0] def is_empty(self): return len(self.items) == 0
1783baaf6e9a35bf53f833d37af41abef53b7ea8
lernerbruno/python-trainning-itc
/one_liners/filter_dividable.py
427
3.90625
4
""" It makes one liners functions Author: Bruno Lerner """ def filter_dividable(numbers, divisors): ''' for each number in the list provided, it checks if it is divisible by any of the divisor :param numbers: :param divisors: :return: ''' return [x for x in numbers if any([x % divisor == 0 for divisor in divisors])] if __name__ == "__main__": print(filter_dividable([1, 2, 3, 4, 5, 6], [2, 3]))
6be67c7b175f4166a8180c4c11edfb0dfca836d5
LogicalFish/DiscordBot
/python/modules/reminders/reminder_manager.py
1,056
3.5625
4
from datetime import datetime class ReminderManager: def __init__(self): self.reminders = [] def add_reminder(self, delta, message_string, target): self.reminders.append((datetime.now() + delta, message_string, target)) self.reminders.sort(key=lambda tup: tup[0]) def pop_reminder(self): """ Method to request a reminder. :return: The first reminder in the queue, if it is ready. False if no reminder is ready. """ if self.reminders and self.reminders[0][0] < datetime.now(): return self.reminders.pop(0) else: return False def get_all_reminders(self): """ This method will check if any reminders need to be sent. :return: A list of reminders that need to be sent. """ list_of_reminders = [] next_reminder = self.pop_reminder() while next_reminder: list_of_reminders.append(next_reminder) next_reminder = self.pop_reminder() return list_of_reminders
5848eb28061158df60002a40ed1dd7889cef2236
roechi/advent_of_code_2019
/day_1/fuel_calc.py
635
3.5625
4
from functools import reduce from math import floor def calculate_fuel(weight: int) -> int: return floor(weight / 3) - 2 def calculate_fuel_for_many(weights: [int]) -> int: fuel_results = list(map(calculate_fuel, weights)) return reduce(lambda l, r: l + r, fuel_results, 0) def calculate_fuel_recursively(weight: int) -> int: fuel = calculate_fuel(weight) return 0 if fuel <= 0 else fuel + calculate_fuel_recursively(fuel) def calculate_fuel_for_many_recursively(weights: [int]) -> int: fuel_results = list(map(calculate_fuel_recursively, weights)) return reduce(lambda l, r: l + r, fuel_results, 0)
0ac8ee75c140e24ac2470b9a23cc9bb07f6fd4af
batra98/Mario_Testing
/20171114_assignment3/20171114_part1/Refactored/start_screen.py
2,200
3.78125
4
"""gaurav""" import color class Start(object): """gaurav""" def __init__(self, height, width): self.height = height self.width = width self.start_screen = \ [" ____ ___ ___ ___", \ "| | || || | | Instructions:", \ "|____ | ||___||___ |___|", \ " || || | | \\ 1) Press E to start the Easy mode" \ +"or H to start the Hard mode", \ " ____||___|| |___ | \\ 2) Press R to restart the Game", \ " 3) Press Q to quit the Game", \ " ___ ___ ___ ___", \ "|\\ /|| || | | | | Controls:", \ "| \\/ ||___||___| | | |", \ "| || || \\ | | | 1) Use WAD to move the player", \ "| || || \\ _|_ |___| 2) Use F to shoot"+ \ "(can be used in super mode)", ""] self.mario_start = [] def initialize(self): """gaurav""" temp = [] temp_2 = [] for i in range(0, self.height-1): for j in range(0, self.width): j = j if i == 0: temp.append("*") elif i >= self.height-3: temp.append("#") else: temp.append(" ") self.mario_start.append(temp) temp = [] for i in range(0, self.width): temp_2.append("*") self.mario_start.append(temp_2) def draw(self): """gaurav""" for gabru in range(0, self.height): print(color.getcolor("*"), end="") for hello in range(0, self.width): print(color.getcolor(self.mario_start[gabru][hello]), end="") print(color.getcolor("*")) def label(self): """gaurav""" for i in range(0, 11): for j in range(0, len(self.start_screen[i])): self.mario_start[int( self.height/4)+i][int(self.width/12)+j] = self.start_screen[i][j]
139547a2a8793101bdd8d6cb8b57190a9e9118a6
peterwj/advent-of-code-2015
/day11.py
2,259
3.6875
4
#!/usr/bin/python import sys import unittest class TestDay11(unittest.TestCase): def test_check_validity(self): assert(includes_run('hijklmmn')) self.assertFalse(no_verboten_letters('hijklmmn')) assert(includes_two_pairs('abbceffg')) self.assertFalse(includes_run('abbceffg')) def test_next_password(self): assert(next_password('xz') == 'ya') assert(next_password('xx') == 'xy') def test_find_new_password(self): assert(find_new_password('abcdefgh') == 'abcdffaa') assert(find_new_password('ghijklmn') == 'ghjaabcc') def check_validity(password): return ( includes_run(password) and no_verboten_letters(password) and includes_two_pairs(password) ) def no_verboten_letters(password): return ( 'i' not in password and 'o' not in password and 'l' not in password ) def includes_run(password): for i in range(len(password) - 2): if ( ord(password[i]) == ord(password[i+1]) - 1 and ord(password[i]) == ord(password[i+2]) - 2 ): return True return False def includes_two_pairs(password): first = find_pair(password) if not first: return False second = find_pair(password, forbidden=first) if not second: return False return True def find_pair(password, forbidden=None): for i in range(len(password) - 1): if password[i] == password[i+1] and password[i] != forbidden: return password[i] return None def find_new_password(password): password = next_password(password) while not check_validity(password): password = next_password(password) return password def next_password(password): password = list(password) carry = False i = len(password) - 1 c = ord(password[i]) + 1 while i >= 0: if c <= ord('z'): password[i] = chr(c) break else: password[i] = 'a' i -= 1 c = ord(password[i]) + 1 return "".join(password) if __name__ == '__main__': if len(sys.argv) < 2: unittest.main() print(find_new_password(sys.argv[1]))
69f18d8c28ec972c7d7ec1285548d288b0448374
priscilafraser/AtividadesModulo1
/Exercicio 11.05.2021/exercicio6.py
599
3.8125
4
""" def ficha(jogador='Não informado', gols=-1): print('-'*40) print(f'{"Jogador":<20}{"Gols":<20}') if gols == -1: print(f'{jogador:<20}{"Não informado":<20}') else: print(f'{jogador:<20}{gols:<20}') ficha() ficha('ana') ficha(gols=5) ficha('marta', 3) """ """ def notas(a,b,c): med=(a+b+c)/3 print('a media das 3 notas') lista=[a,b,c] min(lista) medaltas=((a+b+c)-(min(lista)))/2 max(lista) print('a nota mais alta{max(lista)}') print('a nota mais alta{max(lista)}') print('a nota mais alta{max(lista)}') """ def calculadora(notas)
39f094b71fee416dc5694c1b7c9e07e184af423f
niki1729/AutoCar
/Tests/FirstAttempt/MotorsWork/turn.py
391
3.65625
4
import os class Turn: """ This class works or with arduino or with the motors directly through relays and turn right or left """ def __init__(self): self.IN1 = 6 # IN1 self.IN2 = 13 # IN2 self.IN3 = 19 # IN3 self.IN4 = 26 # IN4 def turn_right(self): print('turn_right') def turn_left(self): print('turn_left')
067b9ed55f2223cf4cf7a480db4fbf6408b566dc
kuroitenshi9/Xmass-python
/10/10.py
569
3.890625
4
''' Zaznacz prawidłowe odpowiedz/i: The first snippet leaves the file open whereas the second does not. The second snippet iterates more efficiently through the file. The second snippet opens the file for reading and writing blocks whereas the first only for reading. The second snippet opens the file for reading and writing blocks whereas the first only for reading. None of above ''' #first snippet with open('file.txt', 'r') as f: for line in f: print(line) #second snipped f = open('file.txt', 'rb') for line in f.xreadlines(): print(line) f.close()
faa61d915b009e4748001eff219c448c16228dc6
encdec2020/Python-BlockPy
/bouncingballrevised.py
1,035
3.765625
4
import pygame import time pygame.init() # set up the drawing window screen = pygame.display.set_mode((500, 300)) y = 0 x = 0 running = True increment = 1 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() else: while y <= 300: screen.fill((255, 255, 0)) # draw a circle of colour (red=255,0,0 and x =255,y =0,1,.. radius=13,thickness=0 pygame.draw.circle(screen, (255, 0, 0), (250, y), 13, 0) pygame.display.update() # increment y to move ahead y = y + increment # add sleep to reduce speed of ball time.sleep(0.006) # when y hits border decrement if y == 300: increment = -1 break # else increment elif y == 0: increment = 1 break else: y = y + increment break pygame.display.flip() pygame.quit()
4ec4f2c4e8a152d1340fd911cf2d561c2b22561a
DavidStoilkovski/python-fundamentals
/text-processing-fundamentals/activation_keys.py
1,180
3.71875
4
key = input() line = input() while not line == "Generate": line = line.split(">>>") command = line[0] if command == "Contains": substring = line[1] if substring in key: print(f'{key} contains {substring}') else: print("Substring not found!") elif command == "Flip": action = line[1] start = int(line[2]) end = int(line[3]) if action == "Upper": original = [key[i] for i in range(start, end)] original = "".join(original) to_replace = original.upper() key = key.replace(original, to_replace) print(key) else: original = [key[i] for i in range(start, end)] original = "".join(original) to_replace = original.lower() key = key.replace(original, to_replace) print(key) elif command == "Slice": start = int(line[1]) end = int(line[2]) remove = [key[i] for i in range(start, end)] remove = "".join(remove) key = key.replace(remove, "") print(key) line = input() print(f"Your activation key is: {key}")
dd7d4cb8b051a5a455d64bb394bb12032360c12a
RaulNinoSalas/Programacion-practicas
/Practica7/P7E7.py
619
4.03125
4
"""RAUL NIO SALAS DAW 1 Ejercicio_07 Escribe un programa que lea una frase, y la pase como parmetro a un procedimiento. El procedimiento contar el nmero de vocales (de cada una) que aparecen, y lo imprimir por pantalla. """ nombre=raw_input("Dime una frase ") def cuantos (): conta1=nombre.count("a") conta2=nombre.count("e") conta3=nombre.count("i") conta4=nombre.count("o") conta5=nombre.count("u") print "Hay "+str(conta1)+" a" print "Hay "+str(conta2)+" e" print "Hay "+str(conta3)+" i" print "Hay "+str(conta4)+" o" print "Hay "+str(conta5)+" u" cuantos()
cd0ac69ca101c22ecd6053681c4e76a43ff3575b
doer001/Programs66
/58.2左旋转字符串.py
723
3.796875
4
''' ******************************************************************** 题目描述 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如, 字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。 ******************************************************************** ''' # -*- coding:utf-8 -*- class Solution: def LeftRotateString(self, s, n): if not s: return '' if n > len(s): n %= len(s) return s[n:]+s[:n] ''' ******************************************************************** 解题思路: ******************************************************************** '''
2f3c1479763fcb5c63c3ae3d48885b51b08e46c7
bjknbrrr/hillel_kiseev
/lesson_04/op_continue.py
304
4.15625
4
# i = 0 # while i < 100: # i += 1 # if i % 3 == 0: # continue # # print(i) num = int(input('Please enter a number: ')) while num != 0: if num < 0: break print('Your number:', num) num = int(input('Please enter a number: ')) else: print('No negative value.')
d9c6923b80d8faeabbd9bdd0387b6c1d703a5196
rahuljngr/My-Projects
/A4_GUI_App/frontend.py
2,928
4.03125
4
''' A program that stores this book information: Title, Author Year , ISBN User can: View all records Search an Entry Add entry Update entry Delete Close ''' from tkinter import * import backend def get_selected_row(event): try: global selected_tuple index=list1.curselection()[0] selected_tuple=list1.get(index) e1.delete(0,END) e1.insert(END,selected_tuple[1]) e2.delete(0,END) e2.insert(END,selected_tuple[2]) e3.delete(0,END) e3.insert(END,selected_tuple[3]) e4.delete(0,END) e4.insert(END,selected_tuple[4]) except IndexError: pass def view_command(): list1.delete(0,END) for row in backend.view(): list1.insert(END,row) def search_command(): list1.delete(0,END) for row in backend.search(title_text.get(),author_text.get(),year_text.get(),isbn_text.get()): list1.insert(END,row) def add_command(): backend.insert(title_text.get(),author_text.get(),year_text.get(),isbn_text.get()) list1.delete(0,END) list1.insert(END,(title_text.get(),author_text.get(),year_text.get(),isbn_text.get())) def delete_command(): backend.delete(selected_tuple[0]) def update_command(): backend.update(selected_tuple[0],title_text.get(),author_text.get(),year_text.get(),isbn_text.get()) window = Tk() window.wm_title("BookStore") l1 = Label(window, text = "Tilte") l1.grid(row=0,column=0) l2 = Label(window, text = "Author") l2.grid(row=0,column=2) l3 = Label(window, text = "Year") l3.grid(row=1,column=0) l4 = Label(window, text = "ISBN") l4.grid(row=1,column=2) title_text = StringVar() e1 = Entry(window, textvariable =title_text) e1.grid(row=0,column =1) author_text = StringVar() e2 = Entry(window, textvariable =author_text) e2.grid(row=0,column =3) year_text = StringVar() e3 = Entry(window, textvariable =year_text) e3.grid(row=1,column =1) isbn_text = StringVar() e4 = Entry(window, textvariable =isbn_text) e4.grid(row=1,column =3) list1 = Listbox(window, height =6, width =35) list1.grid(row=2,column=0, rowspan =6, columnspan =2) list1.bind('<<ListboxSelect>>',get_selected_row) sb1 = Scrollbar(window) sb1.grid(row =2,column =2,rowspan =6) list1.configure(yscrollcommand = sb1.set) sb1.configure(command = list1.yview) b1 = Button(window, text = "View all",width =12,command =view_command) b1.grid(row = 2, column =3) b2 = Button(window, text = "Search entry",width =12,command = search_command) b2.grid(row = 3, column =3) b3 = Button(window, text = "Add entry",width =12, command = add_command) b3.grid(row = 4, column =3) b4 = Button(window, text = "Update",width =12, command = update_command) b4.grid(row = 5, column =3) b5 = Button(window, text = "Delete",width =12,command = delete_command) b5.grid(row = 6, column =3) b6 = Button(window, text = "Close",width =12,command = window.destroy) b6.grid(row = 7, column =3) window.mainloop()
a7d54b3a0ae666bcbd3c3d141029b1576956413c
philwade/Euler
/euler7.py
441
3.890625
4
#By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. #What is the 10001st prime number? start = 3 count = 2 import math def is_prime(num): start = 2 end = int(math.ceil(math.sqrt(num))) for n in range(start, end + 1): if num % n == 0: return False return True while count < 10001: start += 2 if is_prime(start): count += 1 print start
9901363aec80b3b3f452b1096b841e1badd34ec1
gabrieltren/urionline
/1257.py
1,649
3.609375
4
def posicaoN(letra): if letra == 'A': return 0 elif letra == 'B': return 1 elif letra == 'C': return 2 elif letra == 'D': return 3 elif letra == 'E': return 4 elif letra == 'F': return 5 elif letra == 'G': return 6 elif letra == 'H': return 7 elif letra == 'I': return 8 elif letra == 'J': return 9 elif letra == 'K': return 10 elif letra == 'L': return 11 elif letra == 'M': return 12 elif letra == 'N': return 13 elif letra == 'O': return 14 elif letra == 'P': return 15 elif letra == 'Q': return 16 elif letra == 'R': return 17 elif letra == 'S': return 18 elif letra == 'T': return 19 elif letra == 'U': return 20 elif letra == 'V': return 21 elif letra == 'W': return 22 elif letra == 'X': return 23 elif letra == 'Y': return 24 elif letra == 'Z': return 25 return 0 def valorTotal(hash, elem): valor = 0 for i in range(len(hash)): valor += posicaoN(hash[i]) + elem + i return valor def vrec(hash, elem, e): if hash == []: return 0 else: return posicaoN(hash.pop(0)) + elem + e + vrec(hash,elem,(e+1)) n = int(input()) total = 0 for i in range(n): a = int(input()) for k in range(a): hash = input() total += vrec(list(hash), k, 0) print(total) total = 0
5c860a1e82d09dbf352992b597a60963560b4aa0
telelvis/projecteuler
/projecteuler/problem4.py
497
3.734375
4
#!/usr/bin/python """ (c) projecteuler.net Largest palindrome product Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. """ for i in range(999, 900, -1): num = int(str(i)+ str(i)[::-1]) for j in range(999, 900, -1): if num%j == 0 and num/j<1000: print num break
2f831d5efaf0c47929f86681239d7b3255d22677
alinemitri/Python_para_zumbis
/Lista_II/L2E2.py
280
3.796875
4
ano = int( input ('Digite o ano: ')) if ano % 4 != 0 : print ('O ano %d não é bissexto!' %ano) elif ano % 100 != 0 : print ('O ano %d é bissexto!' %ano) elif ano % 400 != 0 : print ('O ano %d não é bissexto!' %ano) else : print ('O ano %d é bissexto!' %ano)
ca3fc1769382eb8a55ae6b15f0086266d81102f9
duong22/Test_Task_Neuro
/Test_Task_LD_Flask/src/yandex_geocoder.py
3,555
3.53125
4
from decimal import Decimal from typing import Tuple import requests import json from math import sin, cos, sqrt, atan2, radians from src.exceptions import InvalidKey, NothingFound, UnexpectedResponse class YandexGeocoder(object): def __init__(self, api_key): self.api_key = api_key self.long_moscow_ring_road, self.lat_moscow_ring_road = self.find_coordinates(address="Moscow Ring Road") def request_geocoder(self, location): """Send request to yandex_geocoder API Args: location: str, location could be address or 'longitude, latitude' Returns: json response from yandex_geocoder API """ response = requests.get( "https://geocode-maps.yandex.ru/1.x/", params=dict(format="json", apikey=self.api_key, geocode=location, lang='en_RU'), ) if response.status_code == 200: return response.json()["response"] elif response.status_code == 400: raise InvalidKey() else: raise UnexpectedResponse( f"status_code={response.status_code}, body={response.content}" ) def find_coordinates(self, address=None) -> Tuple[Decimal]: """Find coordinates from address using request_geocoder function Args: address: str, address that want to find coordinates Returns: longitude, latitude """ data = self.request_geocoder(address)["GeoObjectCollection"]["featureMember"] if not data: raise NothingFound(f'Nothing found for "{address}"') coordinates = data[0]["GeoObject"]["Point"]["pos"] # type: str longitude, latitude = tuple(coordinates.split(" ")) return Decimal(longitude), Decimal(latitude) def find_address(self, longitude=None, latitude=None) -> str: """Find address from coordinates using request_geocoder function Args: longitude: str latitude: str Returns: address from coordinates """ coordinates = str(longitude) + ',' + str(latitude) data = self.request_geocoder(coordinates)["GeoObjectCollection"]["featureMember"] if not data: raise NothingFound(f'Nothing found for "{longitude}, {latitude}"') return data[0]["GeoObject"]["metaDataProperty"]["GeocoderMetaData"]["text"] def calculate_distance(self, address=None): """Find distance from Moscow Ring Road to some address Args: longitude: str latitude: str address: str Returns: distance calculated in miles """ # find longitude and latitude from given address if address is not None: longitude, latitude = self.find_coordinates(address=address) address = self.find_address(longitude=longitude, latitude=latitude) # check is address in MKAD or not if "MKAD" in address: return 0 else: R = 6373.0 lat1 = radians(self.lat_moscow_ring_road) lon1 = radians(self.long_moscow_ring_road) lat2 = radians(latitude) lon2 = radians(longitude) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return distance
bd914ec7b2550d6c1aae0509a9b68702aaf5ee11
Musokeking/projects
/dictionary.py
84
3.828125
4
x=0 dict={} for x in range(x,15): sqrt= x**2 dict[x]=sqrt print(dict)
ab0e6193637d06ff7f25c911df386258cb71c031
fxpxzh/pythonStu
/PythonTest/src/com/fangxp/func/sortedFucTest.py
379
3.59375
4
# -*- coding: utf-8 -*- ''' Created on Mar 22, 2016 @author: xianpanfang ''' L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88),('adb',99)] def by_score(t): return t[1] L2 = sorted(L, key=by_score,reverse=True) print(L2) def by_name(t): return t[0].lower() #str.lower(t[0]) L3 = sorted(L,key=by_name,reverse = True) print(L3) print('hello')
10f93d2044eda8d6840069224491a862dc71dcff
gaoxuboy/cs
/questionnaire/x1.py
1,700
3.875
4
# 什么是可迭代对象?其中含有__iter__方法,返回迭代器 # 什么是迭代器? """ 1. 自定义可迭代对象 class Foo(object): def __init__(self,arg): self.arg = arg def __iter__(self): return iter([11,22,33,44,55]) obj = Foo("as") for row in obj: print(row) """ # class Foo(object): # # def __init__(self,arg): # self.arg = arg # # def __iter__(self): # yield '开始' # for item in self.arg: # yield item # yield '结束' # obj = Foo([11,22,33,44]) # # # 去循环一个含有__iter__方法的对象时,会执行__iter__方法,获取返回值 # # 在进行for循环:next... # for row in obj: # print(row) # 什么是可迭代对象?其中含有__iter__方法,返回迭代器 # 什么是迭代器? 含有__next__方法 # iter([1,2,3,4,54]) # 什么是生成器? 函数中含有yield关键字的函数,被执行后是生成器;含有__next__方法 # def func(): # yield 1 # yield 2 # 什么是可迭代对象?其中含有__iter__方法,返回【迭代器;生成器】 # class Foo(object): # def __iter__(self): # return iter([11,22,3,4]) # def __iter__(self): # yield 1 # yield 2 # yield 3 # import requests # # # requests.get( # url='http://127.0.0.1:8001/score/1/1/' # ) # # requests.post( # url='http://127.0.0.1:8001/score/1/1/', # data={'username':'alex','pwd':123} # ) # class Foo(object): def __add__(self, other): return 999 obj1 = Foo() obj2 = Foo() obj3 = obj1 + obj2 # 自动触发 obj1的 __add__方法(obj2) print(obj3) # c = 1 + 2 # print(c)