blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
371d862ac49e9c80dc0095451b52f2610094317a
anuragull/algorithms
/leetcode/15.3Sum.py
1,497
3.765625
4
""" Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] """ #constraints : negative number # idea : sort the first, then class Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ total_len = len(nums) if total_len < 3: return [] # sort nums = sorted(nums) valid_values = set() solution_list = {} for i in range(total_len -2 ): cur_val = nums[i] if cur_val in valid_values: continue l = i + 1 r = total_len -1 while l < r : total = cur_val + nums[l] + nums[r] if total == 0: valid_values.add(cur_val) key = "%d_%d_%d" % (cur_val, nums[l], nums[r]) if key not in solution_list: solution_list[key] = [cur_val, nums[l], nums[r]] l = l + 1 r = r - 1 elif total < 0: l = l+1 else: r = r - 1 return list(solution_list.values())
8cf101d9ea1e087e8205480d38ff760f2755762e
kmadathil/sanskrit_parser
/sanskrit_parser/parser/sandhi.py
11,621
4.0625
4
# -*- coding: utf-8 -*- """ Intro ===== Sandhi splitter for Samskrit. Builds up a database of sandhi rules and utilizes them for both performing sandhi and splitting words. Will generate splits that may not all be valid words. That is left to the calling module to validate. See for example SanskritLexicalAnalyzer Example usage: from sandhi import Sandhi sandhi = Sandhi() joins = sandhi.join('tasmin', 'iti') splits = sandhi.split_at('tasminniti', 5) Draws inspiration from https://github.com/sanskrit/sanskrit @author: Avinash Varna (github: @avinashvarna) Usage ===== The ``Sandhi`` class can be used to join/split words: .. code:: python >>> from sanskrit_parser.parser.sandhi import Sandhi >>> sandhi = Sandhi() >>> word1 = SanskritImmutableString('te') >>> word2 = SanskritImmutableString('eva') >>> joins = sandhi.join(word1, word2) >>> for join in joins: ... print(join) ... teeva taeva ta eva tayeva To split at a specific position, use the ``Sandhi.split_at()`` method: .. code:: python >>> w = SanskritImmutableString('taeva') >>> splits = sandhi.split_at(w, 1) >>> for split in splits: ... print(split) ... (u'tar', u'eva') (u'tas', u'eva') (u'taH', u'eva') (u'ta', u'eva') To split at all possible locations, use the ``Sandhi.split_all()`` method: .. code:: python >>> splits_all = sandhi.split_all(w) >>> for split in splits_all: ... print(split) ... (u't', u'aeva') (u'tar', u'eva') (u'taev', u'a') (u'to', u'eva') (u'ta', u'eva') (u'te', u'eva') (u'taH', u'eva') (u'tae', u'va') (u'taeva', u'') (u'tas', u'eva') **Note**: As mentioned previously, both over-generation and under-generation are possible with the ``Sandhi`` class. Command line usage ================== :: $ python -m sanskrit_parser.parser.sandhi --join te eva Joining te eva set([u'teeva', u'taeva', u'ta eva', u'tayeva']) $ python -m sanskrit_parser.parser.sandhi --split taeva 1 Splitting taeva at 1 set([(u'tar', u'eva'), (u'tas', u'eva'), (u'taH', u'eva'), (u'ta', u'eva')]) $ python -m sanskrit_parser.parser.sandhi --split taeva --all All possible splits for taeva set([(u't', u'aeva'), (u'tar', u'eva'), (u'taev', u'a'), (u'to', u'eva'), (u'ta', u'eva'), (u'te', u'eva'), (u'taH', u'eva'), (u'tae', u'va'), (u'taeva', u''), (u'tas', u'eva')]) """ import itertools import pickle import logging import datetime from zipfile import ZipFile from sanskrit_parser.base.sanskrit_base import SanskritNormalizedString, outputctx from sanskrit_parser.util.data_manager import data_file_path class Sandhi(object): """ Class to hold all the sandhi rules and methods for joining and splitting. Uses SLP1 encoding for all internal operations. """ def __init__(self, rules_dir=None, use_default_rules=True, logger=None): """ Sandhi class constructor :param rules_dir: directory to read rules from :param use_default_rules: reads pre-built-rules from sandhi_rules dir under module directory :param logger: instance of python logger to use """ self.forward = None self.backward = None self.logger = logger or logging.getLogger(__name__) @staticmethod def _load_rules_pickle(filename): zip_path = data_file_path('sandhi_rules.zip') with ZipFile(zip_path) as myzip: with myzip.open(filename) as f: return pickle.load(f) def _load_forward(self): if self.forward is None: self.forward = self._load_rules_pickle('sandhi_forward.pkl') keys = self.forward.keys() self.lc_len_max = max(len(k[0]) for k in keys) self.rc_len_max = max(len(k[1]) for k in keys) def _load_backward(self): if self.backward is None: self.backward = self._load_rules_pickle('sandhi_backward.pkl') keys = self.backward.keys() self.after_len_max = max(len(k) for k in keys) def join(self, first_in, second_in): """ Performs sandhi. **Warning**: May generate forms that are not lexically valid. :param first_in: SanskritImmutableString first word of the sandhi :param second_in: SanskritImmutableString word of the sandhi :return: list of strings of possible sandhi forms, or None if no sandhi can be performed """ self._load_forward() first = first_in.canonical() second = second_in.canonical() self.logger.debug("Join: {}, {}".format(first, second)) if first is None or len(first) == 0: return second if second is None: return first left_chars = [first[i:] for i in range(max(0, len(first)-self.lc_len_max), len(first))] left_chars.append("^"+first) right_chars = [second[0:i] for i in range(min(self.rc_len_max, len(second))+1)] self.logger.debug("left_chars = %s, right_chars %s", left_chars, right_chars) joins = set() for key in itertools.product(left_chars, right_chars): afters = self.forward.get(key) if afters: for after, annotation in afters: self.logger.debug("Found sandhi %s = %s (%s)", key, after, annotation) joins.add(first[:-len(key[0])] + after + second[len(key[1]):]) if len(joins) == 0: self.logger.debug("No joins found") return None else: return joins def split_at(self, word_in, idx): """ Split sandhi at the given index of word. **Warning**: Will generate splits that are not lexically valid. :param word_in: SanskritImmutableString word to split :param idx: position within word at which to try the split :return: set of tuple of strings of possible split forms, or None if no split can be performed """ self._load_backward() word = word_in.canonical() self.logger.debug("Split: %s, %d", word, idx) splits = set() # Figure out how may chars we can extract for the afters stop = min(idx+self.after_len_max, len(word)) afters = [word[idx:i] for i in range(idx+1, stop+1)] for after in afters: self.logger.debug("Trying after %s", after) befores = self.backward[after] if befores: for before, annotation in befores: self.logger.debug("Found split %s -> %s (%s)", after, before, annotation) # Do we have a beginning-of-line match rule if before[0][0] == "^": if idx != 0: # Can't allow matches at any other position continue else: # drop the ^ in the result before = (before[0][1:], before[1]) left = word[:idx] + before[0] right = before[1] + word[idx+len(after):] splits.add((left, right)) if len(splits) == 0: self.logger.debug("No split found") return None else: return splits def split_all(self, word_in, start=None, stop=None): """ Split word at all possible locations and return splits. **Warning**: Will generate splits that are not lexically valid. :param word_in: SanskritImmutableString word to split :return: set of tuple of strings of possible split forms, or None if no split can be performed """ splits = set() word = word_in.canonical() start = start or 0 stop = stop or len(word) for idx in range(start, stop): split = self.split_at(word_in, idx) if split: splits |= split if len(splits) == 0: self.logger.debug("No split found") return None else: return splits if __name__ == "__main__": from argparse import ArgumentParser def getArgs(): """ Argparse routine. Returns args variable """ # Parser Setup parser = ArgumentParser(description='Sandhi Utility') # Input Encoding (autodetect by default) parser.add_argument('--input-encoding', type=str, default=None) parser.add_argument('--loglevel', type=str, help="logging level. Can be any level supported by logging module") parser.add_argument('--split', action='store_true', help="Split the given word using sandhi rules") parser.add_argument('--join', action='store_true', help="Join the given words using sandhi rules") parser.add_argument('--all', action='store_true', help="Return splits at all possible locations") parser.add_argument('--strict-io', action='store_true', help="Do not modify the input/output string to match conventions", default=False) # String to encode parser.add_argument('word', nargs='?', type=str, default="tasminniti", help="First word of sandhi if join, or word to split") parser.add_argument('word_or_pos', nargs="?", type=str, default="eva", help="Second word of sandhi if join, or position to split") return parser.parse_args() def main(): args = getArgs() if args.input_encoding is None: ie = None else: ie = args.input_encoding # Setup logging if args.loglevel: numeric_level = getattr(logging, args.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % args.loglevel) logging.basicConfig(filename="sandhi.log", filemode="w", level=numeric_level) logging.info("---------------------------------------------------") logging.info("Started processing at %s", datetime.datetime.now()) sandhi = Sandhi() # if neither split nor join is chosen, just demo both if not args.split and not args.join: print("Neither split nor join option chosen. Here's a demo of joining") args.join = True with outputctx(args.strict_io): if args.split: word_in = SanskritNormalizedString(args.word, encoding=ie, strict_io=args.strict_io) if args.all: print("All possible splits for {}".format(args.word)) splits = sandhi.split_all(word_in) else: pos = int(args.word_or_pos) print("Splitting {0} at {1}".format(args.word, pos)) splits = sandhi.split_at(word_in, pos) print(splits) if args.join: print("Joining {0} {1}".format(args.word, args.word_or_pos)) first_in = SanskritNormalizedString(args.word, encoding=ie, strict_io=args.strict_io) second_in = SanskritNormalizedString(args.word_or_pos, encoding=ie, strict_io=args.strict_io) joins = sandhi.join(first_in, second_in) print(joins) logging.info("Finished processing at %s", datetime.datetime.now()) logging.info("---------------------------------------------------") logging.shutdown() main()
e8234258252f633baef8f390fc32e5db2049ebed
prabhupant/python-ds
/data_structures/bst/dfs_recursion.py
615
3.734375
4
class Node(): def __init__(self, val): self.val = val self.left = None self.right = None # Depth First Search def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) def postorder(root): if root: postorder(root.left) postorder(root.right) print(root.val) def preorder(root): if root: print(root.val) postorder(root.left) postorder(root.right) root = Node(3) root.left = Node(2) root.right = Node(4) root.left.left = Node(1) root.right.right = Node(5) inorder(root)
08585d156fed8de6ed7b104ab73aab97f135c625
mpresto/dojo
/python_stack/_python/OOP/chaining.py
1,246
4.09375
4
class User: """A Class for bank users""" def __init__(self, username, email_address): self.name = username self.email = email_address self.account_balance = 0 def make_deposit(self, amount): self.account_balance += amount return self def make_withdrawal(self, amount): self.account_balance -= amount return self def display_user_balance(self): # print the user's name and account balance to the terminal print('Name:', self.name, '\nAccount Balance: $', self.account_balance) return self def transfer_money(self, other_user, amount): self.account_balance -= amount other_user.account_balance += amount return self monty = User('Monty Python', 'monty@python.com') rowan = User('Rowan Atkinson', 'rowan@bean.com') john = User('John Cleese', 'john@fawltytowers.com') monty.make_deposit(100).make_deposit(75).make_deposit(150).make_withdrawal(65).display_user_balance() rowan.make_deposit(95).make_deposit(175).make_withdrawal(25).make_withdrawal(50).display_user_balance() john.make_deposit(325).make_withdrawal(50).make_withdrawal(15).make_withdrawal(100).display_user_balance() monty.transfer_money(john, 75).display_user_balance() john.display_user_balance()
66629c477b96fadafe7559ff4750794d0dcf45ea
LandenBrown/ProjectFrog
/src/frog_species.py
4,351
3.953125
4
import random class Frog: def __init__(self, name, external_attributes, internal_attributes, days_alive, lifespan_days, days_without_food, starvation_days, is_dead, mate_chance, infertile): self.name = name self.external_attributes = external_attributes self.internal_attributes = internal_attributes self.days_alive = days_alive self.lifespan_days = lifespan_days self.days_without_food = days_without_food self.starvation_days = starvation_days self.is_dead = is_dead self.mate_chance = mate_chance self.infertile = infertile def checkLifespan(self): #Check to see if the frog has died of old age yet. self.days_alive+=1 if self.days_alive >= self.lifespan_days: print("################################### A FROG HAS DIED OF OLD AGE") self.is_dead = True #####Kill frog def checkStarvation(self): #check to see if the frog has died of starvation. if self.days_without_food >= self.starvation_days: print("################################### A FROG HAS DIED OF STARVATION") ######Kill frog self.is_dead = True def checkMating(self): #Check to see if the frog is fertile or not if self.infertile == True: #print("This frog is infertile") pass else: #generate random number between 1-100 for mate chance potential comparison mateComparison = random.randint(1,100) if self.mate_chance >= mateComparison: #print("######################### A NEW FROG CAN MATE") return True else: return False def Mate(self, x, initializeFrog): #Grab an internal and external attribute from the other frog new_int_att = x.internal_attributes[0] new_ext_att = x.external_attributes[0] #Grab an internal and external attribute from myself self_int_att = self.internal_attributes[0] self_ext_att = self.external_attributes[0] #Combine the lists into an interal_atts list and an eternal_atts list internal_atts = [] internal_atts.append(new_int_att) internal_atts.append(self_int_att) external_atts = [] external_atts.append(new_ext_att) external_atts.append(self_ext_att) return initializeFrog(internal_atts, external_atts) def findFood(self, biome): #Make sure you're alive and not dead of old age. self.checkLifespan() #Generate a random number foodRandom = random.randint(1, 100) #Is the biome food density low if biome.food_density == "Low": #5% chance of finding food that day if foodRandom >= 95: #print("We have found food.") #Set days without food to 0 self.days_without_food = 0 else: #print("We have not found food today.") #Set days without food to + 1 self.days_without_food += 1 #check starvation status self.checkStarvation() #Is the biome food density standard if biome.food_density == "Standard": #10% chance of finding food that day if foodRandom >= 90: #print("We have found food.") #Set days without food to 0 self.days_without_food = 0 else: #print("We have not found food today.") #Set days without food to + 1 self.days_without_food += 1 #check starvation status self.checkStarvation() #Is the biome food density high if biome.food_density == "High": #15% chance of finding food that day if foodRandom >= 85: #print("We have found food.") #Set days without food to 0 self.days_without_food = 0 else: #print("We have not found food today.") #Set days without food to + 1 self.days_without_food += 1 #check starvation status self.checkStarvation()
02a5b163f5a83d037d3d50cb73db148b69df6521
coderMaruf/Problem_solving
/1021.py
326
3.515625
4
#Banknotes and Coins a = float(input()) print('NOTAS:') for i in [100,50,20,10,5,2]: print(f'{int(a/i)} nota(s) de R$ {i}.00') a = float(f'{a%i:.2f}') # print (a) print('MOEDAS:') for i in [1.00,0.50,0.25,0.10,0.05,0.01]: print(f'{int(a/i)} moeda(s) de R$ {i:.2f}') a = float(f'{a % i:.2f}') # print (a)
3e42962f01b5950ffac1e82bc802a10d9c73225e
alf808/python-labs
/01_python_fundamentals/01_07_area_perimeter.py
419
4.03125
4
''' Write the necessary code to display the area and perimeter of a rectangle that has a width of 2.4 and a height of 6.4. ''' rectangle_width = 2.4 rectangle_height = 6.4 rectangle_area = rectangle_width * rectangle_height rectangle_perimeter = rectangle_width * 2 + rectangle_height * 2 print(f"Area of a 2.4 by 6.4 rectangle: {rectangle_area}") print(f"Perimeter of a 2.4 by 6.4 rectangle: {rectangle_perimeter}")
e3a38ceb0859d518f4fa4c56fd59e30bc66c3211
gscr10/Python_study
/r_26_文件目录管理操作.py
373
3.703125
4
# 文件目录操作 # 导入 os模块 import os # 文件操作 os.rename("test.txt", "Test.txt") # os.remove() # 目录操作 print(os.listdir(".")) # eval函数 # 将字符串当成有效的表达式,并返回计算结果 # 不要使用eval函数直接转换 input 的结果 # 案例:计算器 input_str = input("请输入算术题:") print(eval(input_str))
7989259788936ab2041acec7df842b72e75eebc8
amitsingh790634/tathastu_week_of_code
/day1/program5.py
903
4.03125
4
run_player1=int(input("Enter the run scored by player1 in 60 balls: ")) run_player2=int(input("Enter the run scored by player2 in 60 balls: ")) run_player3=int(input("Enter the run scored by player3 in 60 balls: ")) strikerate1=run_player1 * 100/60 strikerate2=run_player2 * 100/60 strikerate3=run_player3 * 100/60 print("Strike rate of player1 is",strikerate1) print("Strike rate of player2 is",strikerate2) print("Strike rate of player3 is",strikerate3) print("Runs scored by player1 if they played 60 more balls is", run_player1*2) print("Runs scored by player2 if they played 60 more balls is", run_player2*2) print("Runs scored by player3 if they played 60 more balls is", run_player3*2) print("Maximum number of sixes player 1 could hit =",run_player1 //6) print("Maximum number of sixes player 2 could hit =",run_player2 //6) print("Maximum number of sixes player 3 could hit =",run_player3 //6)
f1009259b4e576b0555dc2bc55272c11927578fa
hamazumi/Leetcode
/detect-capital/detect-capital.py
357
3.734375
4
class Solution: def detectCapitalUse(self, word: str) -> bool: if word.isupper(): return True elif word.islower(): return True elif word == word.capitalize(): # capitalize() turns the first letter capital and the rest are turned lowercase return True else: return False
13ed209ec1af069c6f45eb843898ef9b4cdf055c
bjaus/RealPython
/sql/assignment3b.py
964
4.4375
4
# Assignment 3b - prompt the user # import the sqlite3 library import sqlite3 # create the connection object conn = sqlite3.connect('newnum.db') # create a cursor object used to execute SQL commands cursor = conn.cursor() prompt = """ Select the operation that you want to perform [1-5]: 1. Average 2. Max 3. Min 4. Sum 5. Exit """ # loop until user enters a valid operation number [1-5] while True: # get user input x = input(prompt) # if user enters any choice from 1-4 if x in set(['1', '2', '3', '4']): # parse the corresponding operation text operation = { 1: 'avg', 2: 'max', 3: 'min', 4: 'sum' }[int(x)] # retrieve data cursor.execute(""" SELECT {}(num) FROM numbers """.format(operation)) # fetchone() retrieves one record from the query get = cursor.fetchone() # output result to screen print("{}: {}".format(operation, get[0])) # if user enters 5 elif x == '5': print("Exit") # exit loop break
ed24cb5b592af17291c01d6cf9927a5c57320fb3
SimeonTsvetanov/Coding-Lessons
/SoftUni Lessons/Python Development/Python Advanced January 2020/Python Advanced/23. EXAM/01. Expression Evaluator.py
829
3.828125
4
import math from collections import deque the_ugly_expression = input().split() current_nums = deque([]) check = True for symbol in the_ugly_expression: if symbol.isdigit() or len(symbol) >= 2: current_nums.append(symbol) else: if check and (symbol == "/" or symbol == "*"): result = 1 check = False elif check: result = 0 check = False while len(current_nums) >= 2: num = current_nums.popleft() next_num = current_nums.popleft() if symbol == "/": total = math.floor(eval(f"{num} {symbol} {next_num}")) else: total = eval(f"{num} {symbol} {next_num}") current_nums.appendleft(total) print(current_nums.pop())
fb9903c28aaf1aec877b8db2e59066bf5ee6cef0
JaredColon-Rivera/The-Self-Taught-Programmer
/.Chapter-7/Challenge_4.py
397
4.03125
4
list_num = [1, 2, 3, 4, 5, 6, 7, 8, 9] guess_q = "What number is in the list?: " while True: print("Input q to quit") guess = input(guess_q) if guess == "q": print("Goodbye") break try: guess = int(guess) except ValueError: print("please type a number or q to quit") if guess in list_num: print("You got it right! {} was in the list".format(guess)) break else: print("WRONG")
3848b6baaddf728df150a746a8c97ed0da8ad3ac
Taller-Python-SEGuach/Leccion7
/parametres_ex.py
293
4
4
def saludo(idioma): if idioma == "En" : print("Hello") elif idioma == "Fr" : print ("Bonjour") elif idioma == "Es" : print("Hola") else : print("No es un idioma") Entrada=input("Ingrese el idioma del saludo (En, Fr, Es):") saludo(Entrada)
454e64f53768d881701fbe2556e9a7758992f295
timisenman/python
/projects/Codewars/high_and_low.py
807
3.953125
4
# In this little assignment you are given a string of space # separated numbers, and have to return the highest and lowest number. #high_and_low("1 2 3 4 5") # return "5 1" # def high_and_low(numbers): # high = max(numbers.split()) # low = min(numbers.split()) # return str(high) + " " + str(low) # print high_and_low("1, 2, 3, 4, 5") # def high_and_low(numbers): # res = numbers.split() # high = max(int(res)) # low = min(int(res)) # return str(high) + " " + str(low) def high_and_low(numbers): res = numbers.split() res = [int(s) for s in numbers.split()] high, low = max(res), min(res) return str(high) + " " + str(low) #num = ['4', '5', '29', '54', '4', '0', '-214', '542', '-64', '1', '-3', '6', '-6'] num = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6" print high_and_low(num)
c3948b74ac59fa06636f009621b63dd866b7c5a3
grzegorz-rogalski/pythonGrogal
/zaj2/zad2.py
129
3.59375
4
""" wyswietl tabliczke mnozenia """ for x in range(1,11): for y in range(1, 11): print "%3i" %( x*y), print "\n"
83d40dfa25747056a0fbbf226e3648270abf0acb
kyirong6/ds-for-fun
/arash/recursion/Reverse_Sequence.py
352
4.03125
4
def reverse(S, start, stop): if start < stop - 1: S[start], S[stop - 1] = S[stop - 1], S[start] reverse(S, start + 1, stop - 1) S = [1, 2, 3, 4, 5, 6, 7, 8] reverse(S, 0, 8) # Reverses the sequence print(S) reverse(S, 4, 5) # Nothing happens print(S) reverse(S, 3, 5) # Something happens print(S)
4f1e5d4b10010a13792998a305d0bc179b643ec4
hossainlab/dsn-template
/book/_build/jupyter_execute/demo/debugging.py
5,480
3.703125
4
(debugging)= # Debugging > \"Debugging is twice as hard as writing the code in the first place. > Therefore, if you write the code as cleverly as possible, you are, by > definition, not smart enough to debug it.\" -- Brian Kernighan ## Overview Are you one of those programmers who fills their code with `print` statements when trying to debug their programs? Hey, we all used to do that. (OK, sometimes we still do that...) But once you start writing larger programs you\'ll need a better system. Debugging tools for Python vary across platforms, IDEs and editors. Here we\'ll focus on Jupyter and leave you to explore other settings. We\'ll need the following imports import numpy as np import matplotlib.pyplot as plt %matplotlib inline ## Debugging ### The `debug` Magic Let\'s consider a simple (and rather contrived) example def plot_log(): fig, ax = plt.subplots(2, 1) x = np.linspace(1, 2, 10) ax.plot(x, np.log(x)) plt.show() plot_log() # Call the function, generate plot This code is intended to plot the `log` function over the interval $[1, 2]$. But there\'s an error here: `plt.subplots(2, 1)` should be just `plt.subplots()`. (The call `plt.subplots(2, 1)` returns a NumPy array containing two axes objects, suitable for having two subplots on the same figure) The traceback shows that the error occurs at the method call `ax.plot(x, np.log(x))`. The error occurs because we have mistakenly made `ax` a NumPy array, and a NumPy array has no `plot` method. But let\'s pretend that we don\'t understand this for the moment. We might suspect there\'s something wrong with `ax` but when we try to investigate this object, we get the following exception: ax The problem is that `ax` was defined inside `plot_log()`, and the name is lost once that function terminates. Let\'s try doing it a different way. We run the first cell block again, generating the same error def plot_log(): fig, ax = plt.subplots(2, 1) x = np.linspace(1, 2, 10) ax.plot(x, np.log(x)) plt.show() plot_log() # Call the function, generate plot But this time we type in the following cell block ```python %debug ``` You should be dropped into a new prompt that looks something like this ```{code-block} none ipdb> ``` (You might see `pdb\>` instead) Now we can investigate the value of our variables at this point in the program, step forward through the code, etc. For example, here we simply type the name `ax` to see what\'s happening with this object: ```{code-block} none ipdb> ax array([<matplotlib.axes.AxesSubplot object at 0x290f5d0>, <matplotlib.axes.AxesSubplot object at 0x2930810>], dtype=object) ``` It\'s now very clear that `ax` is an array, which clarifies the source of the problem. To find out what else you can do from inside `ipdb` (or `pdb`), use the online help ```{code-block} none ipdb> h Documented commands (type help <topic>): ======================================== EOF bt cont enable jump pdef r tbreak w a c continue exit l pdoc restart u whatis alias cl d h list pinfo return unalias where args clear debug help n pp run unt b commands disable ignore next q s until break condition down j p quit step up Miscellaneous help topics: ========================== exec pdb Undocumented commands: ====================== retval rv ipdb> h c c(ont(inue)) Continue execution, only stop when a breakpoint is encountered. ``` ### Setting a Break Point The preceding approach is handy but sometimes insufficient. Consider the following modified version of our function above def plot_log(): fig, ax = plt.subplots() x = np.logspace(1, 2, 10) ax.plot(x, np.log(x)) plt.show() plot_log() Here the original problem is fixed, but we\'ve accidentally written `np.logspace(1, 2, 10)` instead of `np.linspace(1, 2, 10)`. Now there won\'t be any exception, but the plot won\'t look right. To investigate, it would be helpful if we could inspect variables like `x` during execution of the function. To this end, we add a \"break point\" by inserting `breakpoint()` inside the function code block ```python def plot_log(): breakpoint() fig, ax = plt.subplots() x = np.logspace(1, 2, 10) ax.plot(x, np.log(x)) plt.show() plot_log() ``` Now let\'s run the script, and investigate via the debugger ```{code-block} none > <ipython-input-6-a188074383b7>(6)plot_log() -> fig, ax = plt.subplots() (Pdb) n > <ipython-input-6-a188074383b7>(7)plot_log() -> x = np.logspace(1, 2, 10) (Pdb) n > <ipython-input-6-a188074383b7>(8)plot_log() -> ax.plot(x, np.log(x)) (Pdb) x array([ 10. , 12.91549665, 16.68100537, 21.5443469 , 27.82559402, 35.93813664, 46.41588834, 59.94842503, 77.42636827, 100. ]) ``` We used `n` twice to step forward through the code (one line at a time). Then we printed the value of `x` to see what was happening with that variable. To exit from the debugger, use `q`. ## Other Useful Magics In this lecture, we used the `%debug` IPython magic. There are many other useful magics: - `%precision 4` sets printed precision for floats to 4 decimal places - `%whos` gives a list of variables and their values - `%quickref` gives a list of magics The full list of magics is [here](http://ipython.readthedocs.org/en/stable/interactive/magics.html).
5145a4ab3eb447954260bc844cf08d32fc9f2293
SophieEchoSolo/PythonHomework
/Lesson2/solos02_celsius2fahrenheit.py
522
4.28125
4
""" Author: Sophie Solo Course: CSC 121 Assignment: Lab: Lesson 02 - Variables - Individual Description: Converts user input from celsius to fahrenheit """ # Input - Ask user for tempterature input in celsius celsius = input("Enter temperature in Celsius: ") # Convert the user input from string to float celsius = float(celsius) # Processing - Convert from Celsius to Fahrenheit fahrenheit = celsius * 9/5 + 32.0 # Output - display the result for the user print("The temperature in Fahrenheit is: ", fahrenheit)
1e0305078426211c35d1bc434468b490f30985d5
beomjun96/python-study
/2.1 if_statement_practice/if_practice2_1_6.py
571
4.0625
4
# 영문 대문자를 입력받아 # 'A'이면 “Excellent”, # 'B'이면 “Good”, # 'C'이면 “Usually”, # 'D'이면 “Effort”, # 'F'이면 “Failure”, # 그 외 문자이면 “error” 라고 출력하는 프로그램을 작성하시오. # 입력 예: B # 출력 예: Good word = input("영문 대문자 입력:") if word == 'A': print("Exellent") elif word =='B': print("Good") elif word == 'C': print("Usually") elif word == 'D': print("Effort") elif word == 'F': print("Failure") else: print("error")
7d8af0bf673542c57045b7796eb2ab3e5ab87036
maddrings/comp110-21f-workspace
/exercises/ex01/hype_machine.py
240
3.640625
4
"""Hype phrases with your name as a variable.""" __author__ = str("730396516") name: str = input("What is your name? ") print(name + ", you rock!") print("That's right, " + name + ", you are a baddie!") print("Talk yo stuff " + name + "!")
82d3b10fb2c32c864982aee09ad341c8dc6467c4
Nfrederiksen/PythonRep
/ML/DeepNN_inNumPy.py
3,617
4.28125
4
import numpy as np from matplotlib import pyplot as plt def sigmoid(z): """sigmoid activation function on input z""" return 1 / (1 + np.exp(-z)) # defines the sigmoid activation function def forward_propagation(X, Y, W1, b1, W2, b2): """ Computes the forward propagation operation of a neural network and returns the output after applying the sigmoid activation function """ net_h = np.dot(W1, X) + b1 # net output at the hidden layer out_h = sigmoid(net_h) # actual after applying sigmoid net_y = np.dot(W2, out_h) + b2 # net output at the output layer out_y = sigmoid(net_y) # actual output at the output layer return out_h, out_y def calculate_error(y, y_predicted): """Computes cross entropy error""" loss = np.sum(- y * np.log(y_predicted) - (1 - y) * np.log(1 - y_predicted)) return loss def backward_propagation(X, Y, out_h, out_y, W2): """ Computes the backpropagation operation of a neural network and returns the derivative of weights and biases """ l2_error = out_y - Y # actual - target dW2 = np.dot(l2_error, out_h.T) # derivative of layer 2 weights is the dot product of error at layer 2 and hidden layer output db2 = np.sum(l2_error, axis=1, keepdims=True) # derivative of layer 2 bias is simply the error at layer 2 dh = np.dot(W2.T, l2_error) # compute dot product of weights in layer 2 with error at layer 2 l1_error = np.multiply(dh, out_h * (1 - out_h)) # compute layer 1 error dW1 = np.dot(l1_error, X.T) # derivative of layer 2 weights is the dot product of error at layer 1 and input db1 = np.sum(l1_error, axis=1, keepdims=True) # derivative of layer 1 bias is simply the error at layer 1 return dW1, db1, dW2, db2 # return the derivatives of parameters def update_parameters(W1, b1, W2, b2, dW1, db1, dW2, db2, learning_rate): """Updates weights and biases and returns thir values""" W1 = W1 - learning_rate * dW1 W2 = W2 - learning_rate * dW2 b1 = b1 - learning_rate * db1 b2 = b2 - learning_rate * db2 return W1, b1, W2, b2 def train(X, Y, W1, b1, W2, b2, num_iterations, losses, learning_rate): """Trains the neural network and returns updated weights, bias and loss""" for i in range(num_iterations): A1, A2 = forward_propagation(X, Y, W1, b1, W2, b2) losses[i, 0] = calculate_error(Y, A2) dW1, db1, dW2, db2 = backward_propagation(X, Y, A1, A2, W2) W1, b1, W2, b2 = update_parameters(W1, b1, W2, b2, dW1, db1, dW2, db2, learning_rate) return W1, b1, W2, b2, losses np.random.seed(42) # seed function to generate the same random value # Initializing parameters X = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) Y = np.array([[0, 1, 1, 0]]) # XOR n_h = 2 n_x = X.shape[0] n_y = Y.shape[0] W1 = np.random.randn(n_h, n_x) b1 = np.zeros((n_h, 1)) W2 = np.random.randn(n_y, n_h) b2 = np.zeros((n_y, 1)) num_iterations = 100000 learning_rate = 0.01 losses = np.zeros((num_iterations, 1)) W1, b1, W2, b2, losses = train(X, Y, W1, b1, W2, b2, num_iterations, losses, learning_rate) print("After training:\n") print("W1:\n", W1) print("b1:\n", b1) print("W2:\n", W2) print("b2:\n", b2) print("losses:\n", losses) # Evaluating the performance plt.figure() plt.plot(losses) plt.xlabel("EPOCHS") plt.ylabel("Loss value") plt.show() plt.savefig('output/legend.png') X2 = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) Y2 = np.array([[1, 0, 0, 1]]) # XOR # Predicting value A1, A2 = forward_propagation(X2, Y2, W1, b1, W2, b2) pred = (A2 > 0.5) * 1.0 print("Predicted labels:", pred)
0386733594c90607a4d34b0f5468fd6340644c52
muzigit/PythonNotes
/section1_语法基础/action3.py
945
4
4
# 条件判断 age = 18 # if...elif...else的定义 if age < 18: print('未成年') elif age == 18: print('刚好成年') else: print('已成年') # 练习: # 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数: # # 低于18.5:过轻 # 18.5-25:正常 # 25-28:过重 # 28-32:肥胖 # 高于32:严重肥胖 height = 1.78 # 单位:m weight = 60 # 单位:kg # ** 表示求平方 BMI = weight / (height ** 2) # round():对浮点数进行四舍五入 参数二表示需要保留多少位小数点 BMI = round(BMI, 2) def switchBmi(dec): print('您的BMI值是', BMI, dec) if BMI < 18.5: switchBmi(dec='过轻') elif BMI > 18.5 and BMI < 25: switchBmi(dec='正常') elif BMI > 25 and BMI < 28: switchBmi(dec='过重') elif BMI > 28 and BMI < 32: switchBmi(dec='肥胖') else: switchBmi(dec='严重肥胖')
229f1481265b25beaecbb58976d926ef43f86081
nagauta/Codecademy
/DataStructure/data_structure/Graph/graph.py
2,680
3.90625
4
from vertex import Vertex class Graph: def __init__(self): self.graph_dict = {} def add_vertex(self, node): self.graph_dict[node.value] = node def add_edge(self, from_node, to_node, weight = 0): self.graph_dict[from_node.value].add_edge(to_node.value, weight) self.graph_dict[to_node.value].add_edge(from_node.value, weight) def explore(self): print("Exploring the graph....\n") #FIadd_edgeLL IN EXPLORE METHOD BELOW current_room = 'entrance' path_total = 0 print("\nStarting off at the {0}\n".format(current_room)) while current_room != 'treasure room': node = self.graph_dict[current_room] for connected_room,weight in node.edges.items(): key = connected_room[:1] print("enter {0} for {1}: {2} cost".format(key,connected_room,weight)) valid_choices = [room[:1] for room in node.edges.keys()] print("\nYou have accumulated: {0} cost".format(path_total)) choice = input("\nWhich dsroom do you move to? ") if choice not in valid_choices: print("please select from these letters: {0}".format(valid_choices)) else: for room in node.edges.keys(): if room.startswith(choice): current_room = room print("\n*** You have chosen: {0} ***\n".format(current_room)) print("Made it to the treasure room with {0} cost".format(path_total)) def print_map(self): print("\nMAZE LAYOUT\n") for node_key in self.graph_dict: print("{0} connected to...".format(node_key)) node = self.graph_dict[node_key] for adjacent_node, weight in node.edges.items(): print("=> {0}: cost is {1}".format(adjacent_node, weight)) print("") print("") def build_graph(): graph = Graph() # MAKE ROOMS INTO VERTICES BELOW... entrance = Vertex("entrance") ante_chamber = Vertex("ante-chamber") kings_room = Vertex("kings room") grand_gallery = Vertex("grand gallery") treasure_room = Vertex("treasure room") # ADD ROOMS TO GRAPH BELOW... graph.add_vertex(entrance) graph.add_vertex(ante_chamber) graph.add_vertex(kings_room) graph.add_vertex(grand_gallery) graph.add_vertex(treasure_room) # ADD EDGES BETWEEN ROOMS BELOW... graph.add_edge(entrance,ante_chamber,7) graph.add_edge(entrance,kings_room,3) graph.add_edge(kings_room,ante_chamber,1) graph.add_edge(grand_gallery,ante_chamber,2) graph.add_edge(grand_gallery,kings_room,2) graph.add_edge(treasure_room,ante_chamber,6) graph.add_edge(treasure_room,grand_gallery ,4) # DON'T CHANGE THIS CODE graph.print_map() return graph
314c06fdb778ea671c3bfa2e4cb97bc3a4e2fabb
linth/learn-python
/data_structure/list/list_iter.py
1,498
4.4375
4
""" iterable (可) - Lists, tuples, dictionaries, and sets are all iterable objects. - list, tuple, dict, set 都是 iterable 的 object。 - 通常是一個容器 - iterable實作__iter__方法回傳一個參考到此容器內部的iterator iterator - an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__(). - iterator 屬於實作iterator protocol 的 object,包含__iter__(), __next()__。 - 迭代器 - 請釐清楚下面幾個的名詞和觀念:(詳細內容可以參考reference) - 容器 (container) - 迭代器物件 (iterator):能用來產生迭代器的物件,回傳其包含的所有元素,但它不必是資料結構。 - 產生器物件 (generator) - generator expression - list, set, dict comprehension Reference: - https://medium.com/ai-academy-taiwan/python-%E7%9A%84%E5%8F%AF%E8%BF%AD%E4%BB%A3%E7%89%A9%E4%BB%B6-%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%92%8C%E7%94%A2%E7%94%9F%E5%99%A8-236d19c4051e """ # list student = ["george", "may", "peter", "JJ", "Haha"] # tuple fruit = ("apple", "banana", "cherry") # dict s = {'name': 'george', 'age': 88, 'sex': 'boy', 'id': 'p0001'} print(student, type(student)) print(fruit, type(fruit)) for i in s: print(i) # name, age, sex, id x = iter(fruit) y = iter(fruit) # x 是 tuple 型別的資料結構,但這並非必要條件。 print(f'x =', next(x)) print(f'x =', next(x)) print(f'y =', next(y))
abc62e87950a26fb88985c6396b67609876dee9f
nog642/MathTools
/mttools/CalculusTools/__init__.py
904
3.9375
4
from mttools.Constants import EPSILON from mttools.Core import check_inf def derivative(f): """ Takes a lambda function and returns the derivative as a lambda function :param f: A one dimensional lambda function :return: f'(x) """ g = lambda x, h: f(x + h) return limit(()) # TODO Diferentiation def limit(f, a): """ Takes the limit of some lambda function, f, as f approaches a :param f: function :param a: value f tends towards :return: limit of f """ try: return f(a) # if the function exists at a it tends to f(a) except ZeroDivisionError: if abs(f(a - EPSILON) - f(a + EPSILON)) <= pow(10, -10): return check_inf(f(a + EPSILON)) return None def function_roots(f): """ Uses Newton's method to find the roots of a function :param f: function :return: (roots, ) """ pass
39eb9fbd59ff77e277d98f109422384dbc75d6db
anaheino/investmentCalculator
/investmentCalculator.py
1,000
3.609375
4
#!/usr/bin/python3 import sys def calculateInvestments(investmentsPerYear, years, gainAsNumber, calcOnlyWholeSum): i = 0 wholeSum = investmentsPerYear if calcOnlyWholeSum else 0 while i < years: if calcOnlyWholeSum: wholeSum = wholeSum * gainAsNumber else: wholeSum = (wholeSum + investmentsPerYear) * gainAsNumber i+=1 return wholeSum if __name__ == "__main__": print("Monetary value after this time would be:") n = 3 investmentsPerYear = sys.argv[1] years = sys.argv[2] gainAsNumber = sys.argv[3] if len(sys.argv) > 3 else 1 calcOnlyWholeSum = True if len(sys.argv) > 4 else False moneyArray = str(calculateInvestments(int(investmentsPerYear), int(years), float(gainAsNumber), calcOnlyWholeSum)).split(".") sumOfMoney = moneyArray[0][::-1] formatted = [sumOfMoney[index : index + n] for index in range(0, len(sumOfMoney), n)] print(" ".join(formatted)[::-1]+","+str(moneyArray[1])[0: 2])
5243f74dcc584041296672cd446568fa9642c067
ohmygodlin/snippet
/ctf/misc/dijkstra.py
2,752
3.59375
4
#https://www.cnblogs.com/P201521440001/p/11415504.html #https://blog.csdn.net/imotolove/article/details/80633006 #https://blog.csdn.net/anlian523/article/details/80893372 #https://blog.csdn.net/AivenZhong/article/details/84385736 import heapq class Node: def __init__(self, cur): self.cur = cur self.edges = {} self.parent = None self.distance = None self.is_visited = False def __lt__(self, other): # for heapq, not used here! return self.distance < other.distance def __str__(self): s = '[' for end, edge in self.edges.items(): s += end + str(edge) s += ']' return '({}, {}, {}, {})'.format(self.cur, s, self.parent, self.distance) def add_edge(self, end, edge): self.edges[end] = edge class Edge: def __init__(self, weight, data): self.weight = int(weight) self.data = data def __str__(self): return '<{}, {}>'.format(self.weight, self.data) def dijkstra(node_dict, start): heap = [] start_node = node_dict[start] start_node.parent = start start_node.distance = 0 heapq.heappush(heap, start_node) while heap: top = heapq.heappop(heap) #same node would be put into heap many times when distance is updated, need to verify parent if top.is_visited: continue for end, edge in top.edges.items(): end_node = node_dict[end] v = top.distance + edge.weight #update distance, like DP if end_node.distance is None or v < end_node.distance: end_node.parent = top.cur end_node.distance = v heapq.heappush(heap, end_node) #same node would be put into heap many times, but the small ONE would stay first print end_node def add_node(node_dict, start, end, edge): if start not in node_dict: node = Node(start) node_dict[start] = node else: node = node_dict[start] node.add_edge(end, edge) def show(node_dict): for key, node in node_dict.items(): print node def init(): node_dict = {} # {start: [nodelist]} with open('dijkstra.txt', 'r') as f: for line in f: arr = line.strip().split(' ') if len(arr) < 4: continue add_node(node_dict, arr[0], arr[1], Edge(arr[2], arr[3])) #undirected graph would also need to add end -> start add_node(node_dict, arr[1], arr[0], Edge(arr[2], arr[3])) return node_dict node_dict = init() show(node_dict) print '===================' start = '1' dijkstra(node_dict, start) print '===================' show(node_dict) print '===================' i = '26' flag = '' while i != start: node = node_dict[i] edge = node_dict[node.parent].edges[i] flag += edge.data[::-1] print i, node.parent, flag i = node.parent print flag[::-1] #FLAG{WEIVKASJVLSJCHFSJVHJSDEV}
9cbd0275df06a26853121366ea8dc338bda8746a
KonekoTJ/Level-3_Python
/Homework4/Fenrir/Homework4_4.py
664
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 20:33:30 2020 @author: Fenrir Description : 数値の表示、総計、及び平均数値を表示する事。 総計値と平均値、全て小数点以下は1桁に留める事。 Variable: Input:(a~e) sum:総計 average:平均数 Algorithm/Calculation: sum = a + b + c + d + e average = sum/5 """ # input a = int(input("input a:")) b = int(input("input b:")) c = int(input("input c:")) d = int(input("input d:")) e = int(input("input e:")) # Calculation sum = a + b + c + d + e average = sum/5 # output print("Sum = {:.1f}".format(sum)) print("Average = {:.1f}".format(average))
e1c197b8dabd59ebc8c71bf29ed462d57e11053e
nerissavu/D4E-TC-NGA
/Session4/hw/serious_exercise1.py
174
3.875
4
name = str(input('Write your name: ')) name_lower = name.lower() name_notab = " ".join(name_lower.split()) updated_name = name_notab.title() print('Updated:', updated_name)
f32c0671b50aec14b9c629a9e880c7e0adbbacc8
The-Fungi/Hacktoberfest2021-1
/ProductOfNintegers.py
151
3.828125
4
a= int(input("Enter No of Numbers: ")) b = [] d = 1 for i in range a: c = int(input("Enter Number: ")) b.append(c) for x in b: d = d*x print(d)
37fc67d49aa8964814b97b24b338ea7e7807ebee
WaleedRanaC/Prog-Fund-1
/Lab 7/IndexList.py
862
4.4375
4
#this program demonstrates how to get the #index of an item in a list and replace it w/ # a new one def main(): #create a list with some items food=["pizza","chips","burgers"] #display the list print("Here are the utens ub the food list: ") print(food) #get the item to change item=input("Which item should I change? ") try: #get the item's index in the list itemIndex=food.index(item) #get the value to replace it with newItem=input("Enter the new value") #replace the old with the new food[itemIndex]=newItem #display the list print("Here is the revised list: ") print(food) except ValueError: print("This item was not found in the list") main()
d3e887175c602883043179247c4423098a099d2f
selvi7/samplepyhon
/19.py
132
4.21875
4
n=int(input("Enter a number:")) fact=1 for i in range(1,n+1): fact=fact*i print("The fact of",n,"is",end="") print(fact)
5b12892a17e62ba2df60c28306d899f4e83e1083
RocketryVT/rocket-os
/src/sensors/scripts/sensor_monitor.py
5,303
3.546875
4
#! /usr/bin/env python3 ''' Sensor Monitor: Monitors and Displays the data streams of various sensors. + Num of Functions: 4 + Num of Classes: 1 ''' from time import time import rospy from std_msgs.msg import String, Bool, Float32 from sensors.msg import SensorReading import csv import numpy import re sensor_timer = None voltage_timer = None class Tracker: ''' Tracks and displays a specific stream of sensor data. ''' def __init__(self, name, unit=None): self.name = name self.last = None def get(self, message): ''' Update Tracker with current sensor data ''' self.last = message def to_string(self, voltage=False): ''' Put tracked sensor data in a string of the following format: ACRONYM: Data UnitType @param voltage: - True - Convert raw Voltage Data to string - False - Convert SI Unit Data to string ''' # Create Acronym from Tracker Name acronym = ''.join([x[0] for x in self.name.split()]).upper() # Return Empty if self.last is None: return "{}: ".format(acronym) # Return only raw voltage data if voltage: return "{}: {:0.2f} V".format(acronym, self.last.voltage) # Return only data with no SI Unit value if self.last.unit == "": return "{}: {:0.2f}".format(acronym, self.last.reading) # Return only SI unit data return "{}: {:0.2f} {}".format(acronym, self.last.reading, self.last.unit) def get_data(self): ''' Returns the current data reading ''' return self.last.reading def echo_sensors(event=None): ''' Displays the SI Unit data for all Trackers ''' echo(False) def echo_voltage(event=None): ''' Displays the voltage data for all Trackers ''' echo(True) def echo(print_voltage): ''' Prints the current data for every Tracker to screen, each separated by a "/". @param print_voltage: - True - Prints Raw Voltage value - False - Prints SI Unit value ''' output = "" for i, tracker in enumerate(trackers): output += tracker.to_string(print_voltage) if i < len(trackers) - 1: output = output + " / " rospy.loginfo(output) # Print def get_command(message): ''' Initiate commands pertaining to the display of sensor data. - read data - read data [0-9]+ - stop data - read voltage - read voltage [0-9]+ - stop voltage ''' global sensor_timer global voltage_timer command = message.data # Start displaying sensor data if command == "read data": echo_sensors() elif bool(re.match(re.compile("^read data [0-9]+"), command)): period = float(command.split()[2]) # Num of Seconds to read data if sensor_timer: sensor_timer.shutdown() sensor_timer = rospy.Timer(rospy.Duration(period), echo_sensors) # Stop displaying sensor data elif command == "stop data": if sensor_timer: sensor_timer.shutdown() sensor_timer = None # Start displaying sensor voltage data elif command == "read voltage": echo_voltage() elif bool(re.match(re.compile("^read voltage [0-9]+"), command)): period = float(command.split()[2]) if voltage_timer: voltage_timer.shutdown() voltage_timer = rospy.Timer(rospy.Duration(period), echo_voltage) # Stop displaying sensor voltage data elif command == "stop voltage": if voltage_timer: voltage_timer.shutdown() voltage_timer = None def makeCSV(): ''' Build CSV file from sensor data ''' csv_w.writerow([time_count, tracker[0].get_data, tracker[1].get_data, tracker[2].get_data, tracker[3].get_data, tracker[4].get_data]) time_count += 1 if __name__ == "__main__": # Set up CSV file csv_w = csv.writer(open("data.csv", 'w')) csv_w.writerow(["Time", "Pressure 1", "Pressure 2", "Temperature 1", "Temperature 2", "Temperature 3"]) global time_count time_count = 0 #Initialize Node rospy.init_node("sensor_monitor", log_level=rospy.DEBUG) rospy.Subscriber("/commands", String, get_command) trackers = [ Tracker("Oxidizer tank pressure"), Tracker("Combustion chamber pressure"), Tracker("Oxidizer tank temperature"), Tracker("Combustion chamber temperature 1"), Tracker("Combustion chamber temperature 2"), Tracker("Float switch") ] #Set Subscriptions rospy.Subscriber("/sensors/ox_tank_transducer", SensorReading, trackers[0].get) rospy.Subscriber("/sensors/combustion_transducer", SensorReading, trackers[1].get) rospy.Subscriber("/sensors/ox_tank_thermocouple", SensorReading, trackers[2].get) rospy.Subscriber("/sensors/combustion_thermocouple_1", SensorReading, trackers[3].get) rospy.Subscriber("/sensors/combustion_thermocouple_2", SensorReading, trackers[4].get) rospy.Subscriber("/sensors/float_switch", SensorReading, trackers[5].get) rospy.spin() rospy.Timer(rospy.Duration(1), makeCSV)
01fb8c6cca4f94e7cad4442be7e95b187d733f4c
kononovk/HomeTasks
/hw3/t03Hangman/hangman.py
2,081
4.125
4
from random import randint from hw3.t03Hangman.hangman_logic import get_guessed_word, is_word_guessed from termcolor import colored from string import ascii_lowercase def rand_word_gen(filename): with open(filename) as file: words = [row.strip() for row in file] random_word = words[randint(0, len(words) - 1)] return random_word def letter_input(): temp_character = input("Choose the next letter: ") while temp_character.lower() not in set(ascii_lowercase): print("You must input only latin letters") temp_character = input("Choose the next letter: ") return temp_character.lower() def choose_complexity(word): complexity = input("1-Easy, 2-Medium, 3-Hard\nPlease, choose the complexity:") while complexity not in {'1', '2', '3'}: print("The number of complexity must be 1, 2 or 3") complexity = input("1-Easy, 2-Medium, 3-Hard\nPlease, choose the complexity:") attempts = len(word) * (4 - int(complexity)) return attempts if __name__ == '__main__': secret_word = rand_word_gen("words.txt") available_letters = set(secret_word) used_letters = set() num_of_attempts = choose_complexity(secret_word) print(colored("---------------------------", "green")) while not is_word_guessed(secret_word, used_letters) and num_of_attempts > 0: print("You have got {} attempts".format(num_of_attempts)) print("Word: " + colored(get_guessed_word(secret_word, used_letters), "green")) curr_letter = letter_input() if curr_letter not in available_letters: print("You didn't guess\n") num_of_attempts -= 1 else: print() used_letters.add(curr_letter) available_letters.discard(curr_letter) if num_of_attempts <= 0: print("You lose, I pour your wine into the sink\nThe word was " + colored(secret_word, "green")) else: print("Word: " + colored(get_guessed_word(secret_word, used_letters), "green")) print(colored("Congratulations you won!!!", "yellow"))
a47a7b170b44df13bb3de2f3ea1110e7fa2b2433
sr-utkarsh/python-TWoC-TwoWaits
/day_6/12th.py
533
3.890625
4
def longestCommonPrefix( a,n): if (n == 0): return "" if (n== 1): return a[0] a.sort() end = min(len(a[0]), len(a[n - 1])) i = 0 while (i < end and a[0][i] == a[n - 1][i]): i += 1 if(i==0): print("No common prefix is found") else: print("The common prefix is ",a[0][0: i]) n=int(input("Enter the size of list: ")) A=[] print("Enter the elements: ") for i in range (n): el=input() A.append(el) longestCommonPrefix(A,n)
b0df20782b5b63e402c7e50dd39983f121a82a15
quochoantp/Project2
/PythonBTCoBan/1.5.py
155
3.65625
4
a= float(input()) b= float(input()) if a==0: print("Phuong trinh vo nghiem") else: c= -b/a print("Phuong trinh co nghiem la") print(c)
33ed443cc1ed26c1273cded15f229c21c92a5869
daniel-reich/ubiquitous-fiesta
/TsRjbMRoNCM3GHuDk_21.py
516
4.4375
4
def syllabification(word): ''' Returns a syllabificated version of words as per the instructions. ''' s_word = '' i = len(word) - 1 # step backwards through word VOWELS = {'A', 'a', 'e', 'i', 'o', 'u'} # the Persian vowels ​ while i >= 0: if word[i] not in VOWELS: s_word = word[i] + s_word i-= 1 else: s_word = '.' + word[i-1] + word[i] + s_word i-= 2 # skip over CV ​ return s_word[1:] # drop the leading '.'
e9b47397b86abfaa39863f5e9c0ba652fddd54a7
jdrkanchana/python_beginner_days
/printing_patterns.py
120
3.6875
4
a=[5,2,2,5,2] length_a=len(a) for x in range(0,length_a): y=a[x] for z in range(0,y): print('x', end='') print("")
f52a3545299ef5b0226757417bebe68e57147765
shash95/datastructures-and-algorithms
/LeetCode/Longest Substring Without Repeating Characters.py
1,378
4.125
4
""" Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. Example 4: Input: s = "" Output: 0 """ class Solution: def lengthOfLongestSubstring(self, s): if len(s) == 0 or len(s) == 1: return len(s) start = 0 end = 0 character_list = [] max_length = 1 while True: if start == len(s): return max(max_length, len(character_list)) end = start while True: if end == len(s): max_length = max(max_length, len(character_list)) break if s[end] in character_list: max_length = max(max_length, len(character_list)) character_list = [] break else: character_list.append(s[end]) end += 1 start += 1
925ececf074a0820a4910bbe81649badcc833edc
awpathum/hackerRank
/jc.py
550
3.765625
4
# number of elements # n = int(input("Enter number of elements : ")) # a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n] # print("\nList is - ", a) #print("Enter the string : ") s = input() #print("Enter index : ") n = int(input()) #count = 0 def findChar(s,e): c = 0 p =0 for i in range(len(s)): if(s.find('a',p,len(s)) != -1): c = c + 1 i = p return c if(len(s) >= n): print(s.find('a',0,len(s))) else: while len(s) < n: s.join(s)
f64dc7059ceaad30539a8c93d4ed54e573e98d6a
suiup/pythonProject
/python_learning/装饰器/demo02.py
273
4.125
4
""" 一个没有装饰器的方式 将 function 当成参数传入另一个function """ def decorator(fn, name): print(name+"say I'm in") # 这是我的前处理 return fn(name) def outer_fn(name): print(name+"say I'm out") decorator(outer_fn, "mofanpy")
11532104c40d82302696e278cb3cac8f429a4b78
smwa/double_elimination
/double_elimination/participant.py
865
3.9375
4
""" The Participant class represents a participant in a specific match. It can be used as a placeholder until the participant is decided. """ class Participant: """ The Participant class represents a participant in a specific match. It can be used as a placeholder until the participant is decided. """ def __init__(self, competitor=None): self.competitor = competitor def __repr__(self) -> str: return f'<Participant {self.competitor}>' def get_competitor(self): """ Return the competitor that was set, or None if it hasn't been decided yet """ return self.competitor def set_competitor(self, competitor): """ Set competitor after you've decided who it will be, after a previous match is completed. """ self.competitor = competitor
12c7759dba81ce6faddf5c1a7fadc4ebc0835be7
uhvardhan/ML_Python
/Vectors-Matrices-Arrays/max_min.py
540
4.40625
4
# Load library import numpy as np # Create matrix matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Return maximum element print("The maximum element in the array is: {}".format(np.max(matrix))) # Return the minimum element print("The minimum element in the array is: {}".format(np.min(matrix))) # Find maximum element in each column print("The maximum element in each column is: {}".format(np.max(matrix, axis=0))) # Find maximum element in each row print("The maximum element in each row is: {}".format(np.max(matrix, axis=1)))
9517a2cd95f99dfb4523ad79792f539c4bdb403c
zhiyiTec/machineLearn
/python/pythonProject/Demo15.py
785
3.796875
4
# A = {"python", 123, ("python", 123)} # print(A) # B = set("pypy123123") # print(B) # C = {"python", 123, "python", 123} # print(C) # A = {"p", "y", 123} # B = set("pypym123") # print("A-B:{}".format(A - B)) # print("B-A:{}".format(B - A)) # print("A&B:{}".format(A & B)) # print("A | B:{}".format(A | B)) # print("A ^ B", format(A ^ B)) # A={"p","y",123} # for item in A: # print(item,end="") # A = {"p", "y", 123} # try: # while True: # print(A.pop(), end="") # except: # pass # A = {"p", "y", 123} # print("p" in A) # # 列表 # ls = ["p", "p", "y", "y", 123] # s = set(ls) # print(s) # ls = list(s) # 将集合转为列表 # print(ls) creature = "cat", "dog", "tiger", "human" print(creature[::-1]) color = (111, "blue", creature) print(color[-1][2])
21629315646742b0cbe75278e0477204d2d042b2
ruslan-baichurin/magic
/problems/calculating_pi.py
287
3.96875
4
def calculate_pi(n_terms: int) -> float: numerator, denominator, operation, pi = 4.0, 1.0, 1.0, 0.0 for _ in range(n_terms): pi += operation * (numerator / denominator) denominator += 2.0 operation *= -1.0 return pi print(calculate_pi(100000000))
4a85948723fa0bcc0ef41bc564a34028503678d5
sudhanthiran/Python_Practice
/Competitive Coding/Nearest multiple of 10.py
322
3.71875
4
def nearest(n: int): str_n = str(n) digit_2_add_or_sub = 0 last_digit = int(str_n[len(str_n)-1]) if(last_digit <=5): n = n - last_digit else: digit_2_add_or_sub = 10 - last_digit print(n+digit_2_add_or_sub) T = int(input()) for i in range(T): N = int(input()) nearest(N)
b6520a6269edfec658ad6652e1c712692eaf117d
javamaasai/python_crypto_test
/encrypt-one-two-way-test.py
1,647
4.0625
4
#!/usr/bin/env python3 from Crypto.Cipher import AES import uuid import hashlib import binascii import os # A function to hash password using sha256 salt def hash_it_with_salt(strg): # uuid is used to generate a random number salt = uuid.uuid4().hex return hashlib.sha256(salt.encode() + strg.encode()).hexdigest() + ':' + salt #Data Entry print () print ("----------------------------------------------------") print (" Encryption Test") print ("----------------------------------------------------") print (" 1: One way") print (" 2: Two way") print ("----------------------------------------------------") strgOrig = input("|-> Enter String :") print () print (" 1: One way (using sha256 + salt)") print ("----------------------------------------------------") print ("|-> hashed = "+hash_it_with_salt(strgOrig)); print () print (" 1: Two way (AES)") print ("----------------------------------------------------") pskey = binascii.hexlify(os.urandom(16)) print("|-> Generated Key: "+pskey.decode('utf-8')) # ENCRYPT: AES obj = AES.new(pskey, AES.MODE_CBC, 'This is an IV456') storeLen = len(strgOrig) if storeLen < 16: diflen = (32-storeLen) strgOrig = strgOrig+pskey.decode('utf-8')[0:diflen] ciphertext = obj.encrypt(strgOrig) print () print ("|-> ENCRYPT: AES > "+str(ciphertext)) # DECRYPT: AES obj2 = AES.new(pskey, AES.MODE_CBC, 'This is an IV456') if storeLen < 16: plaintext = obj2.decrypt(ciphertext)[0:storeLen] else: plaintext = obj2.decrypt(ciphertext) print () os.system('color 7') print ("|-> DECRYPT: AES > "+str(plaintext)) print ("----------------------------------------------------")
f1706c934b3a3ab7fbbf45ce705fa0438089ef08
seohae2/python_algorithm_day
/이것이코딩테스트다/chapter06_정렬/03_성적이낮은순서로_학생출력하기/seohae.py
492
3.625
4
n = int(input()) array = [] for i in range(n): input_data = input().split() # 이름은 문자열 # 점수는 정수형으로 변환하여 저장 # 리스트안에 튜플 형태로 저장 array.append((input_data[0], int(input_data[1]))) # 점수 오름차순 # 람다 사용 # 점수를 기준으로 정렬함을 명시 array = sorted(array, key=lambda student: student[1]) print(array) # 출력은 이름으로 for student in array: print(student[0], end=' ')
5cef9d4fa53ebb00307edc2b5920aa70ea23e53d
PyroAVR/easygrade
/grade.py
866
3.515625
4
from gradeitem import gradeitem class grade: def __init__(self): self.max_score = 100 self.total_points = 0 self.score = 0 self.items = dict() def add_grade_item(self, item): self.items[item.name] = item self.total_points += item.total_points def get_points_earned(self): self.score = 0 for item in self.items: self.score += items[item].get_points_earned() return self.score def get_percentage_grade(self): points = self.get_points_earned() return points/self.total_points def clone(self): g = grade() g.max_score = self.max_score g.total_points = self.total_points g.score = 0 g.items = dict([item.clone() for item in self.items]) #deep return g
4aa270ca8fd3a034df0fa4256bc0578039453596
sammyrano/tech-project
/TASK 2.py
556
3.96875
4
def likes(array): if len(array)== 0 : print('no one like this item') elif len(array) == 1: print(array[0], 'likes this item') elif len(array) == 2: print(array[0], 'and', array[1], 'likes this item') elif len(array) == 3: print(array[0], ',', array[1], 'and' , array[2] , 'likes this item') else : print(array[0], ',', array[1], 'and' , len(array[2:]), 'others likes this item') likes(["Soji", "Samuel", "Jane", "Kelechi", "Peter", "Buhari"]) likes([])
e66c89bb1de64593bdb2bf8f73601b568ad67a1d
ashracc/TC4002_Development_Exercises
/lab3/lab3_16.py
1,119
3.625
4
""" Given the math.ceil function, - Define a set of unit test cases that exercise the function (Remember Right BICEP) """ import unittest import math class TestCeil(unittest.TestCase): def test_happy_paths(self): # Test ceil function when input >= 0 self.assertAlmostEqual(math.ceil(1), 1.0) self.assertAlmostEqual(math.ceil(1.6), 2.0) self.assertAlmostEqual(math.ceil(1.4), 2.0) def test_edge_cases(self): self.assertAlmostEqual(math.ceil(math.pi), 4.0) self.assertAlmostEqual(math.ceil(999999999999999999),999999999999999999.0) def test_sad_paths(self): # Test ceil function when input <= 0 self.assertAlmostEqual(math.ceil(0), 0) self.assertAlmostEqual(math.ceil(-2.3), -2.0) self.assertAlmostEqual(math.ceil(True), 1.0) def test_types(self): # Make sure type errors are raised when necessary self.assertRaises(TypeError, math.ceil, 3+5j) self.assertRaises(TypeError, math.ceil, "hello") self.assertRaises(TypeError, math.ceil, ) self.assertRaises(TypeError, math.ceil, [1])
9d0e6ac91a7edd4f1ceefe7e3ab34c341fe834f2
xavieroldan/Phyton
/Proyecto1/fori.py
176
3.75
4
if __name__ == '__main__': # Usuario entra palabras hasta que la palabra sea salir word = "hola" for i in range(0,len(word)): print(len(word)+str(word))
1b699c33d603677377811a1fec21c46e9a9fcef4
ksparkje/leetcode-practice
/python/graph/q310_minimum_height_tree.py
3,124
4.09375
4
# 310. Minimum Height Trees # Nice problem! # Medium # # For an undirected graph with tree characteristics, we can choose any # node as the root. The result graph is then a rooted tree. Among all # possible rooted trees, those with minimum height are called minimum # height trees (MHTs). Given such a graph, write a function to find all # the MHTs and return a list of their root labels. # # Format # The graph contains n nodes which are labeled from 0 to n - 1. You will # be given the number n and a list of undirected edges (each edge is a pair of labels). # # You can assume that no duplicate edges will appear in edges. Since all edges # are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. # # Example 1 : # # Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]] # # 0 # | # 1 # / \ # 2 3 # # Output: [1] # Example 2 : # # Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] # # 0 1 2 # \ | / # 3 # | # 4 # | # 5 # # Output: [3, 4] # Note: # # According to the definition of tree on Wikipedia: “a tree is an undirected # graph in which any two vertices are connected by exactly one path. In other # words, any connected graph without simple cycles is a tree.” # The height of a rooted tree is the number of edges on the longest downward # path between the root and a leaf. ''' Idea is quite simple... # 0 1 2 # \ | / -------- CUT HERE # 3 # | # 4 # | -------- CUT HERE # 5 Answer is [3, 4]. Start with the nodes with no children. Get rid of those children. Then go to the nodes with no children. Obviously, when getting rid of the children, we have to keep track of which nodes no longer have any children. https://leetcode.com/problems/minimum-height-trees/discuss/76149/Share-my-Accepted-BFS-Python-Code-with-O(n)-Time ''' from typing import List from collections import defaultdict class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: graph = defaultdict(list) degree = defaultdict(int) for v1, v2 in edges: degree[v1] += 1 degree[v2] += 1 graph[v1].append(v2) graph[v2].append(v1) # get all the children previous_level = [] for key, val in degree.items(): if val == 1: previous_level.append(key) not_visited = set(range(n)) # Number of root <= 2 while len(not_visited) > 2: waiting = [] for node in previous_level: not_visited.remove(node) for next_node in graph[node]: if next_node in not_visited: degree[next_node] -= 1 if degree[next_node] == 1: waiting.append(next_node) previous_level = waiting return previous_level if __name__ == '__main__': s = Solution() n, given = 4, [[1,0],[1,2],[1,3]] s.findMinHeightTrees(n, given)
0d30f622972f7d20db406f0ff6ea0d1f9f20c116
thiagoiferreira/treinamento-git
/code.py
207
3.796875
4
print ('Treino') a = range(1,21) b = range (2,12) print(a) b = range (21,121) print(a) a = range(1,21) b = range (21,121) print('Nova Alteracao') for i in a: print(str(i) + 'BOA NOITE AMIGOS')
22be0688880e92ac8a4b8196533be6fb6b2177f0
iRoy7/python_examples
/while_with_condition.py
684
3.796875
4
list_test = [1, 2, 1, 2] value = 2 while value in list_test: list_test.remove(value) print(list_test) import time number = 0 target_tick = time.time() + 5 while time.time() < target_tick: number += 1 print("5초 동안 {}번 반복했습니다.".format(number)) #break/continue i = 0 while True: print("{}번째 반복문입니다.".format(i)) i = i + 1 input_text = input("> 종료하시겠습니까?(y): ") if input_text in ["y", "Y"]: print("반복을 종료합니다") break numbers = [5, 15, 6, 20, 7, 25] for number in numbers: if number < 10: continue print(number)
671bde6a5b6ba6e3e6dd70cf636b83161aa72447
bronydell/python-cipher
/vigenere.py
967
3.8125
4
from string import printable TABLE_WIDTH = len(printable) ASC_A = ord(printable[0]) # ThX Chines guy def init_table(): return [[chr((col + row) % TABLE_WIDTH + ASC_A) \ for col in range(TABLE_WIDTH)] \ for row in range(TABLE_WIDTH)] def encrypt(table, words, key): cipher = '' count = 0 key = key for ch in words: key_shift = ord(key[count % len(key)]) - ASC_A word_shift = ord(ch) - ASC_A cipher += table[key_shift][word_shift]; count += 1 return cipher def decrypt(words, key): text = '' count = 0 key = key for ch in words: shift = ord(ch) - ord(key[count % len(key)]) text += chr((shift + TABLE_WIDTH) % TABLE_WIDTH + ASC_A) count += 1 return text encrypted = encrypt(init_table(), words='My magic will tear you apart', key='astounding') print(encrypted) decrypted = decrypt(words=encrypted, key='astounding') print(decrypted)
efff4be6b8c21ae1cc6f997508e228d6612c29c8
cflin-cjcu/test-python
/6-f.py
121
3.765625
4
n=int(input()) a=1 # print(1,end=' ') b=1 # print(1,end=' ') i=3 while i <= n: a,b=b,a+b i += 1 print(b, end=' ')
97d289ea86a156567d5827bf7e42a42ba05355dd
jiangw41/LeetCode
/739.py
1,372
4.09375
4
''' 739. Daily Temperatures Medium Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. ''' class Solution: ''' As we traverse T, we use a stack to store the indexes of items that have not seen a warmer temperature. Every time we move to a new temperature, we pop out all the items on the stack from the right that are colder than this temperature. Complexity: time O(n*n); space O(n) ''' def dailyTemperatures(self, T: List[int]) -> List[int]: stack, ans = [], [] length = len(T) for _ in range(length): ans.append(0) for index in range(length): while stack: i = stack[-1] if T[i] < T[index]: stack.pop() ans[i] = index - i else: stack.append(index) break if not stack: stack.append(index) return ans
d1de22d6669152b83c2a37284461d43aa1b20d7d
chavarera/SentimentAnalyzerWithRealtimeVoice
/SentimentAnalyzerWithRealtimeVoice.py
1,623
3.609375
4
import speech_recognition as sr from textblob import TextBlob as blob import pyttsx3 ''' speech_recognition: For Realtime Speech Recognizer textblob : Sentimental analysis pyttsx3 : Text-to-speech conversion library if you got any error Please check Readme.md File To solve it. ''' __AUTHOR__='Ravishankar Chavare' __GITHUB__='https://github.com/chavarera' def takeSound(): ''' It Takes Microphone input From user and return string output ''' r = sr.Recognizer() mic = sr.Microphone() with mic as source: print("Listening....") r.adjust_for_ambient_noise(source) r.pause_threshold=0.6 audio=r.listen(source) try: print("Recognizing...") query=r.recognize_google(audio,language='en-in') except: return None return query def getsentiment(text): ''' Take input as text and Return Sentimental ''' tb=blob(text) result=tb.sentiment polarity=result.polarity print({'polarity':polarity,'text':text}) if polarity==0: return "Neutral" elif polarity>0: return "Positive" else: return "Negative" def Speak(audio): ''' Accept Text and Speak with Computer voice ''' engine=pyttsx3.init('sapi5') voices=engine.getProperty('voices') engine.setProperty("voice",voices[0].id) engine.say(audio) engine.runAndWait() while True: print() text=takeSound() if text is not None: state=getsentiment(text) speak_text='I think You Are speaking {} thought'.format(state) print("Computer:",speak_text) Speak(speak_text)
1477f881644208f1623068e0b584ecef97794173
Akshay-Chandelkar/PythonTraining2019
/Ex32_ValidTime.py
521
4.0625
4
def ValidTime(hh,mm,ss): if hh >= 0 and hh < 25: if mm >= 0 and mm < 60: if ss > 0 and ss < 60: print("The time {}:{}:{} is valid.".format(hh,mm,ss)) else: print("ss %d is invalid." %ss) else: print("mm %d is invalid." %mm) else: print("hh %d is invalid." %hh) def main(): hh,mm,ss = eval(input("Enter time in hh,mm,ss format :: ")) ValidTime(hh,mm,ss) if __name__ == '__main__': main()
be7a3a09dd9a229fc630c52a036ad3af4e2b813a
robsondrs/Exercicios_Python
/ex043.py
486
3.75
4
peso = float(input('Qual é seu peso? (Kg) ')) alt = float(input('Qual é sua altura? (m) ')) imc = peso / alt ** 2 print('O IMC dessa pessoa é de {:.1f}'.format(imc)) if imc < 18.5: print('Você esta ABAIXO DO PESO normal.') elif imc < 25: print('Parabéns, você esta na faixa de PESO NORMAL.') elif imc < 30: print('Você esta com SOBREPESO.') elif imc < 40: print('Você esta em OBESIDADE.') elif imc >= 40: print('Você está em OBESIDADE MORBIDA, cuidado!.')
fa7bdd13db37666ab4ab8a7f690f794837953cff
andylshort/dotfiles
/bin/filter-row
1,069
3.9375
4
#!/usr/bin/python3 import argparse import csv import fileinput def create_parser(): parser = argparse.ArgumentParser(description="Filters rows from csv") parser.add_argument("-f", "--file", type=str, help="Path to csv file to filter") parser.add_argument("-i", "--indices", metavar="I", type=int, nargs="+", help="List of zero-indexed row indices to extract") return parser def print_filtered_rows(target, indices): for index, data in enumerate(target): if index in indices: print(",".join(data)) def main(): parser = create_parser() args = parser.parse_args() indices = args.indices file = None if args.file is None: file = fileinput.input("-") for i, l in enumerate(file): if i in indices: print(l.strip()) else: with open(args.file, "r") as f: csv_f = csv.reader(f) for index, data in enumerate(csv_f): if index in indices: print(",".join(data)) if __name__ == "__main__": main()
c1c3a272670b97f5d81676e7d4f143816b224a4e
shekhar-hippargi/test
/recommendation_system/surprise_library_exploration/ContentBased/scripts/preprocessing.py
2,193
3.921875
4
# Data frame manipulation library import pandas as pd # Math functions, we'll only need the sqrt function so let's import only that from math import sqrt import numpy as np import matplotlib.pyplot as plt # Loading datasets # Storing the movie information into a pandas dataframe movies_df = pd.read_csv('../data/movies.csv') # Storing the user information into a pandas dataframe ratings_df = pd.read_csv('../data/ratings.csv') # Preprocessing movies_df # remove 'year' from title and make new column # Using regular expressions to find a year stored between parentheses # We specify the parantheses so we don't conflict with movies that have years in their titles movies_df['year'] = movies_df.title.str.extract('(\(\d\d\d\d\))',expand=False) # Removing the parentheses movies_df['year'] = movies_df.year.str.extract('(\d\d\d\d)',expand=False) # Removing the years from the 'title' column movies_df['title'] = movies_df.title.str.replace('(\(\d\d\d\d\))', '') # Applying the strip function to get rid of any ending whitespace characters that may have appeared movies_df['title'] = movies_df['title'].apply(lambda x: x.strip()) # print(movies_df.head()) # Every genre is separated by a | so we simply have to call the split function on | movies_df['genres'] = movies_df.genres.str.split('|') # print(movies_df.head()) # Copying the movie dataframe into a new one since we won't need to use the genre information in our first case. moviesWithGenres_df = movies_df.copy() # For every row in the dataframe, iterate through the list of genres and place a 1 into the corresponding column for index, row in movies_df.iterrows(): for genre in row['genres']: moviesWithGenres_df.at[index, genre] = 1 # Filling in the NaN values with 0 to show that a movie doesn't have that column's genre moviesWithGenres_df = moviesWithGenres_df.fillna(0) print(moviesWithGenres_df.head()) # Now Preprocessing ratings_df ratings_df = ratings_df.drop('timestamp', 1) # print(ratings_df.head()) # movies_df.to_csv("../preprocessedData/moviesPreprocessed.csv", index=False) # moviesWithGenres_df.to_csv("../preprocessedData/moviesWithGenres.csv", index=False) print(moviesWithGenres_df.shape)
5a669b1d387f4836a989e06596a787526483d69c
TorpidCoder/Python
/HeadFirst_DocQuestions/B16.py
125
4.0625
4
letter = input("Please enter a letter : ") if(letter.islower()): print(letter.upper()) else: print(letter.lower())
a0d50b703df2c6905bccd4271d862c2d56393894
PetitPandaRoux/python_katas
/next_palindrome/next_palindrome.py
159
3.9375
4
def is_palindrome(number): number_string = str(abs(number)) if number_string[::-1] == number_string: return True else: return False
c6d9476190e9973650eeb26f3ac052201de2faad
PrivateGoose/LaboratorioRepeticionRemoto
/mayor.py.py
308
3.875
4
n=int(input("De 10 números cuantos son positivos, negativos y cero")) pos=0 neg=0 cero=0 conta=0 if n>0: pos=pos+1 if n<0: neg=neg+1 if n=0: cero=cero+1 while (conta <=10) #Comment 1 print("Hay {} números positivos, hay {} números negativos y hay {} ceros".format(pos,neg,cero))
42d857c67a0b51fbc657c1efe2f87282e7555560
taeheechoi/coding-practice
/F_next-greater-element-i.py
1,569
3.921875
4
# https://leetcode.com/problems/next-greater-element-i/ # Example 1: # Input: nums1 = [4,1,2], nums2 = [1,3,4,2] # Output: [-1,3,-1] # Explanation: The next greater element for each value of nums1 is as follows: # - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. # - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. # - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. # Example 2: # Input: nums1 = [2,4], nums2 = [1,2,3,4] # Output: [3,-1] # Explanation: The next greater element for each value of nums1 is as follows: # - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. # - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1 class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: result = [] for num1 in nums1: for i, num2 in enumerate(nums2): if num1 == num2: if i+1 >= len(nums2): result.append(-1) else: found = False for num3 in nums2[i+1:]: if num1 < num3: result.append(num3) found = True break if not found: result.append(-1) return result
e635cec1dd0b5d9d02443bbe208fc295bef04d63
Shorokhov-A/repo-algorithms_python
/lesson_3/task_3_2.py
203
3.828125
4
numbers = (8, 3, 15, 6, 4, 2) even_numbers_indices = [] for idx in range(len(numbers)): if numbers[idx] % 2 == 0: even_numbers_indices.append(idx) print(numbers) print(even_numbers_indices)
0f37d14b91effcf6a79f9cf0f27c2d42e7ed1d4e
Bzan96/FreeCodeCamp_Projects
/Scientific_Computing_with_Python/polygon_area_calculator/shape_calculator.py
2,035
3.734375
4
import math def handle_undefined_values(height, width): if height == None and width == None: raise Exception("None", "height and width are not set.") elif height == None: raise Exception("None", "height is not set.") elif width == None: raise Exception("None", "width is not set.") class Rectangle: def __init__(self, width, height): handle_undefined_values(height, width) self.width = width self.height = height def __str__(self): return "Rectangle(width=%(width)s, height=%(height)s)"%{ "width": self.width, "height": self.height } def set_width(self, width): self.width = width def set_height(self, height): self.height = height def get_area(self): handle_undefined_values(self.height, self.width) return self.height * self.width def get_perimeter(self): handle_undefined_values(self.height, self.width) return (2 * self.width + 2 * self.height) def get_diagonal(self): handle_undefined_values(self.height, self.width) return ((self.width ** 2 + self.height ** 2) ** .5) def get_picture(self): handle_undefined_values(self.height, self.width) if self.width > 50 or self.height > 50: return "Too big for picture." horizontal = ["*"] * self.width picture = "" for row in range(self.height): for star in horizontal: picture += star picture += "\n" return picture def get_amount_inside(self, shape): horizontal = self.width / shape.width vertical = self.height / shape.height return math.floor(horizontal * vertical) class Square(Rectangle): def __init__(self, side): super().__init__(side, side) def __str__(self): return "Square(side=%(side)s)"%{ "side": self.width, } def set_side(self, side): self.height = side self.width = side def set_width(self, width): self.width = width self.height = width def set_height(self, height): self.height = height self.width = height
0d359a3c30b12076205a4b030b7723ecf65b7ba0
asiguqaCPT/Hangman_1
/hangman.py
1,137
4.1875
4
#TIP: use random.randint to get a random word from the list import random def read_file(file_name): """ TODO: Step 1 - open file and read lines as words """ words = open(file_name,'r') lines = words.readlines() return lines def select_random_word(words): """ TODO: Step 2 - select random word from list of file """ r_word_pos = random.randint(0,len(words)-1) r_word = words[r_word_pos] letter_pos = random.randint(0,len(r_word)-1) letter = r_word[letter_pos] word_prompt = r_word[:letter_pos] + '_' + r_word[letter_pos+1:] print("Guess the word:",word_prompt) return r_word def get_user_input(): """ TODO: Step 3 - get user input for answer """ guess = input("Guess the missing letter: ") return guess def run_game(file_name): """ This is the main game code. You can leave it as is and only implement steps 1 to 3 as indicated above. """ words = read_file(file_name) word = select_random_word(words) answer = get_user_input() print('The word was: '+word) if __name__ == "__main__": run_game('short_words.txt')
019af9dd2bdc9511e090453e21604e88386768e9
luketibbott/Predicting-Shelter-Animal-Outcomes
/breeds.py
745
3.578125
4
# Parses a wikipedia page listing dog breeds recognized by the American Kennel Club and the # group of dog each breed belongs to. import wikipedia dog_breeds = wikipedia.page('List of dog breeds recognized by the American Kennel Club') counter = 0 dog_groups = dict() for line in dog_breeds.content.split('\n')[1:]: counter += 1 split = False # Catch text error with no space after comma if (', ' in line) and (counter < 272): line = line.split(', ') split = True elif (',' in line) and (counter < 272): line = line.split(',') split = True # Split being true means the line we're interested in has dog breed info if split: dog_groups[line[0]] = line[1] print(dog_groups)
9eca73ddd171a14fd45fbd6986dc7faeb2d8525d
bigtree1952/zb
/caoke.py
1,322
3.703125
4
#!/usr/bin/env python # coding=utf-8 import sys import os #运行方式安装好python #D:\>python caoke.py a1.txt 即可以生成如下 #转换成功!文件为: coverted_a1.txt def convert(source_file): dest_file = 'coverted_' + os.path.basename(source_file) ret = {} with open(source_file,'r',encoding='UTF-8') as f: for line_no, line in enumerate(f): line = str(line).strip() try: name, url = line.split(',') if name in ret: ret[name] = ret[name] + '#' + url else: ret[name] = url except ValueError: pass with open(dest_file, 'w', encoding='UTF-8') as d: for name, urls in ret.items(): line = name + ',' + urls + '\n' d.write(line) print("转换成功!文件为: %s" % dest_file) if __name__ == '__main__': if len(sys.argv) == 1: print("请在脚本后面指定输入源文件!") elif len(sys.argv) >= 2: file_name = sys.argv[1] source_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name) if os.path.isfile(file_name): convert(file_name) elif os.path.isfile(source_file): convert(source_file) else: print ("不存在源文件:%s" % file_name)
2887d886574a5be45d2ed29e0a12817b02bdf277
PawarKishori/Alignment1
/Transliteration/Transliterate_Dict.py
3,272
3.546875
4
#This program creates a transliteration dictionary for entire corpus once. #This program calls Roja mam's program which runs in python2 #import check_transliteration.py as ct ##Pending task to do, once roja mam completes this will be complete def remove_punct_from_word(word): word=word.translate(word.maketrans('','',string.punctuation)) return(word) def extract_only_words_from_sent(sent): all_words = sent.split(" ") #print(all_words) plain_words=[] for word in all_words: plain_words.append(remove_punct_from_word(word)) #print(plain_words) while "" in plain_words: #If E_sentence/H_sentence contains 2 sentence remove an empty word plain_words.remove("") return(plain_words) def corpus_to_sentence(corpus): cor=open(corpus,"r") lines=cor.read().split("\n") return lines def create_dictionary_from_exceptional_dictionary(filename): ex = open(filename,"r") ex_dic = {} for line in ex : ex_lst = line.strip().split('\t') ex_dic[ex_lst[0]] = ex_lst[1] return(ex_dic) def check_from_exceptional_dic(ex_dic, e,h): flag=0 dic_stack=[] for key in ex_dic: ex_list = ex_dic[key].split('/') for each in ex_list: val = key + ' ' + each dic_stack.append(val) for i in range(0, len(dic_stack)): e_key = dic_stack[i].split() if e_key[0]==e and e_key[1]==h : flag=1 break if flag == 1 : #print(e,h) str_temp=e +" <> "+ h if str_temp not in final : final.append(str_temp) def transliterate_Dict(): e_lines=corpus_to_sentence(e_corpus) h_lines=corpus_to_sentence(h_corpus) for e_line,h_line in zip(e_lines,h_lines): e_words=extract_only_words_from_sent(e_line) h_words=extract_only_words_from_sent(h_line) e_words = e_words[1:] #print(e_words) upper_words = [e_word for e_word in e_words if e_word[0].isupper()] #print(upper_words) for e in upper_words: for h in h_words: check_from_exceptional_dic(excep_dic, e,h) #ct.check(e,w) #print(e,h) call_roja_prog = "python "+roja_prog_path+" "+ e + " " + h +" "+ dict_path+"/Sound-dic.txt" #print(e,h,commands.getoutput(call_roja_prog)) if subprocess.getoutput(call_roja_prog)=="Given word is transliterate word": #print(call_roja_prog) print(e,h) str_temp=e +" <> "+ h if str_temp not in final : final.append(str_temp) for i in final: print(i) f.write(i+"\n") import sys, string, os, itertools import subprocess e_corpus=sys.argv[1] h_corpus=sys.argv[2] roja_prog_path = os.getenv('HOME_alignment')+'/Transliteration/check_transliteration.py' dict_path = os.getenv('HOME_alignment')+'/Transliteration/dictionary' print(dict_path) final=[] f=open(dict_path+"/lookups/Lookup_transliteration_" + e_corpus + ".txt", "w") excep_dic = create_dictionary_from_exceptional_dictionary(dict_path+"/Exception-dic.txt") transliterate_Dict()
26b757c234e5903d175d099a005b338b0a9a390d
Su-Shee/open-data-weather
/pandas-weather.py
1,196
3.703125
4
#!/usr/bin/env python import sys from datetime import datetime, date, time import pandas from pandas import Series, DataFrame, Panel import matplotlib.pyplot as plt import matplotlib as matplot matplot.rc('figure', figsize=(12, 8)) data = pandas.read_csv('tageswerte-1948-2012.csv', parse_dates = {'Messdatum': ['MESS_DATUM']}, index_col = 'Messdatum') # extract certain columns we're interested in ticks = data.ix[:, ['NIEDERSCHLAGSHOEHE', 'LUFTTEMPERATUR']] # display 5 first rows print ticks.head() # output a couple of basic statistics - minimum, maximum, mean, etc print ticks.describe() # get a specific value - lowest values of two columns print ticks.min() # get a specific value - highest temperatur print ticks.LUFTTEMPERATUR.max() #extract a specific column temperature = ticks.LUFTTEMPERATUR # display 20 rows print temperature.head(20) # display value of rows 5 to 8 print temperature.ix[5:8] # create a simple plot by date range temperature['1948-01-01':'1948-01-31'].plot() # basic configuration of plot plt.ylim(-25.0, 40.0) plt.legend() plt.axhline(linewidth = 1, color = 'g') # display the whole thing plt.show()
77d0b4efc172374d6e00e841e03279c27964635e
zilunzhang/puzzles
/puzzles-BFS-DFS/mn_puzzle.py
7,476
3.53125
4
from puzzle import Puzzle class MNPuzzle(Puzzle): """ An nxm puzzle, like the 15-puzzle, which may be solved, unsolved, or even unsolvable. """ def __init__(self, from_grid, to_grid): """ MNPuzzle in state from_grid, working towards state to_grid @param MNPuzzle self: this MNPuzzle @param tuple[tuple[str]] from_grid: current configuration @param tuple[tuple[str]] to_grid: solution configuration @rtype: None """ # represent grid symbols with letters or numerals # represent the empty space with a "*" assert len(from_grid) > 0 assert all([len(r) == len(from_grid[0]) for r in from_grid]) assert all([len(r) == len(to_grid[0]) for r in to_grid]) self.n, self.m = len(from_grid), len(from_grid[0]) self.from_grid, self.to_grid = from_grid, to_grid def __eq__(self, other): """ Return whether MNPuzzle self is equivalent to other. @type self: MNPuzzle @type other: MNPuzzle @rtype: bool >>> start_grid = (("*", "2", "3"), ("1", "4", "5")) >>> target_grid = (("1", "2", "3"), ("4", "5", "*")) >>> puzzle1 = MNPuzzle(start_grid, target_grid) >>> puzzle2 = MNPuzzle(start_grid, target_grid) >>> puzzle1 == puzzle2 True >>> puzzle3 = MNPuzzle(target_grid, start_grid) >>> puzzle1 == puzzle3 False """ return all([type(self) == type(other), self.from_grid == other.from_grid, self.to_grid == other.to_grid]) def __str__(self): """ Return a human-readable string representation of MNPuzzle self. @type self: MNPuzzle @rtype: str >>> start_grid = (("*", "2", "3"), ("1", "4", "5")) >>> target_grid = (("1", "2", "3"), ("4", "5", "*")) >>> puzzle = MNPuzzle(start_grid, target_grid) >>> print(puzzle) * 2 3 1 4 5 <BLANKLINE> >>> from_grid = (("1", "2", "3"), ("*", "5", "6")) >>> to_grid = (("1", "2", "3"), ("5", "6", "*")) >>> puzzle_1 = MNPuzzle(from_grid, to_grid) >>> print(puzzle_1) 1 2 3 * 5 6 <BLANKLINE> """ grid = self.from_grid result = "" for i in range(len(grid)): result += " ".join(grid[i]) + "\n" return result def __repr__(self): """ Return representation of nxm puzzle (self) as string that can be evaluated into an equivalent n x m puzzle. @type self: MNPuzzle @rtype: string >>> grid1 = (('A', 'C', 'B', 'D'), ('F', 'E', 'G', 'H'), ... ('M', 'N', 'O', '*')) >>> grid2 = (('A', 'B', 'C', 'D'), ('E', 'F', 'G', 'H'), ... ('M', 'N', 'O', '*')) >>> MNP = MNPuzzle(grid1, grid2 ) >>> MNP.__repr__() 'This is a 3 X 4 NMPuzzle' """ row_length = self.m col_length = self.n return "This is a {} X {} NMPuzzle".format(col_length, row_length) def extensions(self): """ Return list of extensions of MNPuzzle self. @type self: MNPuzzle @rtype: list[MNPuzzle] >>> start_grid = (("1", "2", "3", "*"), ("4", "5", "6", "7")) >>> target_grid = (("1", "2", "3", "4"), ("5", "6", "7", "*")) >>> puzzle = MNPuzzle(start_grid, target_grid) >>> L = puzzle.extensions() >>> len(L) 2 >>> print(L[0]) 1 2 * 3 4 5 6 7 <BLANKLINE> >>> print(L[1]) 1 2 3 7 4 5 6 * <BLANKLINE> """ def transform(grid_): """ Transpose between tuple-grid and list-grid. @type grid_: tuple(tuple(str)) | list[list[str]] @rtype: list[list[str]] | tuple(tuple(str)) """ # tuple-grid -> list-grid if isinstance(grid_, tuple): return [list(row) for row in grid_] # list-grid -> tuple-grid if isinstance(grid_, list): return tuple(tuple(row) for row in grid_) grid = transform(self.from_grid) extension = [] # <l>: length of col l = len(grid) # <w>: length of row w = len(grid[0]) # get the Y-coordinate for the point for y in range(l): # get the X-coordinate for the point for x in range(w): # we only consider the area around "*" if grid[y][x] == "*": # (*)(a) -> (a)(*) if x + 1 < w: new_grid = [list(row) for row in grid] new_grid[y][x] = new_grid[y][x + 1] new_grid[y][x + 1] = "*" extension.append(MNPuzzle(transform(new_grid), self.to_grid)) # (a)(*) -> (*)(a) if x - 1 >= 0: new_grid = [list(row) for row in grid] new_grid[y][x] = new_grid[y][x - 1] new_grid[y][x - 1] = "*" extension.append(MNPuzzle(transform(new_grid), self.to_grid)) # (*) -> (a) # (a) -> (*) if y + 1 < l: new_grid = [list(row) for row in grid] new_grid[y][x] = new_grid[y + 1][x] new_grid[y + 1][x] = "*" extension.append(MNPuzzle(transform(new_grid), self.to_grid)) # (a) -> (*) # (*) -> (a) if y - 1 >= 0: new_grid = [list(row) for row in grid] new_grid[y][x] = new_grid[y - 1][x] new_grid[y - 1][x] = "*" extension.append(MNPuzzle(transform(new_grid), self.to_grid)) return extension def is_solved(self): """ Return whether MNPuzzle self is solved. @type self: MNPuzzle @rtype: bool >>> start_grid = (("1", "2", "3", "4"), ("5", "6", "7", "*")) >>> target_grid = (("1", "2", "3", "4"), ("5", "6", "7", "*")) >>> puzzle_1 = MNPuzzle(start_grid, target_grid) >>> puzzle_1.is_solved() True >>> start_grid_1 = (("1", "2", "3", "*"), ("4", "5", "6", "7")) >>> puzzle_2 = MNPuzzle(start_grid_1, target_grid) >>> puzzle_2.is_solved() False """ return self.from_grid == self.to_grid if __name__ == "__main__": import doctest doctest.testmod() target_grid = (("1", "2", "3"), ("4", "5", "*")) start_grid = (("*", "2", "3"), ("1", "4", "5")) from puzzle_tools import breadth_first_solve, depth_first_solve from time import time start = time() solution = breadth_first_solve(MNPuzzle(start_grid, target_grid)) end = time() print("BFS solved: \n\n{} \n\nin {} seconds".format( solution, end - start)) start = time() solution = depth_first_solve((MNPuzzle(start_grid, target_grid))) end = time() print("DFS solved: \n\n{} \n\nin {} seconds".format( solution, end - start))
d266388b5c4382d697f0717915d8fd8cd1a457cc
oneshan/Leetcode
/accepted/097.interleaving-string.py
1,570
3.734375
4
# # [97] Interleaving String # # https://leetcode.com/problems/interleaving-string # # Hard (24.41%) # Total Accepted: # Total Submissions: # Testcase Example: '""\n""\n""' # # # Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and # s2. # # # # For example, # Given: # s1 = "aabcc", # s2 = "dbbca", # # # When s3 = "aadbbcbcac", return true. # When s3 = "aadbbbaccc", return false. # # class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ n1, n2, n3 = len(s1), len(s2), len(s3) if n3 != n1 + n2: return False dp = [[False for _ in range(n2 + 1)] for _ in range(n1 + 1)] dp[0][0] = True for i in range(n1): dp[i + 1][0] = dp[i][0] and s1[i] == s3[i] for j in range(n2): dp[0][j + 1] = dp[0][j] and s2[j] == s3[j] for i in range(n1): for j in range(n2): dp[i + 1][j + 1] = (dp[i][j + 1] and s1[i] == s3[i + j + 1]) or \ (dp[i + 1][j] and s2[j] == s3[i + j + 1]) return dp[-1][-1] if __name__ == "__main__": sol = Solution() assert(sol.isInterleave("a", "", "a") is True) assert(sol.isInterleave("", "b", "b") is True) s1 = "aabcc" s2 = "dbbca" assert(sol.isInterleave(s1, s2, "aadbbcbcac") is True) assert(sol.isInterleave(s1, s2, "aadbbbaccc") is False)
26ec638ed1cd5c3cc65dd69956407d9653219468
gabriellaec/desoft-analise-exercicios
/backup/user_139/ch22_2020_03_04_11_28_13_775698.py
102
3.671875
4
a = int(input('Quantos cigaros por dia?') b = int(input('Há quantos anos?') p = (a * 10) * b print(p)
9ff556f4126ee4fa9a8db224cadd0684a4458bbc
Serg-Protsenko/NIX_Education_Python
/BEGINNER_Python_Level_1/Task_09_two_list/Task_09.py
592
4.5
4
# Создать функцию, которая принимает на вход два списка: первый — список, который нужно # очистить от определённых значений, второй — список тех значений, от которых нужно очистить. # Например, list1 = [1, 2, 3, 4, 5], list2 = [1, 3, 4], функция должна вернуть [2, 5] def two_list(list_1, list_2): return list(set(list_1) - set(list_2)) list1 = [1, 2, 3, 4, 5] list2 = [1, 3, 4] print(two_list(list1, list2))
c5e03974ee795edd8a89e232bb1024d4a0a7b7d5
smartinsert/CodingProblem
/product_subarrays/maximum_product_subarray.py
1,350
4.375
4
""" Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array. Example 1: Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. """ def max_product_subarray(nums: []): if not nums: return 0 current_min, current_max, result = nums[0], nums[0], nums[0] for i in range(1, len(nums)): compare = (current_min * nums[i], current_max * nums[i], nums[i]) current_max, current_min = max(compare), min(compare) result = max(result, current_max) return result def max_product_subarray_another(nums: []): if not nums: return 0 max_product = 0 for i in range(len(nums)): product = nums[i] for j in range(i + 1, len(nums)): product *= nums[j] max_product = max(max_product, product) return max_product print(max_product_subarray([2, 3, -2, 4])) print(max_product_subarray([-2, 0, -1])) print(max_product_subarray_another([-2, 0, -1])) print(max_product_subarray_another([2, 3, -2, 4]))
afe9df8c2d8bc493de4d813e4f4f61a33ef5220a
Aliexer/calcular_area_fg_geometrica.py
/area_geometricas.py
1,902
4.0625
4
#CALCULO DE FIGURAS GEOMETRICAS #esta funcion dibuja un triangulo def triangulito(l): for i in range(0,l,1): for j in range(0, i+1, 1): print("*", end="") print("") #esta funcion dibuja un cuadrado def cuadrito(m,n): for i in range(1, m+1): for j in range(1,n+1): print("*", end="") print(" ") #el ciclo while condicionado por un True while True: #figuras a las cuales se le puede calcular el area print("Bienvenido a Geometric Tool") print("1_TRIANGULO") print("2_CUADRADO") print("3_CIRCULO") print("4_RECTANGULO") #seleccion de la figura a calcular el area seleccion = (input("Que figura desea calcular el area:")) seleccion2 =seleccion.upper() #confirmacion de la figura seleccionada print("Ud escogio un {}".format(seleccion2)) #if anidhado. se desplegara una opcion de acuerdo a la seleccion. if seleccion2 == "CUADRADO": dato1=int(input("ingrese el valor de uno de los lados del cuadrado: ")) area1=dato1*4 print("el area del cuadrado es:",area1) elif seleccion2 == "TRIANGULO": dato2=int(input("ingrese el valor del lado del triangulo:")) dato2a=int(input("ingrese el valor del alto del triangulo:")) area2=(dato2*dato2a)/2 print("el area del triangulo es:",round(area2)) triangulito(5) elif seleccion2 == "CIRCULO": dato3=int(input("ingrese el valor del radio:")) area3=(3.1416)*(dato3)**2 print("el area del circulo es:",area3) elif seleccion2 == "RECTANGULO": dato4=int(input("ingrese el valor del alto del rectangulo:")) dato5=int(input("ingrese el valor del ancho del rectangulo:")) area4 = dato4*dato5 print("el area del rectangulo es:",area4) cuadrito(dato4,dato5) else: print("Introduzca un valor correcto, CUADRADO, TRIANGULO, CIRCULO O RECTANGULO") #condicion para seguir con el ciclo o salir del programa seguir = int(input("1 para seguir 0 para salir: ")) if seguir != 1: break print("hasta luego")
63548e60872ab436938c60a8b79d9d443268abe1
Uttam1982/PythonTutorial
/10-Python-Exceptions/05-Catching-Specific-Exceptions-in-Python.py
833
4.34375
4
#------------------------------------------------------------------------------------------ # Catching Specific Exceptions in Python #------------------------------------------------------------------------------------------ # A try clause can have any number of except clauses to handle different exceptions, # however, only one will be executed in case an exception occurs. # We can use a tuple of values to specify multiple exceptions in an except clause. # Here is an example pseudo code. #------------------------------------------------------------------------------------------ try: # do something pass except ValueError as ve: # handle ValueError exception pass except(TypeError, ZeroDivisionError): #handle multiple exception # Typeerror and ZeroDivisionError pass except: # handle all exceptions pass
ee91560206660719417f4ffedc75772a436845cb
LokeshKD/MachineLearning
/ML4SE/Pandas/dataframe.py
1,388
3.546875
4
import pandas as pd ## 2-D data df = pd.DataFrame() # Newline added to separate DataFrames print('{}\n'.format(df)) df = pd.DataFrame([5, 6]) print('{}\n'.format(df)) df = pd.DataFrame([[5,6]]) print('{}\n'.format(df)) df = pd.DataFrame([[5, 6], [1, 3]], index=['r1', 'r2'], columns=['c1', 'c2']) print('{}\n'.format(df)) df = pd.DataFrame({'c1': [1, 2], 'c2': [3, 4]}, index=['r1', 'r2']) print('{}\n'.format(df)) ## Appending rows... df = pd.DataFrame([[5, 6], [1.2, 3]]) ser = pd.Series([0, 0], name='r3') # index name for the new row df_app = df.append(ser) print('{}\n'.format(df_app)) df_app = df.append(ser, ignore_index=True) # All indices will be 0,1... print('{}\n'.format(df_app)) df2 = pd.DataFrame([[0,0],[9,9]]) df_app = df.append(df2) # New added indices start from 0, 1... print('{}\n'.format(df_app)) ## Dropping data df = pd.DataFrame({'c1': [1, 2], 'c2': [3, 4], 'c3': [5, 6]}, index=['r1', 'r2']) # Drop row r1 df_drop = df.drop(labels='r1') print('{}\n'.format(df_drop)) # Drop columns c1, c3 df_drop = df.drop(labels=['c1', 'c3'], axis=1) print('{}\n'.format(df_drop)) df_drop = df.drop(index='r2') print('{}\n'.format(df_drop)) df_drop = df.drop(columns='c2') print('{}\n'.format(df_drop)) df.drop(index='r2', columns='c2') print('{}\n'.format(df_drop)
89393cbeeaeb1c65f8988ffe6930667660fe1dcd
NeelJVerma/Daily_Coding_Problem
/Construct_Sentence/main.py
1,325
4.0625
4
""" Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox']. Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond']. """ def construct_sentence(dictionary, string): returnlist = [] checkstring = [] for char in string: checkstring.append(char) if ''.join(checkstring) in dictionary: returnlist.append(''.join(checkstring)) checkstring = [] return returnlist print(True if construct_sentence(['quick', 'brown', 'the', 'fox'], 'thequickbrownfox') == ['the', 'quick', 'brown', 'fox'] else False) print(True if construct_sentence(['bed', 'bath', 'bedbath', 'and', 'beyond'], 'bedbathandbeyond') == ['bed', 'bath', 'and', 'beyond'] else False) print(True if construct_sentence(['a'], 'a') == ['a'] else False) print(True if construct_sentence(['ab', 'c', 'd'], 'abdc') == ['ab', 'd', 'c'] else False)
57fa5c44139713a0533b98670f74454ab346d500
Henrique970/Monitoria
/21.py
988
3.703125
4
import random nome = input('Informe o seu nome: ') qt = int(input('Informe a quantidade de partidas que você que jogar: ')) quantidade_jogador = 0 quantidade_computador = 0 for n in range(1, qt + 1): escolha = input('Escolha se quer par ou impa[p/i]: ') numero = int(input('Informe o número: ')) computador = random.randint(1,10) print('O computador escolheu,',computador) soma = numero + computador if escolha == 'p': if soma % 2 == 0: print('Você Ganhou',nome) quantidade_jogador = quantidade_jogador + 1 else: print('Você perdeu',nome) quantidade_computador += 1 elif escolha == 'i': if soma % 2 == 1: print('Você Ganhou',nome) quantidade_jogador += 1 else: print('Você perdeu',nome) quantidade_computador += 1 print('Você ganhou',quantidade_jogador,'vezes') print('O computador ganhou',quantidade_computador,'vezes')
3b8ea81eff17df67e7c58d47dd6d757545eb64b8
Python-x/Python-x
/寒假作业/6/喜欢的数字2.py
193
3.515625
4
favorite_number = {"小红":["1","2","3"],"小刚":["4","5","6"],"小李":["7","8","9"]} for k,v in favorite_number.items(): print("%s最喜欢的数字有:"%k) for i in v: print("%s\t"%i)
d524c3c39c789873a559b7972537cb99f87c1958
alexforcode/py_arcadegames_craven
/ch18/18.5.py
242
3.515625
4
def getInput(): userInput = input("Введите что-нибудь: ") if len(userInput) == 0: raise IOError("Пользователь ничего не ввёл") try: getInput() except IOError as e: print(e)
94d5d5a14eec346776108c5cdb4792d75c068977
hputterm/Projects
/HMM/HMM.py
21,894
4.21875
4
import random import numpy as np class HiddenMarkovModel: ''' Class implementation of Hidden Markov Models. ''' def __init__(self, A, O): ''' Initializes an HMM. Assumes the following: - States and observations are integers starting from 0. - There is a start state (see notes on A_start below). There is no integer associated with the start state, only probabilities in the vector A_start. - There is no end state. Arguments: A: Transition matrix with dimensions L x L. The (i, j)^th element is the probability of transitioning from state i to state j. Note that this does not include the starting probabilities. O: Observation matrix with dimensions L x D. The (i, j)^th element is the probability of emitting observation j given state i. Parameters: L: Number of states. D: Number of observations. A: The transition matrix. O: The observation matrix. A_start: Starting transition probabilities. The i^th element is the probability of transitioning from the start state to state i. For simplicity, we assume that this distribution is uniform. ''' self.L = len(A) self.D = len(O[0]) self.A = A self.O = O self.A_start = [1. / self.L for _ in range(self.L)] def viterbi(self, x): ''' Uses the Viterbi algorithm to find the max probability state sequence corresponding to a given input sequence. Arguments: x: Input sequence in the form of a list of length M, consisting of integers ranging from 0 to D - 1. Returns: max_seq: State sequence corresponding to x with the highest probability. ''' M = len(x) # Length of sequence. # The (i, j)^th elements of probs and seqs are the max probability # of the prefix of length i ending in state j and the prefix # that gives this probability, respectively. # # For instance, probs[1][0] is the probability of the prefix of # length 1 ending in state 0. probs = [[0. for _ in range(self.L)] for _ in range(M + 1)] seqs = [[0 for _ in range(self.L)] for _ in range(M + 1)] # Initialize the start state for state in range(0,self.L): probs[0][state] = np.log(self.A_start[state])+np.log(self.O[state][x[0]]) seqs[0][state] = 0 # Next we iterate for all the remaining possibilities # Iterate through every position in the sequence for t in range(1, M): # Iterate through every state in this position for state in range(0,self.L): # Compute the log probability log_transition_probabilities = [probs[t-1][prev_st]+np.log(self.A[prev_st][state])+np.log(self.O[state][x[t]]) for prev_st in range(0,self.L)] # Find which previous state maximized log probability maximum_log_probability_coordinate = np.argmax(log_transition_probabilities) maximum_log_probability = log_transition_probabilities[maximum_log_probability_coordinate] # Update or dynamic programming probs[t][state] = maximum_log_probability seqs[t][state] = maximum_log_probability_coordinate # Update using output emission for state in range(0, self.L): log_transition_probabilities = [probs[M-1][prev_st]+np.log(self.A[prev_st][state]) for prev_st in range(0,self.L)] # Find which previous state maximized log probability maximum_log_probability_coordinate = np.argmax(log_transition_probabilities) maximum_log_probability = log_transition_probabilities[maximum_log_probability_coordinate] # Update or dynamic programming probs[M][state] = maximum_log_probability seqs[M][state] = maximum_log_probability_coordinate # We have finished generating probs and seqs so now we need to extract the max_seq max_seq = '' starting_coordinate = np.argmax(probs[M-1]) starting_value = seqs[M][starting_coordinate] max_seq += str(starting_value) for t in range(M-1, 0, -1): starting_value = seqs[t][starting_value] max_seq += str(starting_value) return max_seq[::-1] def forward(self, x, normalize=False): ''' Uses the forward algorithm to calculate the alpha probability vectors corresponding to a given input sequence. Arguments: x: Input sequence in the form of a list of length M, consisting of integers ranging from 0 to D - 1. normalize: Whether to normalize each set of alpha_j(i) vectors at each i. This is useful to avoid underflow in unsupervised learning. Returns: alphas: Vector of alphas. The (i, j)^th element of alphas is alpha_j(i), i.e. the probability of observing prefix x^1:i and state y^i = j. e.g. alphas[1][0] corresponds to the probability of observing x^1:1, i.e. the first observation, given that y^1 = 0, i.e. the first state is 0. ''' M = len(x) # Length of sequence. alphas = [[0. for _ in range(self.L)] for _ in range(M + 1)] for state in range(self.L): alphas[0][state] = self.A_start[state] # Initialize the alpha vector for state in range(self.L): alphas[1][state] = self.A_start[state] * self.O[state][x[0]]/sum(self.A_start) # # Loop through all of the tokens in the string for t in range(2, M+1): # Loop through all of the possible states current_sum = 0 for state in range(0, self.L): # Update the alphas at this coordinate with the sum of all # the transition probabilities. temp_var = sum([alphas[t-1][prev_st]*self.A[prev_st][state]*self.O[state][x[t-1]] for prev_st in range(0,self.L)]) current_sum += temp_var alphas[t][state] += temp_var if(normalize==True): for state in range(self.L): alphas[t][state] /= current_sum # return final matrix return alphas def backward(self, x, normalize=False): ''' Uses the backward algorithm to calculate the beta probability vectors corresponding to a given input sequence. Arguments: x: Input sequence in the form of a list of length M, consisting of integers ranging from 0 to D - 1. normalize: Whether to normalize each set of alpha_j(i) vectors at each i. This is useful to avoid underflow in unsupervised learning. Returns: betas: Vector of betas. The (i, j)^th element of betas is beta_j(i), i.e. the probability of observing prefix x^(i+1):M and state y^i = j. e.g. betas[M][0] corresponds to the probability of observing x^M+1:M, i.e. no observations, given that y^M = 0, i.e. the last state is 0. ''' M = len(x) # Length of sequence. betas = [[0. for _ in range(self.L)] for _ in range(M + 1)] # Initialize the last row as the ending probabilities for state in range(0, self.L): betas[M][state] = 1 # Loop through all of the tokens in backwards order for t in range(M - 1, 0, -1): # Loop through all of the states current_sum = 0 for state in range(0, self.L): # Update betas with the probability of the next betas temp_var = sum([betas[t+1][next_st]*self.A[state][next_st]*self.O[next_st][x[t]] for next_st in range(0,self.L)]) betas[t][state] += temp_var current_sum += temp_var if(normalize==True): for state in range(self.L): betas[t][state] /= current_sum # transition back using start current_sum = 0 for state in range(0, self.L): temp_var = sum([betas[t+1][next_st]*self.A_start[state]*self.O[next_st][x[0]] for next_st in range(0,self.L)]) betas[0][state] += temp_var current_sum += temp_var if(normalize==True): for state in range(self.L): betas[0][state] /= current_sum return betas def supervised_learning(self, X, Y): ''' Trains the HMM using the Maximum Likelihood closed form solutions for the transition and observation matrices on a labeled datset (X, Y). Note that this method does not return anything, but instead updates the attributes of the HMM object. Arguments: X: A dataset consisting of input sequences in the form of lists of variable length, consisting of integers ranging from 0 to D - 1. In other words, a list of lists. Y: A dataset consisting of state sequences in the form of lists of variable length, consisting of integers ranging from 0 to L - 1. In other words, a list of lists. Note that the elements in X line up with those in Y. ''' # Calculate each element of A using the M-step formulas. # Loop through every element of the A matrix. for a in range(self.L): for b in range(self.L): # Initialize variables for the numerator and denominator of the expression numerator_sum = 0 denominator_sum = 0 # Loop through every training example for training_label_list in Y: # Loop through every index in the training example for training_label_index in range(1, len(training_label_list)): # Update the numerator if(training_label_list[training_label_index]==b and training_label_list[training_label_index-1]==a): numerator_sum += 1 # Update the denominator if(training_label_list[training_label_index-1]==a): denominator_sum += 1 # Update A self.A[a][b] = numerator_sum/denominator_sum # Calculate each element of O using the M-step formulas. # Loop through every elements of the A matrix for w in range(self.D): for a in range(self.L): #Initialize the variables for the numerator and denominator of the expression numerator_sum = 0 denominator_sum = 0 # Loop through every training example for training_points_list, training_label_list in zip(X, Y): # Loop through every index in the training example for training_index in range(0, len(training_label_list)): # Update the numerator if(training_points_list[training_index]==w and training_label_list[training_index]==a): numerator_sum += 1 # Update the numerator if(training_label_list[training_index]==a): denominator_sum += 1 # Update O self.O[a][w] = numerator_sum/denominator_sum def unsupervised_learning(self, X, N_iters): ''' Trains the HMM using the Baum-Welch algorithm on an unlabeled datset X. Note that this method does not return anything, but instead updates the attributes of the HMM object. Arguments: X: A dataset consisting of input sequences in the form of lists of length M, consisting of integers ranging from 0 to D - 1. In other words, a list of lists. N_iters: The number of iterations to train on. ''' for i in range(N_iters): print(i) # Initialize numerator and denominator matrices A_numerator = np.zeros((self.L, self.L)) A_denominator = np.zeros(self.L) O_numerator = np.zeros((self.L, self.D)) O_denominator = np.zeros(self.L) # Loop through every training example for x in X: # Do the E step for this example alpha = self.forward(x, normalize = True) beta = self.backward(x, normalize = True) # Loop through every index in the example for t in range(1, len(x)+1): p1 = np.zeros(self.L) # Loop up to l to compute marginal probability 1 for a in range(self.L): # Update the marginal 1 probability p1[a] = beta[t][a] * alpha[t][a] # normalize p1 /= np.sum(p1) # Update everything except A_numerator O_denominator += p1 O_numerator[:,x[t-1]] += p1 # It is offset from the denominator of A if (t != len(x)): A_denominator += p1 # Loop through every index in the example for t in range(1, len(x)): p2 = np.zeros((self.L, self.L)) # Loop up to l,l to compute marginal probability 2 for a in range(self.L): for b in range(self.L): # Update the marginal 2 probability p2[a][b] = alpha[t-1][a] * beta[t][b] * self.O[b][x[t]] * self.A[a][b] # normalize p2 /= np.sum(p2) # Update the numerator of A A_numerator += p2 # Set A and O using the equations for the numerators and the denominators. for j in range(len(A_numerator[0])): A_numerator[:, j] /= A_denominator for j in range(len(O_numerator[0])): O_numerator[:, j] /= O_denominator #normalize self.A = A_numerator self.O = O_numerator # ta said that the solution code included this normalization step but it seems kind of redundant and incorrect # for row in self.A: # row /= np.sum(row) # for row in self.O: # row /= np.sum(row) self.A = self.A.tolist() self.O = self.O.tolist() def generate_emission(self, M): ''' Generates an emission of length M, assuming that the starting state is chosen uniformly at random. Arguments: M: Length of the emission to generate. Returns: emission: The randomly generated emission as a list. states: The randomly generated states as a list. ''' emission = [] states = [] i = 0 state = np.random.choice(np.array([i for i in range(self.L)]), p = np.array(self.A_start)) while(i < M): i = i+1 state = np.random.choice(np.array([i for i in range(self.L)]), p =np.array(self.A[state])/np.sum(self.A[state])) output = np.random.choice(np.array([o for o in range(self.D)]), p = np.array(self.O[state])/np.sum(self.O[state])) emission.append(output) states.append(state) return emission, states def probability_alphas(self, x): ''' Finds the maximum probability of a given input sequence using the forward algorithm. Arguments: x: Input sequence in the form of a list of length M, consisting of integers ranging from 0 to D - 1. Returns: prob: Total probability that x can occur. ''' # Calculate alpha vectors. alphas = self.forward(x) # alpha_j(M) gives the probability that the state sequence ends # in j. Summing this value over all possible states j gives the # total probability of x paired with any state sequence, i.e. # the probability of x. prob = sum(alphas[-1]) return prob def probability_betas(self, x): ''' Finds the maximum probability of a given input sequence using the backward algorithm. Arguments: x: Input sequence in the form of a list of length M, consisting of integers ranging from 0 to D - 1. Returns: prob: Total probability that x can occur. ''' betas = self.backward(x) # beta_j(1) gives the probability that the state sequence starts # with j. Summing this, multiplied by the starting transition # probability and the observation probability, over all states # gives the total probability of x paired with any state # sequence, i.e. the probability of x. prob = sum([betas[1][j] * self.A_start[j] * self.O[j][x[0]] \ for j in range(self.L)]) return prob def supervised_HMM(X, Y): ''' Helper function to train a supervised HMM. The function determines the number of unique states and observations in the given data, initializes the transition and observation matrices, creates the HMM, and then runs the training function for supervised learning. Arguments: X: A dataset consisting of input sequences in the form of lists of variable length, consisting of integers ranging from 0 to D - 1. In other words, a list of lists. Y: A dataset consisting of state sequences in the form of lists of variable length, consisting of integers ranging from 0 to L - 1. In other words, a list of lists. Note that the elements in X line up with those in Y. ''' # Make a set of observations. observations = set() for x in X: observations |= set(x) # Make a set of states. states = set() for y in Y: states |= set(y) # Compute L and D. L = len(states) D = len(observations) # Randomly initialize and normalize matrix A. A = [[random.random() for i in range(L)] for j in range(L)] for i in range(len(A)): norm = sum(A[i]) for j in range(len(A[i])): A[i][j] /= norm # Randomly initialize and normalize matrix O. O = [[random.random() for i in range(D)] for j in range(L)] for i in range(len(O)): norm = sum(O[i]) for j in range(len(O[i])): O[i][j] /= norm # Train an HMM with labeled data. HMM = HiddenMarkovModel(A, O) HMM.supervised_learning(X, Y) return HMM def unsupervised_HMM(X, n_states, N_iters): ''' Helper function to train an unsupervised HMM. The function determines the number of unique observations in the given data, initializes the transition and observation matrices, creates the HMM, and then runs the training function for unsupervised learing. Arguments: X: A dataset consisting of input sequences in the form of lists of variable length, consisting of integers ranging from 0 to D - 1. In other words, a list of lists. n_states: Number of hidden states to use in training. N_iters: The number of iterations to train on. ''' # Make a set of observations. observations = set() for x in X: observations |= set(x) # Compute L and D. L = n_states D = len(observations) # Randomly initialize and normalize matrix A. A = [[random.random() for i in range(L)] for j in range(L)] for i in range(len(A)): norm = sum(A[i]) for j in range(len(A[i])): A[i][j] /= norm # Randomly initialize and normalize matrix O. O = [[random.random() for i in range(D)] for j in range(L)] for i in range(len(O)): norm = sum(O[i]) for j in range(len(O[i])): O[i][j] /= norm # Train an HMM with unlabeled data. HMM = HiddenMarkovModel(A, O) HMM.unsupervised_learning(X, N_iters) return HMM
bf936dcfec2f928298f331ccd42eb959585a2522
roshanpiu/PythonOOP
/05_Instance_Attributes.py
341
3.859375
4
'''instance attributes''' #attributes in a class is holds the state of the instance import random class MyClass(object): '''My Class''' def __init__(self): self.rand_val = 0 def dothis(self): '''dothis''' self.rand_val = random.randint(1, 10) MYINST = MyClass() MYINST.dothis() print MYINST.rand_val
09bc7a629ff1e70a1f6f1d00f3f03e1a1c9bedd6
ThomasMGilman/ETGG1801_GameProgrammingFoundations
/Notes/Bullet example.py
1,723
3.59375
4
#bullets example: dynamic game object creation import pscreen import random import time def distance(x1,y1,x2,y2): return ((x2-x1)**2 + (y2-y1)**2)**0.5 #initialize pscreen pscreen.loadScreen() pscreen.fontSelect() #initialize game variables bullet_list=[] bullet_recharge_time=0 #start the game loop while True: #check for exit if pscreen.keyIsPressed("escape"): break #check to see if we want to create a bullet if pscreen.keyIsPressed("space") and time.time()>=bullet_recharge_time: bullet_recharge_time = time.time()+0.1 #calculate time when gun is next ready #create a bullet bullet_list.append([0,300+random.randint(-15,15)]) #move bullets for bullet in bullet_list: bullet[0]+=1 #render section pscreen.clearScreen((0,0,0)) #draw bullets for bullet in bullet_list: (bulletx,bullety)=bullet pscreen.circle(bulletx,bullety,5,(255,0,0),0) #check for bullets that have left the screen for bullet in bullet_list: if bullet[0]>799: bullet_list.remove(bullet) #check for bullet collisions with circle bullets_to_remove=[] for bullet in bullet_list: if distance(mx,my,bullet[0],bullet[1]) <= 30+5: #mark bullets to be removed bullets_to_remove.append(bullet) #remove marked bullets for bullet in bullets_to_remove: bullet_list.remove(bullet) #draw player mx=pscreen.mouseGetX() my=pscreen.mouseGetY() pscreen.circle(mx,my,30,(0,0,255)) #display number of bullets pscreen.fontWrite(0,0,str(len(bullet_list))) pscreen.updateScreen() pscreen.unloadScreen()
59e254743dc69e165168b38519df681600bb9b07
TheXGood/AIDS
/Python/Game/3x3_Matrix.py
1,469
3.625
4
import math blank = 1; Matrix = [[0 for x in range(3)] for y in range(3)]; def istaken(pos): if Matrix[int(pos % 3)][int((pos/3))] == 0: return 0; return 1; def playerone(): xy = max(min(int(input()),8),0); #x = input(); #y = input(); if istaken(xy): xy = max(min(int(input()),8),0); Matrix[int(xy % 3)][int((xy/3))] = 1; def playertwo(): xy = max(min(int(input()),8),0); #x = input(); #y = input(); if istaken(xy): xy = max(min(int(input()),8),0); Matrix[int(xy % 3)][int((xy/3))] = 2; def tictactoe(): print("Your computer has succsesfully acquired AIDS"); printboard(); playerone(); printboard(); playertwo(); # #Matrix[max(min(int(x),3),0)-1][max(min(int(y),3),0)-1] = 1; tictactoe(); def printboard(): print(" 1 2 3\n"); print(" 1 "+p(Matrix[0][0]) + "|" + p(Matrix[1][0]) + "|" + p(Matrix[2][0])); print(" "+"-+-+-"); print(" 2 "+p(Matrix[0][1]) + "|" + p(Matrix[1][1]) + "|" + p(Matrix[2][1])); print(" "+"-+-+-"); print(" 3 "+p(Matrix[0][2]) + "|" + p(Matrix[1][2]) + "|" + p(Matrix[2][2])); def p(i): if i == 0: return " "; if i == 1: return "X"; if i == 2: return "O"; return " "; def main(args): tictactoe(); return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
b0ae2c9d32772fc77c405d2fadae11e6b98d9d96
bobvo23/PointCloudUDA
/src/utils/timer.py
2,324
3.640625
4
from datetime import datetime def timeit(func): def timefunc(*args, **kwargs): start = datetime.now() result = func(*args, **kwargs) end = datetime.now() print("{} time elapsed (hh:mm:ss.ms) {}".format(func.__name__, end - start)) return result return timefunc @timeit def somefunc(): # some function to test 'timeit' result = 1 for i in range(1, 100000): result += i return result class TimeChecker: def __init__(self, max_hours=0, max_minutes=0, max_seconds=0): """ save maximum time duration in seconds check whether the program exceed maximum time duration """ self._max_time_duration = 3600 * max_hours + 60 * max_minutes + max_seconds assert self._max_time_duration > 0, 'max time duration should be greater than 0' print('max time duration: {}'.format(self._max_time_duration)) self._time_per_iter = 0 self._check = None def start(self): # run start() when you want to start timing. self._start_time = datetime.now() def check(self, toprint=False): """ should be called each epoch to check elapsed time duration. :param toprint: :return: whether should stop training """ if self._check is None: self._check = datetime.now() return False else: now = datetime.now() self._time_per_iter = max((now - self._check).seconds, self._time_per_iter) tobreak = (((now - self._start_time).seconds + self._time_per_iter) > self._max_time_duration) self._check = now if toprint or tobreak: print('time elapsed from start: {}'.format(now - self._start_time)) return tobreak if __name__ == '__main__': import time start = datetime.now() print("start: {}".format(start)) # print(somefunc()) time.sleep(3) end = datetime.now() print("end: {}".format(end)) duration = end - start print(type(duration)) print("duration: {}".format(duration)) print("microseconds: {}".format(duration.microseconds)) print("days: {}".format(duration.days)) print(duration.resolution) print(duration.seconds) print(type(duration.seconds))
4b3d6d14dce031f13b13c27d553f114922104571
jmg5219/First-Excercises-in-Python-
/for_loops.py
151
4.125
4
num_list = [1,2,3,4,5,6,7,8,9,10]# input list for i in num_list:#iterating through the list with a for loop print(num_list[i])#printing the list
a16f471560c2e8c7e747ba5830667bbbfaff60a5
mayelespino/code
/LEARN/python/using-yield/yield-examples.py
396
3.734375
4
#!/usr/local/bin/python3 def yieldFibbunacci(number): """ generate a fibunnaci series :param number: :return: """ fibb, prev = 0,1 for x in xrange(number): fibb, prev = fibb+prev, fibb if x > 0: yield fibb # # # def main(): print("Main") for fibb in yieldFibbunacci(10): print(fibb) # # # if __name__ == "__main__" : main()
84da9e6abc1e8ea632490f6247aeaa664d38bdda
BeccaFlake/Python
/contacts_RCF.py
3,583
4.375
4
#!/usr/bin/env python3 #import the csv library and define the file to be used import csv FILENAME = "contacts.csv" #function that writes to the file def write_contacts(contacts): with open (FILENAME, "w", newline="") as file: writer = csv.writer(file) writer.writerows(contacts) #function that reads from the file def read_contacts(): contacts = [] with open (FILENAME, newline="") as file: reader = csv.reader(file) for row in reader: contacts.append(row) return contacts #function that lists the contact names in a numbered list def list_contacts(contacts): for i in range(len(contacts)): contact = contacts[i] print(str(i+1) + ". " + contact[0]) #The number assigned to each contact is the index + 1. print() #function that prints the information of a specified contact def view_contact(contacts): number = int(input("What is the number of the contact you wish to view? ")) index = number - 1 #validate the input and then print the contents of specified row if index >= 0 and index <= (len(contacts)-1): contact = contacts[index] print("Name: " + contact[0]) print("E-mail: " + contact[1]) print("Phone: " + contact[2]) print() else: print("That is not a valid entry. Please try again.\n") #function that adds a new entry to the file def add_contact(contacts): #get the entry name = input("Name: ") email = input("E-mail: ") phone = str(input("Phone: ")) #write the entry to the file contact = [] contact.append(str(name)) contact.append(str(email)) contact.append(str(phone)) contacts.append(contact) write_contacts(contacts) print(name + " was added.\n") #function that removes an entry from the file def delete_contact(contacts): number = int(input("What is the number of the contact you wish to delete? ")) index = number - 1 #Validate the input and then pop the specified contact out of the file if index >= 0 and index <= (len(contacts)-1): contact = contacts.pop(index) write_contacts(contacts) print(contact[0] + " was removed.\n") else: print("That is not a valid entry. Please try again.\n") #function that prints the list of commands to the console def display_menu(): print("COMMAND LIST") print("list -- print list of contacts\n" "view -- print the information for a single contact\n" "add -- add a new contact to the file\n" "del -- remove a contact from the file\n" "exit -- exit the program\n") def main(): print("Contact Manager\n") display_menu() #assign contacts variable to the read_contact() function contacts = read_contacts() while True: command = input("Enter a command: ") #if statements that use the commands to call the functions if command.lower() == "list": list_contacts(contacts) elif command.lower() == "view": view_contact(contacts) elif command.lower() == "add": add_contact(contacts) elif command.lower() == "del": delete_contact(contacts) elif command.lower() == "exit": break #input validation else: print("That is not a valid command. Please try again\n.") print("Goodbye.") if __name__ == "__main__": main()
2d88332ac88bbbc60eb11cf578312055f106f2ba
mrtsif/Py1
/2/Lesson 2 task 3.py
223
4.15625
4
number = int(input('Enter number of month')) if 0 < number <= 12: result = number // 3 month = {1: 'spring', 2: 'summer', 3: 'autumn', 4: 'winter', 0: 'winter'} print(month.get(result)) else: print('Error')
363054b2eb818c1f4c8dbda1899d14988ace5e1e
turo62/exercise
/exercise/codewar/removesmallest.py
289
3.546875
4
def remove_smallest(numbers): list = numbers if list == [] or len(list) == 1: list = [] else: b = list.index(min(list)) del list[b] return list def main(): list = remove_smallest([158]) print(list) if __name__ == "__main__": main()
e9237459e13c27c6b04fe2356a329d7820d52279
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_136/2712.py
1,026
3.578125
4
#!/usr/bin/env python3 # Cookie clicker # Start with 0 cookies # 2 cookies/sec by clicking on a giant cookie # Having C cookies, you buy a cookie farm # A cookie farm costs C cookies and gives +F cookies/sec # You with with X cookies not spent on farms # How long it will take you to win using the best possible strategy? # Input # First line: test cases T import sys # First line the number of test cases T T = int(sys.stdin.readline()) def solve(C, F, X): speed = 2 # We start with 2 cookies/sec time = 0 # Time required to reach X while True: # Time to reach X at current speed tx = X / speed # Time to reach the next farm tc = C / speed # Time to reach X using the farm tf = tc + X / (speed + F) # Check which is faster if tf < tx: speed += F time += tc else: break # Current speed is the best possible return time + X / speed for t in range(T): C, F, X = [float(x) for x in sys.stdin.readline().split()] tottime = solve(C, F, X) print("Case #{}: {}".format(t + 1, tottime))
0e5e9debbcce33e723667dcd5d1d39cc66df54f6
andresflorezp/UVA_PYTHON
/12250.py
850
3.546875
4
import sys def sol(): val="0" count=1 while val!= "#": val=sys.stdin.readline().strip() if val=="HELLO": print("Case {}: ENGLISH".format(count)) if val=="HOLA": print("Case {}: SPANISH".format(count)) if val=="HALLO": print("Case {}: GERMAN".format(count)) if val=="BONJOUR": print("Case {}: FRENCH".format(count)) if val=="CIAO": print("Case {}: ITALIAN".format(count)) if val=="ZDRAVSTVUJTE": print("Case {}: RUSSIAN".format(count)) if val!="HELLO" and val!="HOLA" and val!="HALLO" and val!="BONJOUR" and val!="CIAO" and val!="ZDRAVSTVUJTE" and val!="#": print("Case {}: UNKNOWN".format(count)) count+=1 sol()
2d39b1d00bd676faadfbc20f52d4f141862727ce
woodie/coding_challenges
/max_in_sorted_array.py
428
3.90625
4
#!/usr/bin/env python import collections d = collections.deque(range(1,18)) d.rotate(-3) data = list(d) def find_max(a): if a[0] <= a[-1]: return a[-1] pivot = len(a) / 2 if a[pivot] > a[-1]: return find_max(a[pivot:]) else: return find_max(a[:pivot]) print "input: %s" % ','.join(str(x) for x in data) print "max: %d" % find_max(data) """ input: 4,5,6,7,8,9,10,11,12,13,14,15,16,17,1,2,3 max: 17 """