text
stringlengths
37
1.41M
# Stage 1 class PiggyBank: pass print("Hello") pg1 = PiggyBank() print(pg1) print(id(pg1)) print(hex(id(pg1))) print(type(pg1)) print(pg1.__class__) # Stage 2 -Extensible class PiggyBank: pass pg1 = PiggyBank() print(pg1) print(id(pg1)) print(pg1.__class__) pg1.balance = 10 # It creates a variable balance i.e Object pg1 got extended pg1.lt = 10 # It creates a variable lt print(pg1.balance) print(pg1.lt) pg2 = PiggyBank() print(pg2) print(id(pg2)) print(pg2.__class__) pg2.balance = 200 # It creates a variable balance i.e Object pg2 got extended pg2.lt = 200 # It creates a variable lt print(pg2.balance) print(pg2.lt) print(isinstance(pg1,PiggyBank)) print(isinstance(pg2,PiggyBank)) # Stage 3 - __init__ class PiggyBank: def __init__(self): print("Entering Init") print(id(self)) print("Leaving Init") pg1 = PiggyBank() print(id(pg1)) pg1.balance = 10 pg1.lt = 10 print(pg1.balance) print(pg1.lt) pg2 = PiggyBank() print(id(pg2)) pg2.balance = 200 pg2.lt = 200 print(pg2.balance) print(pg2.lt) # Stage 4 - self class PiggyBank: def __init__(self): #Constructor print("Entering Init") self.balance = 0 self.lt = 0 print("Leaving Init") pg1 = PiggyBank() print(pg1.balance) print(pg1.lt) pg2 = PiggyBank() print(pg2.balance) print(pg2.lt) # Stage 5 - Object Oriented Piggy print("Welcome to Object Oriented PiggyBank") class PiggyBank: def __init__(self): self.balance = 0 self.lt = 0 def deposit(self,amount): self.balance = self.balance + amount self.lt = amount def withdraw(self,amount): if(self.balance >= amount): self.balance -= amount self.lt = -amount def statement(self): print("Balance =",self.balance) print("Last Transaction =",self.lt) pg1 = PiggyBank() pg1.deposit(100) pg1.deposit(100) pg1.statement() pg1.withdraw(50) pg1.statement() pg2 = PiggyBank() pg2.deposit(1000) pg2.deposit(1000) pg2.statement() pg2.withdraw(500) pg2.statement()
print("Welcome to Object Graph1") l1 = [10,20,True,"cat"] l2 = [90,l1,False,[1,2,3],(4,5,6)] t1 = [l1,l2,9,10] d1 = { "a" : [-1,-2,-3], "b" : ['e','a','r'], "c" : (t1,l1,l2), "d" : {"m":11,"n":22,"o":33,"p":[55.66]} } print(l1[3]) print(d1["b"][2]) print("Thankyou for using python's object graph")
# Abigail Anderson print('Hello world!') print('Choose a language and I will greet you in that language!') print('1. Spanish') print('2. French') print('3. Japanese') choice = int(input()) # user inputs number 1, 2, or 3 if choice == 1: print('Hola!') elif choice == 2: print('Bonjour!') elif choice == 3: print('Konnichiwa!') # program greets user with language choosen as input
# WRITE YOUR NAME and YOUR COLLABORATORS HERE #------------------------- 10% ------------------------------------- # The operand stack: define the operand stack and its operations opstack = [] #assuming top of the stack is the end of the list # Now define the HELPER FUNCTIONS to push and pop values on the opstack # Remember that there is a Postscript operator called "pop" so we choose # different names for these functions. # Recall that `pass` in Python is a no-op: replace it with your code. def opPop(): if (len(opstack) > 0): return opstack.pop(-1) else: print("ERROR in opstack") # opPop should return the popped value. # The pop() function should call opPop to pop the top value from the opstack, but it will ignore the popped value. def opPush(value): opstack.append(value) #-------------------------- 16% ------------------------------------- # The dictionary stack: define the dictionary stack and its operations dictstack = [] #assuming top of the stack is the end of the list # now define functions to push and pop dictionaries on the dictstack, to # define name, and to lookup a name def dictPop(): if len(dictstack) > 0: return dictstack.pop(-1) else: print("ERROR dictPop(): zero elements in dictstack") # dictPop pops the top dictionary from the dictionary stack. def dictPush(d): dictstack.append(d) def define(name, value): newd = {} newd[name] = value dictPush(newd) #add name:value pair to the top dictionary in the dictionary stack. #Keep the '/' in the name constant. #Your psDef function should pop the name and value from operand stack and def lookup(name): newname = "/"+name new = None if len(dictstack) == 0: print("ERROR lookup(): dictstack empty") else: for item in dictstack: if newname in item: new = item[newname] else: continue return new # return the value associated with name #--------------------------- 10% ------------------------------------- # Arithmetic and comparison operators: add, sub, mul, eq, lt, gt # Make sure to check the operand stack has the correct number of parameters # and types of the parameters are correct. def add(): if len(opstack) > 1: op2 = opPop() op1 = opPop() if (isinstance(op1, int) and isinstance(op2, int)): opPush(op1 + op2) else: print("Error: add - one of the operands is not a numerical value") opPush(op1) opPush(op2) else: print("Error: add expects 2 operands") def sub(): if len(opstack) > 0: x = opPop() y = opPop() if (isinstance(x, int) and isinstance(y, int)): opPush(y - x) else: print("ERROR sub(): zero elements on opstack") def mul(): if len(opstack) > 0: x = opPop() y = opPop() if (isinstance(x, int) and isinstance(y, int)): opPush(x * y) else: print("ERROR mul(): zero elements on opstack") def eq(): if len(opstack) > 0: x = opPop() y = opPop() if x == y: opPush(True) else: opPush(False) else: print("ERROR eq(): zero elements on opstack") def lt(): if len(opstack) > 0: x = opPop() y = opPop() if x < y: opPush(False) else: opPush(True) else: print("ERROR lt(): zero elements on opstack") def gt(): if len(opstack) > 0: x = opPop() y = opPop() if x > y: opPush(False) else: opPush(True) else: print("ERROR gt(): zero elements on opstack") #--------------------------- 20% ------------------------------------- # String operators: define the string operators length, get, getinterval, putinterval, search def length(): if len(opstack) > 0: str = opPop() length = len(str) if str[0] == '(': if str[-1] == ')': length = length -2 opPush(length) else: print("ERROR length(): zero elements on opstack") def get(): if len(opstack) > 1: index = opPop() str = opPop() new = '' for x in str: if x != '(': if x != ')': new += x print(ord(new[index])) opPush(ord(new[index])) else: print("ERROR get(): zero elements on opstack") def getinterval(): if len(opstack) > 0: count = opPop() index = opPop() str = opPop() if str[0] == "(" and str[-1] == ")": str = str[1:-1] if str[0] == "[" and str[-1] == "]": str = str[1:-1] index = index * 2 count = count * 2 newstr = str[index:index + count] newstr = '(' + newstr + ')' opPush(newstr) else: print("ERROR getinterval(): zero elements on opstack") def putinterval(): if len(opstack) > 0: new = [] count = opPop() index = opPop() str = opPop() str2 = opPop() print("count, index, str") print(count, index, str) new = '' for x in count: if x != '(': if x != ')': new += x print("printing new ", new) part1 = str[:(index + 1)] print("printing part1 ", part1) part1 += new num = len(count) print("part1 2 ", part1) index += num index -= 1 part1 += str[index:] print("opstack ", opstack) print("part1 3 ", part1) opPush(part1) print("dictstack ", dictstack) print("opstack ", opstack) else: print("ERROR putinterval(): zero elements on opstack") def search(): if len(opstack) > 0: new = '' old = '' index_num = 0 split = opPop() str_split = '' string = opPop() for x in split: if x != '(': if x != ')': str_split += x if str_split in string: index_num = str(string).index(str_split) new = string[:index_num] + ')' old = '(' + string[index_num + 1:] opPush(old) opPush(split) opPush(new) opPush(True) else: opPush(string) opPush(False) print("Delimiter not found!") #--------------------------- 18% ------------------------------------- # Array functions and operators: # define the helper function evaluateArray # define the array operators aload, astore def evaluateArray(aInput): functions = {"add": add, "sub": sub, "mul": mul, "eq": eq, "lt": lt, "gt": gt, "length": length, "count": count, "get": get, "putinterval": putinterval, "getinterval": getinterval, "dup": dup, "copy": copy, "pop": pop, "clear": clear, "exch": exch, "dict": psDict, "begin": begin, "end": end, "def": psDef, "seach": search} new = [] for each in aInput: if isinstance(each, str): if each in functions.keys(): call = functions[each] call() elif lookup(each) is not None: token1 = lookup(each) if token1 is not None: opPush(token1) else: opPush(each) else: opPush(each) print(opstack) return opstack #should return the evaluated array def aload(): new = opPop() for x in new: opPush(x) opPush(new) print(opstack) def astore(): print(opstack) new = opPop() num = 0 count = len(new) new_arr = [] while num < count: new_arr.insert(0, opPop()) num += 1 opPush(new_arr) print(opstack) #--------------------------- 6% ------------------------------------- # Define the stack manipulation and print operators: dup, copy, count, pop, clear, exch, stack def dup(): if len(opstack) > 0: x = opPop() opPush(x) opPush(x) else: print("ERROR dup(): zero elements on opstack") def copy(): if len(opstack) > 0: x = opPop() help1 = [] help2 = [] if x > len(opstack): print("ERROR copy(): value greater than stack") else: for n in range(x): val = opPop() help1.append(val) help2.append(val) for n in range(x): val = help1.pop(-1) opPush(val) for n in range(x): val = help2.pop(-1) opPush(val) else: print("ERROR copy(): zero elements on opstack") def count(): pass def pop(): def pop(): if len(opstack) > 0: return opPop() else: print("ERROR pop(): zero elements on opstack") def clear(): global opstack opstack = [] def exch(): if len(opstack) > 0: x = opPop() y = opPop() opPush(x) opPush(y) else: print("ERROR exch(): zero elements on opstack") def stack(): pass #--------------------------- 20% ------------------------------------- # Define the dictionary manipulation operators: psDict, begin, end, psDef # name the function for the def operator psDef because def is reserved in Python. Similarly, call the function for dict operator as psDict. # Note: The psDef operator will pop the value and name from the opstack and call your own "define" operator (pass those values as parameters). # Note that psDef()won't have any parameters. def psDict(): opPop() opPush({}) def begin(): d = opPop() if type(d) is dict: dictPush(d) else: print("begin() ERROR: element not of dictionary type") def end(): dictPop() def psDef(): if len(opstack) > 0: val = opPop() name = opPop() define(name, val) else: print("ERROR psDef(): zero elements on opstack")
''' Using memoization to solve fibonacci problem ''' # Time complexity: O(n) # Space complexity: O(n) def fib(n, memo={}): if n in memo: return memo[n] if n < 0: return if n <=2 : return 1 memo[n] = fib(n-1) + fib(n-2) return memo[n] print(fib(5)) print(fib(6)) print(fib(50))
''' Given a target number and a list of number? Return array of number if we can generate the target number from the list. (use additional only) Else return None Can use any number in the list multiple times. ''' def howSum(target, numbers, memo={}): if target in memo: return memo[target] if target < 0: return None if target == 0: return [] for num in numbers: remainder = target - num remainderResult = howSum(remainder, numbers, memo) if remainderResult is not None: memo[target] = remainderResult + [num] return memo[target] memo[target] = None # return memo[target] print(howSum(7, [2,3,4])) print(howSum(300, [7, 14])) # m = target sum # n = length of the number list # Brute Force # Time complexity: O(n^m*m) # Space complexity: O(m^2) # Memoization # Time complexity: # Space Complexity:
''' Given a target string and list of words. Return number of way that the target string can be generated from the list ''' def countConstruct(target, words): table = [0 for i in range(len(target)+1)] # There is 1 way to construct empty string: table[0] = 1 for i in range(len(target)): for word in words: if target[i:].find(word) == 0: if i + len(word) <= len(target): table[i+len(word)] += table[i] return table[len(target)] print(countConstruct('purple', ['purp', 'p', 'ur', 'le', 'purpl'])) print(countConstruct('skateboard', ['ska', 'teb', 'oar', 'd'])) print(countConstruct('google', ['go', 'oo', 'gle','o'])) print(countConstruct('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaf', ['aaa', 'a', 'aa', 'aaaa','aaaaaa', 'aaaaa']))
from utils.game import Board new_game = Board() new_game.start_game() # COACHES' NOTES: The game works well! Nicely done! # COACHES' NOTES: Your code is close to perfect. # Take these comments as tiny improvements, you have done an excellent job. # - Good type hinting # - Very nice docstring of functions # - Very nice separation of code into methods and functions. # - Very nice method names # COACHES' NOTES: You misunderstood the inheritance in OOP. # It is not mandatory. Each class does not NEED to inherit from another. # You can have standlone classes. Inheritance is to share functionality and reduce code duplication. # Thus, a Player inheriting from Card does not make sense. # COACHES' NOTES: Another misunderstanding was the Card and Symbol class, how they are supposed to be used # and how they interact with each other. They should have been used a objects, not as placeholders # COACHES' NOTES: __str__() is supposed to help you have an easy way to print out the value of an object. # It's perfect for this game, as it allows you to centralize how a card shall be printed on screen. # class Card: # def __init__(self, value, icon): # self.value = value # self.icon = icon # # def __str__(self): # return f"{self.value} {self.icon}" # # if __name__=='__main__': # my_card = Card(value="A", icon="โ™ฃ") # print(my_card) ---> prints out "Aโ™ฃ" #
def test_brackets(string): // limit to only methods push and pop stack = [] for char in string: if ( char == '[' or char == '{' or char == '('): stack.push(string[i]) if (char == ']' or char == ')' or char == '}': bracketPopped = stack.pop() if ((bracketPopped == '[' and char == ']') or (bracketPopped == '(' and char == ')') or (bracketPopped == '{' and char == '}')): # nothing to do all good else: # not good closed out something that was # not opened return false # check all chars been popped if ( not stack.pop()): return true else: return false } print(test_brackets('a[bc(123)]')
from open_program import OpenProgram import json ''' Get string from file ''' json_data = open("tasks.json") data = json.load(json_data) ''' Init OpenProgram class ''' open_program = OpenProgram( data ) ''' Start CLI flow with messages ''' print("list - get all programs available") print("open - select program to open from list") print("open path - open a program from path") print("exit - exit the program \n") loop = True while loop == True: command = input("What do you want to do today? ") if command == "list": open_program.list_programs() elif command == "open": program = input("Please specify program to open from list: ") open_program.open(program) loop = False elif command == "open path": path = input("Please give me the path to the program executable: ") open_program.open_from_path(path) loop = False elif command == "exit": loop = False else: print("Command not found, please try again")
input = "0 5 10 0 11 14 13 4 11 8 8 7 1 4 12 11" def rebalance(bank): bank = list(bank) length = len(bank) max_value = max(bank) max_value_index = bank.index(max_value) index = max_value_index bank[index] = 0 for _ in range(max_value): index = (index + 1) % length bank[index] += 1 return tuple(bank) def solve_part1(input): cur = tuple(int(s) for s in input.strip().split()) cycle = 0 seen = set() while cur not in seen: cycle += 1 seen.add(cur) cur = rebalance(cur) return cycle # print(solve_part1(input)) def solve_part2(input): cur = tuple(int(s) for s in input.strip().split()) cycle = 0 seen = set() step_mapping = dict() while cur not in seen: seen.add(cur) step_mapping[cur] = cycle cycle += 1 cur = rebalance(cur) return cycle - step_mapping[cur] print(solve_part2(input))
''' 24-game gives the player 4 numbers, and ask for player to use operations +, -, * on these numbers in a way that the result equals to 24 ''' import operator import random import itertools class number_set(): def __init__(self, a, b, c, d): self.numbers = [a, b, c, d] def start_game(self): print('Wecome to the game. here are the {0}'.format(self.numbers)) def user_input(self): ask_for_input = input("please give 3 operations (possible: add for +, sub for -, mul for *) in the order, separate by comma") # add, sub, mul while not(len(ask_for_input) == 13): ask_for_input = input("please check if the operations are correct") return ask_for_input def split(self, user_input): x,y,z = user_input.split(',') return [x.replace(' ', ''),y.replace(' ', ''),z.replace(' ', '')] def operators(self, operators): _func = {'add': operator.add, # add 'sub': operator.sub, # substract 'mul': operator.mul # multiplication } self.f1 = _func[operators[0]] self.f2 = _func[operators[1]] self.f3 = _func[operators[2]] def calculate(self): self.result1 = self.f1(self.numbers[0], self.numbers[1]) self.result2 = self.f2(self.result1, self.numbers[2]) self.result3 = self.f3(self.result2, self.numbers[3]) return self.result3 def check_answer(self, result3): if self.result3 == 24: print('Correct') trial = 0 while self.result3 != 24: print("The current answer is {}. Enter 'T' to try again. Enter 'N' to shower answer".format(self.result3)) choice = input() if choice == 'T' and trial <= 3: trial += 1 user_operations = self.user_input() user_operations = self.split(user_operations) self.operators(user_operations) self.result3 = self.calculate() #print("The current answer is {}. Enter 'T' to try again. Enter 'N' to shower answer".format(self.result3)) if choice == 'T' and trial > 3: print('you have reached total number of trials') print(answer) else: print(answer) break def generate_answers(): list_all_num = list(itertools.combinations_with_replacement(range(1, 10), 4)) #print(len(list_all_num)) ops = ['add', 'sub', 'mul'] list_all_ops = list(itertools.combinations_with_replacement(ops, 3)) #print(list_all_ops) possible_cases = [] all_answers = [] for i in list_all_num: test = number_set(*i) for j in list_all_ops: user_operations = j test.operators(user_operations) temp = test.calculate() if temp == 24: possible_cases.append(i) all_answers.append([i, j]) return possible_cases, all_answers if __name__ == '__main__': possible_cases, all_answers = generate_answers() choice = random.choice(possible_cases) answer_index = possible_cases.index(choice) answer = all_answers[answer_index] # save the answer test = number_set(*choice) test.start_game() user_operations = test.user_input() user_operations = test.split(user_operations) test.operators(user_operations) result = test.calculate() test.check_answer(result)
x = input("Tekrar sayฤฑsฤฑnฤฑ giriniz") x = int(x) y = -5 while y < x : if y == 0: y = y + 1 continue print(x / y) y = y + 1 print("ฤฐkinci while") y = 0 while y < x: if y % 2 == 0: break print(y) y = y +1 else: print("ikinci while bitti") print("Dรถngรผ sona erdi") # saitorhan.com
"""Generate Random Number.""" from random import randint dice_roll = input("nds: ") split_array = dice_roll.lower().replace(" ", "").split("d") while len(split_array) != 2: print("Incorrect input, should input number of die, \"d\"," " then side number. i.e. 1d4") dice_roll = input("nds: ") split_array = dice_roll.lower().replace(" ", "").split("d") else: die = int(split_array[0]) sides = split_array[1] total = 0 for dice in range(0, die): rand_num = randint(1, int(sides)) print(str(rand_num)) total += rand_num print("sum: %i" % total)
print("Hello WORLD") for i in range(5): if i==3: continue print(i) for i in range(5): if i==3: break print(i) from datetime import datetime '''print("hello world!") for i in range(10): if i==3: break print("{}".format(i)) #shift+enter for working in interactive mode''' class Employee(): #class variable bonus=5000 #parameterized constructor def __init__(self,name,salary): #instance variable self.name=name self.salary=salary #instance method def getsalary(self): return self.salary #instance method def applyhike(self): self.salary=self.salary*1.04 #4% hike return self.salary # class method since uses class property 'bonus' @classmethod def setbonus(cls,amount): cls.bonus=amount # @staticmethod def isworkingday(): #local variable day=datetime.now().strftime('%w') if day=='0' or day=='6': return False else: return True def __str__(self): return self.name def __add__(self,other): return self.salary+other.salary class Developer(Employee): def __init__(self,name,salary,stack): self.stack=stack super().__init__(name,salary) def getstack(self): return self.stack """emp1=Employee('krishita',200000) emp2=Employee('riya',15000) print(emp1) print(emp2) #memorylocation print(emp1.getsalary()) print(Employee.getsalary(emp1)) print(emp1.applyhike()) Employee.setbonus(10000) print(emp1.bonus) print(emp2.applyhike()) print(emp1.__dict__) #view properties of emp1 object print(emp2.__dict__) print(Employee.isworkingday()) print(emp1+emp2)""" if __name__== '__main__': dev1=Developer("sound",30000,"ss") print(dev1.getstack()) print(dev1.getsalary())
from threading import Thread import time class A(Thread): def run(self): for i in range(1,3): print(i**3) time.sleep(1) class B(Thread): def run(self): for i in range(1,3): print(i**2) time.sleep(1) a=A() b=B() a.start() b.start() a.join() b.join() for i in range(1,3): print("hi") time.sleep(1)
def greater_than(args): return args[0] > args[1] def greater_or_equal_than(args): return args[0] >= args[1] def between(args): return args[1] <= args[0] <= args[2] def even(args): return divisible_by([args[0], 2]) def odd(args): return args[0] % 2 != 0 def equal(args): return args[0] == args[1] def min_length(args): return len(args[0]) >= args[1] def max_length(args): return len(args[0]) <= args[1] def length(args): return len(args[0]) == args[1] def none(args): return args[0] is None def first(args): return args[0][0] == args[1] def last(args): last_idx = len(args[0]) - 1 return args[0][last_idx] == args[1] def less_than(args): return args[0] < args[1] def less_or_equal_than(args): return args[0] <= args[1] def includes(args): return args[1] in args[0] def positive(args): return greater_or_equal_than([args[0], 0]) def negative(args): return less_than([args[0], 0]) def empty(args): return length([args[0], 0]) def divisible_by(args): return args[0] % args[1] == 0
import turtle import math #ๅฎšไน‰ๅคšไธชๅๆ ‡ x1,y1=100,100 x2,y2=100,-100 x3,y3=-100,-100 x4,y4=-100,100 #็ป˜ๅˆถๆŠ˜็บฟ #turtleๆŠฌ็ฌ” turtle.penup() turtle.goto(x1,y1) turtle.pendown() turtle.goto(x2,y2) turtle.goto(x3,y3) turtle.goto(x4,y4) #่ฎก็ฎ—่ตทๅง‹็‚นไธŽ็ปˆ็‚น็š„่ท็ฆป #็ฌฌไธ€็ง่ฎก็ฎ—่ท็ฆป็š„ๆ–นๆณ•๏ผŒๅผ•ๅ…ฅไบ†math # distance =math.sqrt((x1-x4)**2+(y1-y4)**2) # turtle.write(distance) #็ฌฌไบŒ็ง่ฎก็ฎ—่ท็ฆป็š„ๆ–นๆณ•๏ผŒๆฒกๆœ‰ๅผ•ๅ…ฅmath,ๅˆ†ๆญฅ่ฎก็ฎ—็š„๏ผŒ็ป่ฟ‡ๆฃ€้ชŒ็จ‹ๅบๆ˜ฏๆฒกๆœ‰้”™่ฏฏ็š„ # a=(x1-x4)**2 # b=(y1-y4)**2 # c=(a+b)**0.5 # turtle.write(c) #็ฌฌไธ‰็ง่ฎก็ฎ—่ท็ฆป็š„ๆ–นๆณ•๏ผŒๅผ•ๅ…ฅmath,ไฝฟ็”จ็š„**0.5่ฎก็ฎ—ๅผ€ๆ–น๏ผŒ็ป่ฟ‡ๆฃ€้ชŒ็จ‹ๅบๆ˜ฏๆฒกๆœ‰้”™่ฏฏ็š„ distance =((x1-x4)**2+(y1-y4)**2)**0.5 turtle.write(distance)
def main(): #print("Start time: ") #start = input() #print("Duration: ") #duration = input() #print("Day?: ") #day = input() # Temp params start = "11:59 PM" duration = "24:05" day = "null" print(add_time(start, duration, day)) def add_time(start, duration, day="null"): weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] tempHour = "" tempMins = "" new_time = "" addHour = "" days = 0 dayChange = False newDayOfWeek = "" currentTimeType = "" if "AM" in start: currentTimeType = "AM" else: currentTimeType = "PM" colonLoc = start.find(':') currentHour = start[0:colonLoc] currentMinutes = start[colonLoc+1:colonLoc+3] addColonLoc = duration.find(':') addHourTemp = int(duration[0:addColonLoc]) addMinutes = duration[addColonLoc+1:addColonLoc+3] if(int(addHourTemp) == 0 and int(addMinutes) == 0): return start if(addHourTemp >= 24 and int(addMinutes) != 0): days = (addHourTemp // 24) + 1 addHour = addHourTemp - ((days-1) * 24) dayChange = True elif(addHourTemp == 24): days = (addHourTemp // 24) addHour = addHourTemp - ((days) * 24) dayChange = True else: addHour = addHourTemp if(day != "null"): dayOfWeek = weekdays.index(day.lower().capitalize()) partOfWeek = days % 7 dayOfWeek += partOfWeek if(dayOfWeek >= 7): dayOfWeek -= 7 newDayOfWeek = weekdays[dayOfWeek] if((int(currentHour) + int(addHour) > 12) or (int(currentMinutes) + int(addMinutes) >= 60)): if(currentTimeType == "PM"): dayChange = True currentTimeType = "AM" else: currentTimeType = "PM" if((int(currentHour) + int(addHour) > 12)): tempHour = (int(currentHour) + int(addHour)) - 12 else: tempHour = int(currentHour) if(int(currentMinutes) + int(addMinutes) > 59): tempHour += 1 tempMins = int(currentMinutes) + int(addMinutes) - 60 else: tempMins = int(currentMinutes) + int(addMinutes) new_time += str(tempHour) new_time += ':' if(int(tempMins) <= 9): new_time += '0' new_time += str(tempMins) else: new_time += str(tempMins) new_time += " " new_time += currentTimeType if(day != "null"): new_time += ", " new_time += newDayOfWeek if(days > 1): new_time += " (" new_time += str(days) new_time += " days later)" elif((days <= 1) and (dayChange == True)): new_time += " (next day)" else: new_time += str(int(currentHour) + int(addHour)) new_time += ':' new_time += str(int(currentMinutes) + int(addMinutes)) new_time += " " new_time += currentTimeType if(day != "null"): new_time += ", " new_time += newDayOfWeek if(dayChange == True): new_time += " (next day)" return new_time return new_time main()
import sqlite3 class DataStoreSqlite(object): """ Database class to create , insert and fetch the data """ def __init__(self): self.conn = sqlite3.connect('search.sqlite') # connecting to database and creating table self.cur = self.conn.cursor() self.table = self.cur.execute('CREATE TABLE if not exists SearchModel(value text)') def insert_values(self, value): self.cur.execute('insert into SearchModel values(?)', (value,)) self.conn.commit() # Fetching the distinct column value def fetch_value(self): return self.cur.execute('SELECT DISTINCT value FROM SearchModel').fetchall() def remove_duplicates(self): pass # We can create different database also an store that object here database_obj = DataStoreSqlite()
''' N students take K apples and distribute them among each other evenly. The remaining (the undivisible) part remains in the basket. How many apples will each single student get? How many apples will remain in the basket? The program reads the numbers N and K. It should print the two answers for the questions above. ''' N = int(input("enter first value:")) K = int(input("enter second value:")) numberOfApples = K // N remainInBasket = N - K print(f"the number of apple single student got is {numberOfApples} ") print(f"the number of apple remain in the basket is {remainInBasket}")
""" Functions for displaying things on the console """ import sys import os import csv import numpy as np import matplotlib.pyplot as plt def printparamsexp(paramdict, errordict=None, decimals=4): """ Prints the keys and values of a dictionary in an exponential form. Required Parameters ------------------- paramdict : dictionary whose keys are the parameter names and values are the parameter values. paramdict : dictionary defining the errors of each parameter Optional Parameters ------------------- decimals : integer How many decimal points to use to express the values. Default is 4. """ if errordict is None: for key, val in paramdict.items(): print('{} = {:.{prec}e}'.format(key, val, prec=decimals)) else: for key, val in paramdict.items(): err = errordict[key] print('{} = {:.{prec}e} +/- {:.2e}'.format(key, val, err, prec=decimals))
print('*'*80) print('.......................Welcome to Sandeep MLOps task o1...........................') import pandas as pd from sklearn.linear_model import LinearRegression print('*'*80) db=pd.read_csv('test_data_set.csv') print('We have a Data Set Now we are used to and now we are show ...') print('#'*80) print(db) print('#'*80) #type(db) y= db["mark"] x= db["NumberOfStrd"] x.shape x=x.values x = x.reshape(8,1) x.shape mind = LinearRegression() mind.fit(x,y) a=int(input('enter your value : -')) b=mind.predict([[a]]) print('#'*80) print('................ Your Resut is...................') print('#'*80) print('predict data :- ',b) print('#'*80) print('.......................... Thank you for Using App........') print('#'*80)
def arrayTest(array): print(array) array.append('j') print(array) array.pop() print(array) array = ['0'] + array print(array) from collections import deque #faster for pop and append (both left and right, so queues and stacks. But slower for inserting at the middle def tryDequeue(): dequeVar = deque('abc') print(dequeVar) dequeVar.append('j') print(dequeVar) dequeVar.pop() print(dequeVar) dequeVar.appendleft('0') print(dequeVar) dequeVar.popleft() print(dequeVar) arrayTest(['a', 'b', 'c']) tryDequeue()
''' Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: [-1,-100,3,99] and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? ''' from collections import deque def shiftArray(array, steps): array = deque(array) while steps > 0: array.appendleft(array.pop()) steps -=1 return array def shiftArrayNoExtraSpace(array, steps): aux = 0 while steps > 0: newIndexZero = array[len(array)-1] aux = array[0] array[0] = newIndexZero oldAux = aux currentIndex=1 while(currentIndex < len(array)): aux = array[currentIndex] array[currentIndex] = oldAux oldAux = aux currentIndex+=1 steps -=1 return array
#class Memoize: # def __init__(self, fn): # self.fn = fn # self.memo = {} # def __call__(self, *args): # if args not in self.memo: # self.memo[args] = self.fn(*args) # return self.memo[args] def addTo80(n): print("Looooong time") return 80 + n #@Memoize def memoizedAddTo80(n, cache): if n in cache: return cache[n] else: print("Looooong time") cache[n] = n+80 return cache[n] def fibonacci(n, cache): if n in cache: return cache[n] if n == 0: cache[0] = 0 return 0 if n ==1 or n==2: cache[n] = 1 return 1 print("Looooong time") cache[n] = fibonacci(n-1, cache) + fibonacci(n-2, cache) return cache[n] def test(): cache = dict() print(fibonacci(0, cache)) print(fibonacci(1, cache)) print(fibonacci(2, cache)) print(fibonacci(3, cache)) print(fibonacci(4, cache)) print(fibonacci(5, cache)) print(fibonacci(5, cache)) print(fibonacci(5, cache)) print(fibonacci(5, cache)) print(fibonacci(5, cache)) print(fibonacci(5, cache)) print(fibonacci(5, cache)) print(fibonacci(5, cache))
# Define the classes (Student, Exam, University) so that following # Excerpt of code from a Student Management System works as expected. import random class Student: def __init__(self, name, dob): self.name = name self.dob = dob self.exams = {} def takeExam(self, exam): grade = random.randint(1,5) self.exams[exam.name] = grade exam.examTaken(self) class University: def __init__(self, name): self.name = name self.list_of_students = [] def enroll(self, student): self.list_of_students.append(student) def stats(self): for s in self.list_of_students: print(f"{s.name} took {len(s.exams)} exam(s).") for k, v in s.exams.items(): print(f"\tGot {v} in {k}.") class Exam: def __init__(self, name): self.name = name self.students = [] def examTaken(self, student): self.students.append(student) def calculateAvgGrade(self): sum = 0 for s in self.students: if self.name in s.exams: sum += s.exams[self.name] return sum/len(self.students) def stats(self): print(f"{self.name} exam was taken by {len(self.students)} students. Average score = {self.calculateAvgGrade()}") s1= Student ("Sandy", "24.01.1992") # name, dob s2= Student ("Spili", "14.10.1993") # name, dob s3= Student ("Waile", "04.06.1994") # name, dob imc = University ("FH Krems") imc.enroll(s1) imc.enroll(s2) imc.enroll(s3) e1 = Exam("Programming II") e2 = Exam("Software Eng") e3 = Exam("Creativity") # assign a random value as grade s1.takeExam (e1) s2.takeExam(e1) s2.takeExam(e3) s3.takeExam(e1) s1.takeExam(e2) s2.takeExam(e2) s1.takeExam(e3) s3.takeExam(e3) # print statistics imc.stats() #exams statistics e1.stats() e2.stats() e3.stats()
# Decorators # โ€ข Python has an interesting feature called decorators to add functionality to an existing code. # โ€ข This is also called metaprogramming as a part of the program tries to modify another part of the program at compile time # โ€ข A decorator in Python is an object that takes a function and returns a function. def my_decorator(f): def f1(): print ("before hello") f() print ("after hello") return f1 @my_decorator def hello(): print("hello") hello() print("-------------------------") def my_decorator(f): def f1(*args, **kwargs): print ("before ") f(*args, **kwargs) print ("after ") return f1 @my_decorator def fy(t): print(t) @my_decorator def fx(t, name="silly"): print(t, name) fx(10) fy(20) print("-------------------------") # โ€ข Write a Python Decorator called @isGreater10, which when applied to a function checks whether the return value of that function is greater than 10 # โ€ข If the return value is greater than 10, it prints โ€œHurrayโ€. # def isGreater10(funct): def wrappedUpFunct(): if funct() > 10: print("Hurray!!!") else: print("Your number is smaller or equal to 10") return wrappedUpFunct @isGreater10 def somecalculation1(): # complex stuff here return 2 @isGreater10 def somecalculation2(): # complex stuff here return 12 somecalculation1() somecalculation2() print("-------------------------") class Execute_3_times: def __init__(self, function): self.function = function def __call__(self): self.function() self.function() self.function() # adding decorator to the class @Execute_3_times def function(): print("Hello") print (type(function)) function() print("-------------------------") # Define three decorators so that the the output of the method mp() is altered: # โ€ข @bold๏ƒ addsthe<b>..</b>tag # โ€ข @italic๏ƒ <i>..</i>tag # โ€ข @unterline๏ƒ <u>..</u>tag def bold(f): def wrappedUpFunct(): return f"<b>{f()}</b>" return wrappedUpFunct def italic(f): def wrappedUpFunct(): return f"<i>{f()}</i>" return wrappedUpFunct def underline(f): def wrappedUpFunct(): return f"<u>{f()}</u>" return wrappedUpFunct # @bold # @italic # @underline @underline @italic @bold def mp(): return "hello world" print(mp()) print("-------------------------") def isGreater100(fn): def wrapperFunct(num): if fn(num) < 100: print("smaller or equal to 100") else: print("bigger than 100") return wrapperFunct @isGreater100 def somecalculation(num): # complex stuff here return num somecalculation(200) print("-------------------------")
'''This is a simple tennis game created with the use of Pygame module. Players hit the ball using rackets which can move vertically. The game lasts until one of the players gets the score of 6 points winning the game.''' import pygame import time class Background(pygame.sprite.Sprite): '''Background class.''' def __init__(self, image_file, location): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image_file) self.rect = self.image.get_rect() self.rect.left, self.rect.top = location pygame.mixer.init() class Ball(pygame.sprite.Sprite): '''Ball class.''' def __init__(self, image_file, location, speed, increment_x, increment_y, sound): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image_file) self.rect = self.image.get_rect() self.rect.center = location self.speed = speed self.increment_x = increment_x self.increment_y = increment_y self.sound = sound self.speed = speed def reverse_increment_x(self): '''Reversing x increment.''' self.increment_x *= -1 def move(self, increment_x, increment_y): '''Moving the ball.''' self.rect.move_ip(-1*self.increment_x*self.speed, 0) self.rect.move_ip(0, 1*self.increment_y*(self.speed//3)) def collision_left(self, smth): '''Ball hitting racket of Player 1.''' if (self.rect.left <= smth.rect.right) and (self.rect.top < smth.rect.bottom) and (self.rect.bottom > smth.rect.top): return True def collision_right(self, smth): '''Ball hitting racket of Palyer 2.''' if (self.rect.right >= smth.rect.left) and (self.rect.top < smth.rect.bottom) and (self.rect.bottom > smth.rect.top): return True def change_angle(self, smth): '''Change the ball's angle depending on how far from the center it hits the racket.''' a = self.rect.center[1] - smth.rect.top b = smth.rect.bottom - self.rect.center[1] angle = (smth.rect.center[1]-smth.rect.top)/(9000)*(b-a) self.increment_y = angle def hit_reaction(self, smth): '''Reaction of the ball for hitting the racket: hitting sound, reversing x increment and changing y increment depending on the hit.''' self.hit_sound() self.reverse_increment_x() self.change_angle(smth) def out_left(self, field): '''Check if the ball is out of the field and the point goes to player1.''' if ((self.rect.left > 1497) or (((self.rect.bottom < 156) or (self.rect.top > 700)) and (self.rect.left > field.rect.center[0]))): return True def out_right(self, field): '''Check if the ball is out of the field and the point goes to player2.''' if ((self.rect.right < 297) or (((self.rect.bottom < 156) or (self.rect.top > 700)) and (self.rect.right < field.rect.center[0]))): return True def reset_pos(self, new_loc): '''Reset the ball's position to center and increment y to 0.''' self.rect.center = new_loc self.increment_y = 0 def hit_sound(self): '''Sound of hitting the ball with a racket.''' pygame.mixer.music.load(self.sound) pygame.mixer.music.play(0) class Player(pygame.sprite.Sprite): '''Player class.''' def __init__(self, image_file, location, speed, up_key, down_key): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image_file) self.rect = self.image.get_rect() self.rect.center = location self.speed = speed self.up_key = up_key self.down_key = down_key def handle_keys(self): '''Moving rackets when user presses the button.''' key = pygame.key.get_pressed() if key[self.up_key]: if self.rect.top >= 156: self.rect.move_ip(0, -1*self.speed) if key[self.down_key]: if self.rect.bottom <= 700: self.rect.move_ip(0, 1*self.speed) def reset_pos(self, loc_x, loc_y): '''Reset the racket's position to the initial one.''' self.rect.center = (loc_x, loc_y) pygame.font.init() class Score(pygame.sprite.Sprite): '''Score class.''' def __init__(self, points1=0, points2=0): pygame.sprite.Sprite.__init__(self) self.myfont = pygame.font.SysFont('Liberation Sans', 30) self.points1 = points1 self.points2 = points2 self.plus_point_msg = 'One point for Player {}.' self.won_msg = 'Congratualtions, Player {}! You won the game.' self.congrats_song = 'tina_turner_the_best_cut.wav' def refresh(self, screen): '''Refreshing the score with the Players' points.''' self.textsurface = self.myfont.render('Player 1 points: {} Player 2 points: {}'.format(self.points1, self.points2), False, (255, 255, 255)) screen.blit(self.textsurface, (20, 20)) def plus_point1(self): '''Adding point to player 1.''' self.points1 += 1 def plus_point2(self): '''Adding point to player 2.''' self.points2 += 1 def play_congrats_song(self): '''Playing a congratulations song.''' pygame.mixer.music.load(self.congrats_song) pygame.mixer.music.play(0) def display_message(self, msg, screen, background, player_numb, waiting, dist): '''Displaying the add points and victory messages.''' msg_textsurface = self.myfont.render(msg.format(player_numb), False, (255, 255, 255)) screen.blit(msg_textsurface, (background.rect.center[0]-dist, 50)) self.refresh(screen) pygame.display.update() time.sleep(waiting) class Game(object): '''Game class.''' def __init__(self): self.speed = 10 self.background = Background('court.png', [0, 0]) self.screen = pygame.display.set_mode(self.background.rect.size) self.ball = Ball('ball.png', self.background.rect.center, self.speed, 1, 0, 'ball_hit.wav') self.player1 = Player('racket1.png', [297, self.background.rect.center[1]], self.speed, pygame.K_w, pygame.K_s) self.player2 = Player('racket2.png', [1497, self.background.rect.center[1]], self.speed, pygame.K_UP, pygame.K_DOWN) self.score = Score() self.running = True def display_objects(self): '''Displaying all objects on the screen.''' self.screen.blit(self.background.image, self.background.rect) self.screen.blit(self.ball.image, self.ball.rect) self.screen.blit(self.player1.image, self.player1.rect) self.screen.blit(self.player2.image, self.player2.rect) def reset_positions(self): '''Reset the positions of the rackets and the ball.''' self.ball.reset_pos(self.background.rect.center) self.player1.reset_pos(297, self.background.rect.center[1]) self.player2.reset_pos(1497, self.background.rect.center[1]) def add_points(self, player_numb): '''Adding one point to player 1 or 2 and ending the game if they have won.''' if player_numb == 1: self.score.plus_point1() else: self.score.plus_point2() if ((self.score.points1 == 6) or (self.score.points2 == 6)): self.score.play_congrats_song() self.score.display_message(self.score.won_msg, self.screen, self.background, player_numb, 20, 300) self.end_game() else: self.score.display_message(self.score.plus_point_msg, self.screen, self.background, player_numb, 4, 150) def end_game(): '''Ending the game.''' self.running = False def play_game(self): '''Playing process.''' pygame.display.set_caption('Tennis Game') for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False self.display_objects() self.player1.handle_keys() self.player2.handle_keys() if self.ball.collision_left(self.player1): self.ball.hit_reaction(self.player1) if self.ball.collision_right(self.player2): self.ball.hit_reaction(self.player2) self.ball.move(self.ball.increment_x, self.ball.increment_y) if self.ball.out_left(self.background): self.add_points(1) self.reset_positions() if self.ball.out_right(self.background): self.add_points(2) self.reset_positions() self.score.refresh(self.screen) pygame.display.update() tennis_game = Game() while tennis_game.running: tennis_game.play_game()
#!/usr/bin/env python #-*- coding:utf-8 -*- """ Mercury data This program provides the Mercury data for the simulation Author: Sandro Ricardo De Souza: sandro.fisica@gmail.com """ # Import modules import numpy as np import pandas as pd import oe2pv import math # Name for each Mercury's cadidates varying the semi-axis sufix_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] # Numbers of the Mercury's candidates varying the angles candidates_per_dist = 100 # Conic section is ellipse (see Swift documentation) ialpha = -1 # Gravitational factor of the Sun gm = 2.959139768995959e-04 # Define semi-axis mercury_distances = np.arange(0.05, 0.55, 0.05) a = np.repeat(mercury_distances, candidates_per_dist) # Define column Mercury Name mercury_name = [] for char in sufix_list: for number in range(candidates_per_dist): name = 'mercury' + char + str(number) mercury_name.append(name) mercury_name = pd.Series(mercury_name) # Define e, i low_e = 0 high_e = 0.05 low_i = 0 high_i = 0.05 numbers_mercurys = len(sufix_list) * candidates_per_dist e = pd.Series(np.random.uniform(low_e, high_e, numbers_mercurys)) i = pd.Series(np.random.uniform(low_i, high_i, numbers_mercurys)) # Define capom omega e M capom = np.random.uniform(0, 360, numbers_mercurys) omega = np.random.uniform(0, 360, numbers_mercurys) M = np.random.uniform(0, 360, numbers_mercurys) # Gerando o Data Frame inicial mercury = pd.DataFrame({'mercurys': mercury_name, 'a': a, 'e':e, \ 'i':i, 'capom':capom, 'omega':omega, 'M':M}) mercury = mercury.set_index('mercurys') # Including mass, radio and mass_grav (equals to the Earth) mass = 5.972300e+24 mercury['mass'] = np.repeat(mass, numbers_mercurys) radio = 6378.137 mercury['radio'] = np.repeat(radio, numbers_mercurys) mass_grav = 8.887539e-10 mercury['mass_grav'] = np.repeat(mass_grav, numbers_mercurys) # Including period for each mercury def periodKepler(semi_axis, M_planet): """ Calculate the period using Kepler's third law Input semi_axis: semi-axis [au] M_planet: mass of the planet [kg] Output period [days] """ M_sol_kg = 1.9891e30 M_sol_G = 2.959139768995959e-04 M_grav = M_sol_G * M_planet / M_sol_kg period = np.sqrt(((2 * np.pi)**2 * semi_axis**3) / (M_sol_G + M_grav)) return(period) period = periodKepler(mercury.a, mercury.mass) mercury['period'] = period # Determine position and velocity x = np.zeros(numbers_mercurys) y = np.zeros(numbers_mercurys) z = np.zeros(numbers_mercurys) vx = np.zeros(numbers_mercurys) vy = np.zeros(numbers_mercurys) vz = np.zeros(numbers_mercurys) for j in range(len(mercury)): x[j], y[j], z[j], vx[j], vy[j], vz[j] = oe2pv.orbel_el2xv(gm,ialpha,\ a[j],e[j],math.radians(i[j]),\ math.radians(capom[j]),\ math.radians(omega[j]),M[j]) # Create colums x, y, v, vx, vy and vz in data frame mercury['x'] = x mercury['y'] = y mercury['z'] = z mercury['vx'] = vx mercury['vy'] = vy mercury['vz'] = vz # Create csv files from Mercury data mercury.to_csv('Planets/mercury.csv')
# ็ป™ๅฎšไธ€ไธช n ร— n ็š„ไบŒ็ปด็Ÿฉ้˜ต matrix ่กจ็คบไธ€ไธชๅ›พๅƒใ€‚่ฏทไฝ ๅฐ†ๅ›พๅƒ้กบๆ—ถ้’ˆๆ—‹่ฝฌ 90 ๅบฆใ€‚ # # ไฝ ๅฟ…้กปๅœจ ๅŽŸๅœฐ ๆ—‹่ฝฌๅ›พๅƒ๏ผŒ่ฟ™ๆ„ๅ‘ณ็€ไฝ ้œ€่ฆ็›ดๆŽฅไฟฎๆ”น่พ“ๅ…ฅ็š„ไบŒ็ปด็Ÿฉ้˜ตใ€‚่ฏทไธ่ฆ ไฝฟ็”จๅฆไธ€ไธช็Ÿฉ้˜ตๆฅๆ—‹่ฝฌๅ›พๅƒใ€‚ # # # # ็คบไพ‹ 1๏ผš # # # ่พ“ๅ…ฅ๏ผšmatrix = [[1,2,3],[4,5,6],[7,8,9]] # ่พ“ๅ‡บ๏ผš[[7,4,1],[8,5,2],[9,6,3]] # # # ็คบไพ‹ 2๏ผš # # # ่พ“ๅ…ฅ๏ผšmatrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # ่พ“ๅ‡บ๏ผš[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] # # # ็คบไพ‹ 3๏ผš # # # ่พ“ๅ…ฅ๏ผšmatrix = [[1]] # ่พ“ๅ‡บ๏ผš[[1]] # # # ็คบไพ‹ 4๏ผš # # # ่พ“ๅ…ฅ๏ผšmatrix = [[1,2],[3,4]] # ่พ“ๅ‡บ๏ผš[[3,1],[4,2]] # # # # # ๆ็คบ๏ผš # # # matrix.length == n # matrix[i].length == n # 1 <= n <= 20 # -1000 <= matrix[i][j] <= 1000 # # Related Topics ๆ•ฐ็ป„ # ๐Ÿ‘ 800 ๐Ÿ‘Ž 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ # leetcode submit region end(Prohibit modification and deletion)
# ็ป™ๅฎšไธ€็ง่ง„ๅพ‹ pattern ๅ’Œไธ€ไธชๅญ—็ฌฆไธฒ str ๏ผŒๅˆคๆ–ญ str ๆ˜ฏๅฆ้ตๅพช็›ธๅŒ็š„่ง„ๅพ‹ใ€‚ # # ่ฟ™้‡Œ็š„ ้ตๅพช ๆŒ‡ๅฎŒๅ…จๅŒน้…๏ผŒไพ‹ๅฆ‚๏ผŒ pattern ้‡Œ็š„ๆฏไธชๅญ—ๆฏๅ’Œๅญ—็ฌฆไธฒ str ไธญ็š„ๆฏไธช้ž็ฉบๅ•่ฏไน‹้—ดๅญ˜ๅœจ็€ๅŒๅ‘่ฟžๆŽฅ็š„ๅฏนๅบ”่ง„ๅพ‹ใ€‚ # # ็คบไพ‹1: # # ่พ“ๅ…ฅ: pattern = "abba", str = "dog cat cat dog" # ่พ“ๅ‡บ: true # # ็คบไพ‹ 2: # # ่พ“ๅ…ฅ:pattern = "abba", str = "dog cat cat fish" # ่พ“ๅ‡บ: false # # ็คบไพ‹ 3: # # ่พ“ๅ…ฅ: pattern = "aaaa", str = "dog cat cat dog" # ่พ“ๅ‡บ: false # # ็คบไพ‹ 4: # # ่พ“ๅ…ฅ: pattern = "abba", str = "dog dog dog dog" # ่พ“ๅ‡บ: false # # ่ฏดๆ˜Ž: # ไฝ ๅฏไปฅๅ‡่ฎพ pattern ๅชๅŒ…ๅซๅฐๅ†™ๅญ—ๆฏ๏ผŒ str ๅŒ…ๅซไบ†็”ฑๅ•ไธช็ฉบๆ ผๅˆ†้š”็š„ๅฐๅ†™ๅญ—ๆฏใ€‚ # Related Topics ๅ“ˆๅธŒ่กจ # ๐Ÿ‘ 219 ๐Ÿ‘Ž 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def wordPattern(self, pattern: str, s: str) -> bool: """ ่งฃๆณ•ไธ€: hash_map(p2s) + list ่งฃๆณ•ไบŒ(C++): ไธคไธชhash_map(s2pๅ’Œp2s) + stringstream(็”จไบŽๆŒจไธชๅค„็†sไธญ็š„ๅญ—็ฌฆไธฒ) ่งฃๆณ•ไธ‰: ไธคไธชhash_map(string_2_int)๏ผŒpๅ’Œs้ƒฝๆ˜ ๅฐ„ๅˆฐint๏ผŒๅœจ้€ไธชๆ˜ ๅฐ„็š„ๅŒๆ—ถๆŠŠ่ฝฌๆขๅŽ็š„intๅ€ผๆทปๅŠ ๅˆฐไธ€ไธชlistไธญ๏ผŒ็„ถๅŽๅˆคๆ–ญไธคไธชlistๆ˜ฏๅฆ็›ธ็ญ‰ """ used = [] m = collections.defaultdict() s_list = s.split(' ') if len(s_list) != len(pattern): return False for i in range(len(pattern)): if pattern[i] not in m.keys(): if s_list[i] not in used: # ๅฝ“้‡ๅˆฐ็š„patternๆ˜ฏๆ–ฐ็š„ๆ—ถ๏ผŒ้œ€่ฆไฟ่ฏๅฎƒๅฏนๅบ”็š„ๅ€ผๆฒกๆœ‰่ขซ็”จ่ฟ‡๏ผŒ้˜ฒๆญขpattern = "ab", str = "dog dog"่ฟ”ๅ›žtrue m[pattern[i]] = s_list[i] used.append(s_list[i]) else: return False else: if not m[pattern[i]] == s_list[i]: return False return True # leetcode submit region end(Prohibit modification and deletion)
# ็ป™ๅฎšไธ€ไธช้“พ่กจ๏ผŒไธคไธคไบคๆขๅ…ถไธญ็›ธ้‚ป็š„่Š‚็‚น๏ผŒๅนถ่ฟ”ๅ›žไบคๆขๅŽ็š„้“พ่กจใ€‚ # # ไฝ ไธ่ƒฝๅชๆ˜ฏๅ•็บฏ็š„ๆ”นๅ˜่Š‚็‚นๅ†…้ƒจ็š„ๅ€ผ๏ผŒ่€Œๆ˜ฏ้œ€่ฆๅฎž้™…็š„่ฟ›่กŒ่Š‚็‚นไบคๆขใ€‚ # # # # ็คบไพ‹: # # ็ป™ๅฎš 1->2->3->4, ไฝ ๅบ”่ฏฅ่ฟ”ๅ›ž 2->1->4->3. # # Related Topics ้“พ่กจ # ๐Ÿ‘ 620 ๐Ÿ‘Ž 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: # ListNode pre(None) # ่ฟ™ๆ˜ฏc++็š„ๅฎšไน‰ๆ–นๅผ pre = ListNode(None) pre.next = head ret = pre # ret = pre.next.next # ็ฉบ้“พ่กจ่ฟ›ๆฅ็š„่ฏๆฒกๆœ‰.next๏ผŒไผšๅ‡บ้”™ while pre.next and pre.next.next: first = pre.next second = pre.next.next first.next = second.next second.next = first pre.next = second pre = first return ret.next # leetcode submit region end(Prohibit modification and deletion)
# ๅœจไธŠๆฌกๆ‰“ๅŠซๅฎŒไธ€ๆก่ก—้“ไน‹ๅŽๅ’Œไธ€ๅœˆๆˆฟๅฑ‹ๅŽ๏ผŒๅฐๅทๅˆๅ‘็Žฐไบ†ไธ€ไธชๆ–ฐ็š„ๅฏ่กŒ็ชƒ็š„ๅœฐๅŒบใ€‚่ฟ™ไธชๅœฐๅŒบๅชๆœ‰ไธ€ไธชๅ…ฅๅฃ๏ผŒๆˆ‘ไปฌ็งฐไน‹ไธบโ€œๆ นโ€ใ€‚ ้™คไบ†โ€œๆ นโ€ไน‹ๅค–๏ผŒๆฏๆ ‹ๆˆฟๅญๆœ‰ไธ”ๅชๆœ‰ไธ€ไธชโ€œ็ˆถโ€œ # ๆˆฟๅญไธŽไน‹็›ธ่ฟžใ€‚ไธ€็•ชไพฆๅฏŸไน‹ๅŽ๏ผŒ่ชๆ˜Ž็š„ๅฐๅทๆ„่ฏ†ๅˆฐโ€œ่ฟ™ไธชๅœฐๆ–น็š„ๆ‰€ๆœ‰ๆˆฟๅฑ‹็š„ๆŽ’ๅˆ—็ฑปไผผไบŽไธ€ๆฃตไบŒๅ‰ๆ ‘โ€ใ€‚ ๅฆ‚ๆžœไธคไธช็›ดๆŽฅ็›ธ่ฟž็š„ๆˆฟๅญๅœจๅŒไธ€ๅคฉๆ™šไธŠ่ขซๆ‰“ๅŠซ๏ผŒๆˆฟๅฑ‹ๅฐ†่‡ชๅŠจๆŠฅ่ญฆใ€‚ # # ่ฎก็ฎ—ๅœจไธ่งฆๅŠจ่ญฆๆŠฅ็š„ๆƒ…ๅ†ตไธ‹๏ผŒๅฐๅทไธ€ๆ™š่ƒฝๅคŸ็›—ๅ–็š„ๆœ€้ซ˜้‡‘้ขใ€‚ # # ็คบไพ‹ 1: # # ่พ“ๅ…ฅ: [3,2,3,null,3,null,1] # # 3 # / \ # 2 3 # \ \ # 3 1 # # ่พ“ๅ‡บ: 7 # ่งฃ้‡Š:ย ๅฐๅทไธ€ๆ™š่ƒฝๅคŸ็›—ๅ–็š„ๆœ€้ซ˜้‡‘้ข = 3 + 3 + 1 = 7. # # ็คบไพ‹ 2: # # ่พ“ๅ…ฅ: [3,4,5,1,3,null,1] # # ย  3 # / \ # 4 5 # / \ \ # 1 3 1 # # ่พ“ๅ‡บ: 9 # ่งฃ้‡Š:ย ๅฐๅทไธ€ๆ™š่ƒฝๅคŸ็›—ๅ–็š„ๆœ€้ซ˜้‡‘้ขย = 4 + 5 = 9. # # Related Topics ๆ ‘ ๆทฑๅบฆไผ˜ๅ…ˆๆœ็ดข # ๐Ÿ‘ 737 ๐Ÿ‘Ž 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rob(self, root: TreeNode) -> int: """ ๆญฃ่งฃ: DFS + dp 1. ๅฝ“ๅ‰่Š‚็‚น้€‰ๆ‹ฉไธๅทๆ—ถ๏ผŒ่ƒฝๅทๅˆฐ็š„ๆœ€ๅคง้’ฑๆ•ฐ = ๅทฆๅญฉๅญ่ƒฝๅทๅˆฐ็š„้’ฑ + ๅณๅญฉๅญ่ƒฝๅทๅˆฐ็š„้’ฑ๏ผˆ=max(ๅท๏ผŒไธๅท)๏ผŒๅทฆๅณๅญฉๅญไธไธ€ๅฎšๅท๏ผ‰ 2. ๅฝ“ๅ‰่Š‚็‚น้€‰ๆ‹ฉๅทๆ—ถ๏ผŒ่ƒฝๅทๅˆฐ็š„ๆœ€ๅคง้’ฑๆ•ฐ = ๅทฆๅญฉๅญ้€‰ๆ‹ฉ่‡ชๅทฑไธๅทๆ—ถ่ƒฝๅพ—ๅˆฐ็š„้’ฑ + ๅณๅญฉๅญ้€‰ๆ‹ฉไธๅทๆ—ถ่ƒฝๅพ—ๅˆฐ็š„้’ฑ + ๅฝ“ๅ‰่Š‚็‚น็š„้’ฑๆ•ฐ ็ปผไธŠ๏ผŒ้œ€่ฆๅพ—ๅˆฐๅทฆๅณๅญฉๅญๅˆ†ๅˆซๅทๅ’Œไธๅทๆ—ถ็š„ๆœ€ๅคง้’ฑๆ•ฐ๏ผŒๆ‰่ƒฝ่ฎก็ฎ—ๅพ—ๅˆฐๅฝ“ๅ‰่Š‚็‚น็š„ๆœ€ๅคง้’ฑๆ•ฐใ€‚ ไฝ†ๅฝ“ๅ‰robๅ‡ฝๆ•ฐๅช่ƒฝ่ฟ”ๅ›žไธ€ไธชๅ€ผ๏ผŒๆ‰€ไปฅๆƒณๅˆฐ่ฆ็”จไธ€ไธชhelperๅ‡ฝๆ•ฐ """ def helper(cur): if not cur: return 0, 0 # ๅ…ˆๆฑ‚ๅ‡บๅทฆๅณๅญฉๅญๅˆ†ๅˆซ็š„ๅทไธŽไธๅท็š„ๆœ€ๅคง้’ฑๆ•ฐ left_tou, left_butou = helper(cur.left) right_tou, right_butou = helper(cur.right) # ็„ถๅŽๆ นๆฎdpๆ–น็จ‹่ฎก็ฎ—ๅฝ“ๅ‰่Š‚็‚นๅนถ่ฟ”ๅ›ž butou = max(left_butou, left_tou) + max(right_butou, right_tou) tou = cur.val + left_butou + right_butou return tou, butou if not root: return 0 tou, butou = helper(root) return max(tou, butou) """ ้”™่งฃ1๏ผšBFS๏ผŒๅฅ‡ๅถๅฑ‚็š„ๆ€ปๅ’Œไธญ่พƒๅคš็š„่พ“ๅ‡บ๏ผˆๅฏไปฅๅชๅ–็ฌฌ1ๅฑ‚ๅ’Œ็ฌฌ4ๅฑ‚๏ผ‰ ้”™่งฃ2: ๆ นๆฎDP็š„ๆ€ๆƒณ๏ผŒๅฏไปฅๆŠŠๆฏไธ€ๅฑ‚็š„ๆ€ปๅ’Œๅ…ˆ็”จBFSๆŽ’ๆˆๆ•ฐ็ป„๏ผŒ็„ถๅŽdp๏ผˆ[2,1,3,null,4]ไผšๅ‡บ้”™๏ผŒๅฏไปฅ็›ธ้‚ปไธคๅฑ‚ๅ–ไธๅœจๅŒไธ€่ทฏๅพ„็š„่Š‚็‚น๏ผ‰ # if not root: return 0 # dp = [] # # # BFS # q = collections.deque() # q.append(root) # while q: # size = len(q) # curSum = 0 # for _ in range(size): # cur = q.popleft() # curSum += cur.val # # if cur.left: q.append(cur.left) # if cur.right: q.append(cur.right) # # dp.append(curSum) # # # dp # butou, tou = 0, 0 # for i in range(len(dp)): # butou_new = max(butou, tou) # tou_new = butou + dp[i] # tou = tou_new # butou = butou_new # # return max(butou, tou) """ # leetcode submit region end(Prohibit modification and deletion)
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'andylin' __date__ = '17-12-28 ไธŠๅˆ11:06' import threading import time import os def run(num): print('runing on number %s ' % (num)) time.sleep(3) print("------all status-------", threading.current_thread()) thread_list = [] start_time = time.time() for i in range(50): t = threading.Thread(target=run,args=('t--%s ' % i,)) t.setDaemon(True) #ๆŠŠๅฝ“ๅ‰็บฟ็จ‹่ฎพ็ฝฎไธบๅฎˆๆŠค็บฟ็จ‹ t.start() thread_list.append(t) #ไธบไบ†ไธ้˜ปๅกžๅŽ้ข็บฟ็จ‹็š„ๅฏๅŠจ๏ผŒไธๅœจ่ฟ™้‡Œjoin๏ผŒๅ…ˆๆ”พๅˆฐไธ€ไธชๅˆ—่กจ้‡Œ #print('--all--',threading.current_thread()) #ๅฆ‚ๆžœๆฒกๆœ‰ๆ‰ง่กŒjoin ่ฟ›่กŒ็ญ‰ๅพ…,ๅˆ™ๅพˆๅฟซ #for j in thread_list: # j.join() #threading.active_count() ๆ˜พ็คบ็บฟ็จ‹็š„ไธชๆ•ฐ #threading.current_thread() ๆ˜พ็คบ็บฟ็จ‹็š„็Šถๆ€ print("------all master--------",threading.current_thread(),threading.active_count()) print("cost: ",time.time() - start_time)
# Randamized Quick Sort Algorithm # Time Complexity ==> Best Case O(NlogN), Worst Case O(NlogN) # Space Complexity ==> O(1) import random def partitionSort(array,p,r): pivot = array[p] i = p j = i+1 while j<=r: if pivot<array[j]: j +=1 else: i +=1 temp = array[j] array[j] = array[i] array[i] = temp j +=1 temp = array[p] array[p] = array[i] array[i] = temp return i def randomQuickSort(array,p,r): if p<r: random_num = random.randint(p+1,r) temp = array[p] array[p] = array[random_num] array[random_num]= temp pivot = partitionSort(array,p,r) randomQuickSort(array,0,pivot-1) randomQuickSort(array,pivot+1,r) if __name__ == "__main__": array = [6,4,3,2,1,100,90,82,72,89,56,77,0,-8,-16,5559,-898756] randomQuickSort(array,0,len(array)-1) print(array)
for _ in range(int(input("Enter Passes"))): l=[int(i) for i in input().split()] def bubblesort(l): n=len(l) for i in range(n): swapped=False for j in range(n-1-i): if l[j] > l[j+1]: l[j] , l[j+1] = l[j+1],l[j] swapped=True if swapped==False: break bubblesort(l) print(l)
def greet(): return ("Welcome to the Calculator App- your very limited calc app") print(greet()) input_1 = float(input("What is your first number? ")) input_2 = input("What do you want to do with that number? (ie. +,-,*,/) ") input_3 = float(input("Give me one last number that will affect that first number you entered ")) def operator(one, two, three): if two == "+": answer = (one) + (three) return (answer) elif two == "-": answer = (one) - (three) return (answer) elif two == "*": answer = (one) * (three) return (answer) elif two == "/": answer = (one) / (three) return (answer) else: return("You must use either (+,-,*,/) for me to function") print(operator(input_1, input_2, input_3
def bubbleSort(list): for i in range (0,len(list) -1): for j in range(0, len(list) - 1 - i): if list[j] > list[j+1]: list[j], list[j+1] = list[j+1], list[j] return list list = [2,55,6,969,13,1000] print(bubbleSort(list))
import json user_input = "" name = input("What is your name?") with open("guest.json",'w') as file_object: json.dump(name,file_object) responses = [] while user_input != "QUIT": user_input = input("Why do you like programming?") responses.append(user_input) with open("guest.json",'a') as file_object: json.dump(responses,file_object)
def iterative(it, size): conses = [] for el in it: conses.append([]) for index, cons in enumerate(conses): cons.append(el) # print(el, "--", conses) if len(conses[0]) == size: yield conses.pop(0) def recursive(it, size): it = iter(it) def helper(conses, it): conses = [*conses, []] el = next(it) for index, cons in enumerate(conses): cons.append(el) # print(el, "--", conses) if len(conses[0]) == size: head, *tail = conses yield head yield from helper(tail, it) else: yield from helper(conses, it) yield from helper([], it) import unittest class TestEachCons(unittest.TestCase): def helper(self, each_cons): it = range(5) out = [list(cons) for cons in each_cons(it, 3)] exp = [[0, 1, 2], [1, 2, 3], [2, 3, 4]] self.assertEqual(exp, out) def test_iterative(self): self.helper(iterative) def test_recursive(self): self.helper(recursive)
# Detect Pangram # Check if string s contains all alphabet characters import string ''' orginal version def is_pangram(s): return len(set(string.ascii_lowercase)) <= len(set(s.lower())) ''' # Better one: def is_pangram(s): return set(string.ascii_lowercase) <= set(s.lower()) # set operation "<=" checks if right side set contains all elements of left set
def tree_from_string(s, tokens=None, add_space=False): if tokens is not None: assert add_space is False return recursive_parse(tokens)[0] if add_space: s = s.replace('(', '( ').replace(')', ' )') return recursive_parse(s.split())[0] def recursive_parse(tokens, pos=0): if tokens[pos + 2] != '(': label = tokens[pos + 1] leaf = tokens[pos + 2] size = 4 node = (label, leaf) return node, size size = 2 nodes = [] while tokens[pos + size] != ')': xnode, xsize = recursive_parse(tokens, pos + size) size += xsize nodes.append(xnode) size += 1 label = tokens[pos + 1] children = tuple(nodes) node = (label, children) return node, size def print_tree(tree): def helper(tr): label, tr = tr if isinstance(tr, str): return '({} {})'.format(label, tr) nodes = [helper(x) for x in tr] return '({} {})'.format(label, ' '.join(nodes)) return helper(tree) def tree_to_leaves(tree): def helper(tr): label, tr = tr if isinstance(tr, str): return [tr] nodes = [] for x in tr: nodes += helper(x) return nodes return helper(tree)
import cv2 import numpy as np def drawcontours(img): ''' This function is to draw contours on original image ''' image = cv2.imread(img) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (13, 13), 0) edged = cv2.Canny(blurred, 30, 150) contours, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contour_list = [] for contour in contours: approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True) area = cv2.contourArea(contour) if ((len(approx) > 7) & (area > 300)): contour_list.append(contour) img_copy = image.copy() cv2.drawContours(img_copy, contour_list, -1, (255, 0, 0), 2) cv2.imwrite('../img.png', img_copy)
import math def primality(n): a = 0 if n < 2: return False for i in range(2, math.ceil(math.sqrt(n)) + 1): if n % i == 0: a += 1 if a == 0: return True else: return False # ะŸั€ะธะผะตั€ print( primality(61) )
#Using quicksort to sort the list def partition(list, low, high): i = (low-1) pivot = list[high] for x in range(low, high): if list[x] <= pivot: i = i+1 list[i], list[x] = list[x], list[i] list[i+1], list[high] = list[high], list[i+1] return (i+1) def quicksort(list, low, high): if len(list) == 1: return list if low < high: pi = partition(list, low, high) quicksort(list, low, pi-1) quicksort(list, pi+1, high) return list def largestproduct(list): if len(list) < 3: return "List must have 3 or more numbers" list = quicksort(list, 0, len(list)-1) #The largest product of three numbers in a sorted list must either be the first 2 numbers #(because we can have negative numbers), and the last number in the list which is the largest number #Or it must be the three last numbers in the list. Checking which one of these two possible outcomes are largest, and returning #the largest of these 2 prod1 = list[0]*list[1]*list[len(list)-1] prod2 = list[len(list)-1]*list[len(list)-2]*list[len(list)-3] if prod1 > prod2: return prod1 else: return prod2 arr = [5, 6, 7, -10, -12, -3, 20, 5] print(largestproduct(arr))
#Iteration 3: Loop it to run 1000 times import random import numpy def run_simulation(): counter = 0 day_number = 0 prisoner_chief = 1 lever_position = 'down' prisoners_who_have_operated_lever = [] while counter < 50: prisoner_number = random.randint(1,50) # Select a prisoner if not prisoner_number in prisoners_who_have_operated_lever: if lever_position == 'down': prisoners_who_have_operated_lever.append(prisoner_number) lever_position = 'up' if prisoner_number == prisoner_chief: if lever_position == 'up': lever_position = 'down' counter += 1 day_number += 1 return day_number simulation_results = [] simulations = 0 while simulations < 1000: simulation_results.append(run_simulation()) simulations += 1 simulation_results = numpy.array(simulation_results) print numpy.mean(simulation_results)
# Iteration 4: Monte Carlo simulator to method; parameterize no. of prisoners # and no. of runs; prettify output from numpy import array, mean import random def run_simulation(number_of_prisoners): counter = 0 day_number = 0 prisoner_chief = 1 prisoner_chief_has_not_operated_lever = True lever_position = 'down' prisoners_who_have_operated_lever = [] while counter < number_of_prisoners-1 or prisoner_chief_has_not_operated_lever: day_number += 1 prisoner_number = random.randint(1,number_of_prisoners) # Select a prisoner new_prisoner = prisoner_number not in prisoners_who_have_operated_lever not_prisoner_chief = prisoner_number != prisoner_chief if new_prisoner and not_prisoner_chief: if lever_position == 'down': prisoners_who_have_operated_lever.append(prisoner_number) lever_position = 'up' if prisoner_number == prisoner_chief: prisoner_chief_has_not_operated_lever = False if lever_position == 'up': lever_position = 'down' counter += 1 return day_number def monte_carlo(number_of_experiments, prisoner_count): simulation_results = [] simulations = 0 while simulations < number_of_experiments: simulation_results.append(run_simulation(prisoner_count)) simulations += 1 simulation_results = array(simulation_results) #convert to numpy array return simulation_results monte_carlo_simulation = monte_carlo(500,100) average = mean(monte_carlo_simulation) message = "The simulation with {} results took an average of {} days or {} months or {} years to finish." print(message.format(500, average, average/12, average/365.0)) """ Consider prisoners A and B. A is the counter. Probabilty of choosing A = P(A) = 0.5 Probability of choosing B = P(B) = 0.5 Every time B is followed by A, the game is over. Possible outcomes: BA ABA BBA AABA ABBA BBBA ABBBA AABBA Probability of choosing A then B: P(A)*P(B) = 0.5^2 = 0.25 Probablity of choosing B then A: P(B)*P(A) = 0.5^2 = 0.25 """
from ClaseProyecto import Proyecto import csv class ManejadorProyecto: __lista=[] def __init__(self): self.__lista=[] def CargarProyectos(self): archivo=open("proyectos.csv") reader=csv.reader(archivo,delimiter=';') for fila in reader: P=Proyecto(fila[0],fila[1],fila[2]) self.__lista.append(P) archivo.close() def CalcularPuntos(self,MI): for i in range(len(self.__lista)): id=self.__lista[i].getid() cont=MI.Contador(id) if int(cont)>=3: self.__lista[i].CargarPuntos(10) elif int(cont)<3: self.__lista[i].CargarPuntos(-20) print("\nEl Proyecto {} debe tener como mรญnimo 3 integrantes.".format(id)) bandera,director=MI.BuscarDirector(id) if bandera==True: self.__lista[i].CargarPuntos(10) elif bandera ==False: self.__lista[i].CargarPuntos(-5) print("\nEl Director del Proyecto {} debe tener categorรญa I o II.".format(id)) bandera2,codirector=MI.BuscarCoDirector(id) if bandera2==True: self.__lista[i].CargarPuntos(10) elif bandera2 ==False: self.__lista[i].CargarPuntos(-5) print("\nEl Codirector del Proyecto {} debe tener como mรญnimo categorรญa III.".format(id)) if director==False or codirector==False: self.__lista[i].CargarPuntos(-10) if director==False: print("\nEl Proyecto {} debe tener un Director".format(id)) if codirector==False: print("\nEl Proyecto {} debe tener un Codirector".format(id)) def MostrarPuntos(self): self.ordenar() for i in range(len(self.__lista)): print("\nPosiciรณn {}".format(i+1)) print("\nTitulo: {} \nPuntos: {}".format(self.__lista[i].gettitulo(),self.__lista[i].getpuntos())) print("---------------------------------") def ordenar(self): for i in range(len(self.__lista)): for j in range(i+1,len(self.__lista)): if self.__lista[j]>self.__lista[i]: aux=self.__lista[i] self.__lista[i]=self.__lista[j] self.__lista[j]=aux
__author__ = 'Djidiouf' # Python built-in modules from datetime import datetime, timedelta # displaying date and time # Third-party modules import pytz # install module: pytz # timezone information # Project modules import modules.connection import modules.time def main(i_string, i_medium, i_alias=None): """ Responds to an input as "!meet <Continent/City> <HH:MM>" Timezone available here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones /!\ currently only "utc" is working :param i_string: a string with these elements: "<Continent/City> <HH:MM>" :print: time in different timezones """ # Divide a string in a tuple: 'str1', 'separator', 'str2' tuple_string = i_string.partition(' ') if ':' in tuple_string[0]: # Process either !meet Europe/Oslo 10:00 or !meet 10:00 Europe/Oslo time_string = tuple_string[0] tz_requested = tuple_string[2] else: time_string = tuple_string[2] tz_requested = tuple_string[0] # Divide a string in a tuple: 'str1', 'separator', 'str2' tuple_time = time_string.partition(':') simple_hour = tuple_time[0] simple_minute = tuple_time[2] tz_requested = modules.time.capitalize_timezone(tz_requested) try: tz_requested = pytz.timezone(tz_requested) except pytz.exceptions.UnknownTimeZoneError: modules.connection.send_message("Timezone not found", i_medium, i_alias) raise ValueError('Timezone not found') # UTC detailed # time_utc = datetime.now(pytz.utc) # modules.connection.send_message("DEBUG UTC: " + time_utc.strftime(format)) year_utc = datetime.now(pytz.utc).year month_utc = datetime.now(pytz.utc).month day_utc = datetime.now(pytz.utc).day hour_utc = datetime.now(pytz.utc).hour minute_utc = datetime.now(pytz.utc).minute hour = int(simple_hour) # Need to be int and not string minute = int(simple_minute) # Need to be int and not string format = "%H:%M" # format = "%Y-%m-%d - %H:%M:%S - %Z%z" # full format # modules.connection.send_message("DEBUG req: " + str(hour) +"H : " + str(minute) + "M") # modules.connection.send_message("DEBUG utc: " + str(hour_utc) +"H : " + str(minute_utc) + "M") # hour_diff = hour - hour_utc # minute_diff = minute - minute_utc # modules.connection.send_message("DEBUG diff: " + str(hour_diff) +"H : " + str(minute_diff) + "M") hour_req = datetime.now(tz_requested).hour minute_req = datetime.now(tz_requested).minute decal_h = hour_req - hour_utc decal_m = minute_req - minute_utc # modules.connection.send_message("DEBUG decalageH: " + str(hour_req) + " - " + str(hour_utc) + " = " + str(decal_h)) # modules.connection.send_message("DEBUG decalageM: " + str(minute_req) + " - " + str(minute_utc) + " = " + str(decal_m)) hour_new = hour-decal_h minute_new = minute-decal_m # print("hour_new : " + str(hour_new)) # print("minute_new: " + str(minute_new)) if hour_new < 0: hour_new += 24 # print("---- hour_new +24") if hour_new == 24: hour_new = 0 if hour_new > 24: hour_new -= 24 # print("---- hour_new -24") if minute_new == 60: minute_new = 0 hour_new += 1 # print("---- hour_new +1") if minute_new > 60: minute_new -= 60 hour_new += 1 # print("---- hour_new +1") if minute_new < 0: minute_new += 60 hour_new -= 1 # print("---- hour_new -1") # print("hour_new revised: " + str(hour_new)) # print("minute_new revis: " + str(minute_new)) # time_requested = datetime(year_utc, month_utc, day_utc, hour_new, minute_new, 0, 0, pytz.utc).astimezone(pytz.timezone(str(tz_requested))) # modules.connection.send_message(time_requested.strftime(format) + " - %s" % str(tz_requested)) tz_one = "Europe/London" tz_two = "Europe/Oslo" tz_three = "Australia/Sydney" time_one = datetime(year_utc, month_utc, day_utc, hour_new, minute_new, 0, 0, pytz.utc).astimezone(pytz.timezone(tz_one)) modules.connection.send_message(time_one.strftime(format) + " - %s" % tz_one, i_medium, i_alias) time_two = datetime(year_utc, month_utc, day_utc, hour_new, minute_new, 0, 0, pytz.utc).astimezone(pytz.timezone(tz_two)) modules.connection.send_message(time_two.strftime(format) + " - %s" % tz_two, i_medium, i_alias) time_three = datetime(year_utc, month_utc, day_utc, hour_new, minute_new, 0, 0, pytz.utc).astimezone(pytz.timezone(tz_three)) modules.connection.send_message(time_three.strftime(format) + " - %s" % tz_three, i_medium, i_alias)
from A_star_search_Romania_Map import * import time import random cities=["Craiova","Pitesti","Bucuresti","Oradea","Arad","Eforie","Drobeta","Fagaras","Giurgiu","Zerind","Timisoara", "Sibiu","Lugoj","Mehadia","Ramnicu Valcea","Urziceni","Hirsova","Vaslui","Iasi","Neamt"] with open('graph.txt', 'r') as file: lines = file.readlines() #fill the graph and build graph = build_graph_weighted(lines[1:]) #random or keyboard input data if(int(input("Enter 1 if you want random city or 2 if you want to introduce them\n"))==1): start=cities[random.randint(0,len(cities)-1)] dest=cities[random.randint(0,len(cities)-1)] print(" Start city of first friend: "+start +"\n"+" Start city of the second friend: "+ dest) else: start = input("Enter the starting city of the first friend\n") dest = input("Enter the starting city of the second friend\n") t1 = time.time() # try: path=a_star(graph, start, dest, True)#calculate path print("Path is",path, "\n\n") except: print("ERROR !!CHECK THE NAME OF THE INTRODUCED CITIES") friendMeetCity(path) t2 = time.time() print(t2 - t1)
""" Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. Note that 1 is typically treated as an ugly number. """ def is_ugly_number(number): """ Returns True if the number is an ugly number. :param number: the number :return: True or False """ if number <= 0: return False if number == 1: return True primes = {2, 3, 5} # keep dividing until it reaches 1 or some other number while dividable_by_primes(number, primes): for prime in primes: if number % prime == 0: number /= prime return number == 1 def dividable_by_primes(number, primes): """ Returns True if number is dividable by at least one of numbers in the list of `primes` """ return any(number % prime == 0 for prime in primes)
import cv2 import numpy as np #ๅˆ†็ฆปๅ›พๅƒ img = cv2.imread('img\\test.jpg') #b = np.zeros((img.shape[0], img.shape[1]), dtype = img.dtype) #g = np.zeros((img.shape[0], img.shape[1]), dtype = img.dtype) #r = np.zeros((img.shape[0], img.shape[1]), dtype = img.dtype) #b[:, :] = img[:, :, 0] #g[:, :] = img[:, :, 1] #r[:, :] = img[:, :, 2] b = cv2.split(img)[0] g = cv2.split(img)[1] r = cv2.split(img)[2] merged = cv2.merge([b, g, r]) print("Merge by OpenCV") print(merged.strides) mergedByNp = np.dstack([b, g, r]) print("Merge by NumPy ") print(mergedByNp.strides) #NumPyๆ•ฐ็ป„็š„stridesๅฑžๆ€ง่กจ็คบ็š„ๆ˜ฏๅœจๆฏไธช็ปดๆ•ฐไธŠไปฅๅญ—่Š‚่ฎก็ฎ—็š„ๆญฅ้•ฟใ€‚ cv2.imshow("Blue", b) cv2.imshow("Red", g) cv2.imshow("Green", r) cv2.imshow("img", img) #cv2.imshow("merged", merged) #cv2.imshow("mergedByNp", mergedByNp) cv2.waitKey(0) cv2.destroyAllWindows()
user = int(input("How many users do you want to insert? ")) aruser = [] for i in range (user) : aruser.append(input("Insert user " + str(i + 1) + " ")) for i in range (aruser.__len__()): print("The user 1, is: " + aruser[i])
main_str = input("ะ’ะฒะตะดะธั‚ะต ะฝะตัะบะพะปัŒะบะพ ัะปะพะฒ ั‡ะตั€ะตะท ะฟั€ะพะฑะตะป") s = main_str.split(" ") print(s) for ind, el in enumerate(s, 1): if len(el) > 10: string = list(el) i = 10 while i < len(string): string.pop(i) el = ("".join(string)) print(ind, el)
n = float(input()) notas=[100, 50, 20, 10, 5, 2] moedas=[1.00, 0.50, 0.25, 0.10, 0.05, 0.01 ] print("NOTAS:") for i in notas: num = n//i n -= num*i print("{:.0f} nota(s) de R$ {:.2f}".format(num,i)) print("MOEDAS:") for i in moedas: num = n//i n -= num*i print("{:.0f} moeda(s) de R$ {:.2f}".format(num,i)) print("\n")
def hyp(leg1,leg2): c = ((leg1**2)+(leg2**2))**.5 print(c) def mean(a,b,c): d=(a+b+c)/3.0 print(d) def perimeter(base,height): a = (base*2)+(height*2) print(a) hyp(1,12) mean(1,2,3) perimeter(1,1)
#Problem Nr.3 #http://www.practicepython.org print("Problem 3") a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [] print(a) number = int(input("Type in a number..\nthe program will display you all numbers that are less than\nyour typed-in number in the list ")) print(a) for i in a: if i < number: b.append(i) print(b)
# ะ ะฐัั‡ะตั‚ ะฝะฐ ะบะฐะบะพะน ะดะตะฝัŒ ะฑัƒะดะตั‚ ะดะพัั‚ะธะณะฝัƒั‚ะฐ ั†ะตะปัŒ a = 5 b= 10 day= 1 while a <= b: print("in ", day, "day runing", a , "km") a = round(a *1.1,2) day +=1
""" Estudiante: Naranjo Sthory Alexanyer Naranjo Cรฉdula de identidad: V - 26.498.600 Asignatura: Cรกlculo Cientรญfico (6105) Tarea 0: Introducciรณn al Cรกlculo Cientรญfico Ejercico 1.6 """ def methodOne(): print('\t*** METHOD #1 ***\n') a = 0 b = 1 n = 100000 h = b/n x = a for i in range(1,n+1): x = x+h print(f'* Value of x using the method one: {x}') def methodTwo(): print('\n\t*** METHOD #2 ***\n') a = 0 b = 1 n = 100000 h = b/n for i in range(n+1): x = a + i*h print(f'* Value of x using the method two: {x}') # Difference between them methodOne() methodTwo() """ Observaciones: (a) Se considera como mejor el segundo mรฉtodo dado a que hay muy poco margen de error, ya que solo tenemos que hacer el cรกlculo dos (2) veces, primero el calculo de la multiplicaciรณn y luego el correspondiente de la suma. Considerando que la suma se realiza en cada iteracciรณn por N veces. """
n = int(input()) def isPerfect(num): total = 0 for i in range(1, num+1): if num % i == 0: total += i print(total) b = 'True' if num == total/2 else 'False' return b print(isPerfect(n))
def sockMerchant(n, ar): # n = 9, ar = list # sort --> 10 10 10 10 20 20 20 30 50 # inx 0 1 2 3 4 5 6 7 8 # cnt = pair of socks # tmp = list[0] tmp = ar[0] cnt = 0 i = 1 while i<n: try: if tmp == ar[i]: cnt += 1 tmp = ar[i+1] i += 2 else: tmp = ar[i] i += 1 except IndexError: i += 1 return cnt if __name__ == '__main__': n = int(input()) ar = list(map(int, input().rstrip().split())) ar.sort() result = sockMerchant(n, ar) print(result)
# 73 ์˜ ๋‹ค์Œ 5์˜ ๋ฐฐ์ˆ˜ ๊ตฌํ•˜๊ธฐ # 5์˜ ๋ฐฐ์ˆ˜ - 73 < 3 # 73 67 38 33 def finalScore(arr): mul_five = [] for i in arr: i += 5 - (i % 5) mul_five.append(i) return mul_five if __name__ == '__main__': n = int(input()) grades = [] for _ in range(n): score = int(input()) grades.append(score) result = finalScore(grades) print(result)
def review(s): # h a c k e r odd = [] even = [] for i, c in enumerate(s): if i % 2 == 0: #์ง์ˆ˜ odd.append(s[i]) else: even.append(s[i]) return ''.join(odd) + ' '+ ''.join(even) if __name__ == '__main__': n = int(input()) for i in range(n): s = input() result = review(s) print(result)
# 8 # UDDDUDUU def countingValleys(n, s): depth = 0 cnt = 0 for i in range(n): #index๊ฐ€ ํ•„์š” if s[i] == 'D': cnt -= 1 else: cnt += 1 if cnt == 0 and s[i] == 'U': depth += 1 return depth if __name__ == '__main__': n = int(input()) s = input() result = countingValleys(n, s) print(result)
def compare(a, b): aWin = 0 bWin = 0 for i in range(len(a)): if a[i] > b[i]: aWin += 1 elif a[i] == b[i]: pass elif a[i] < b[i]: bWin += 1 return [aWin, bWin] if __name__ == '__main__': a = list(map(int, input().rstrip().split())) b = list(map(int, input().rstrip().split())) result = compare(a, b) print(result)
#x=10, y=85, d=30 # return 3 import math def solution(X, Y, D): return int(math.ceil((Y-X) / D)) if __name__ == '__main__': res = solution(10, 85, 30) print(res)
def IsPrimeNum(d): if d ==1: return False elif d ==2 : return True import math sq = int(math.sqrt(d)) print(sq) for i in range(2, sq+1): if d % i == 0: return False return True if __name__ == '__main__': T = int(input()) for _ in range(T): d = int(input()) res = "Prime" if (IsPrimeNum(d)) else "Not prime" print(res)
def binary_search(arr, target): low = 0 high = len(arr) -1 while low <=high: mid = int((low + high)/2) guess = arr[mid] if guess == target: return mid elif target < guess: high = mid-1 else: low = mid +1 return None if __name__ == '__main__': arr = [1,3,5,7,9] res = binary_search(arr, 7) print(res)
from collections import deque graph = {} graph['CAB'] = ['CAR', 'CAT'] graph['CAR'] = ['BAR', 'CAT'] graph['BAR'] = ['BAT'] graph['CAT'] = ['BAT', 'MAT'] graph['MAT'] = ['BAT'] graph['BAT'] = [] def search(start): search_queue = deque() search_queue += graph['CAB'] visited = ['CAB'] while search_queue: node = search_queue.popleft() if not node in visited: if node == 'BAT': visited.append(node) return visited else: search_queue += graph[node] visited.append(node) return visited # return False if __name__ == '__main__': res = search('CAB') print(res)
""" Dijkstra is a Shortest Path First (SPF) algorithm that iterates through every node in a graph, storing where its been and the weight for each connection. It retrieves useful information about the shortest path by linking a node to its minimum weight predecessor. So it becomes possible to calculate the shortest path from node X to node Y. """ #First we create a template graph to test our algorithm. graph = {'a':{'b':10,'c':3},'b':{'c':1,'d':2}, 'c':{'b':4,'d':8,'e':2},'d':{'e':7},'e':{'d':9}} #Then we define the dijkstra function that receives the graph, #a start and an end position (or node). def dijkstra(graph,start,end): #We are storing the shortest distance in a separate dictionary shortest_distance = {} #And each nodes' predecessor in a separate dictionary predecessor = {} #Stacking the unseen nodes in the graph unseenNodes = graph #Setting an infinity value for unvisited nodes infinity = float('inf') #And creating a list for the resulting shortest path. path = [] #Setting the value of unseen nodes to infinity. #Any visited node will have a value lesser than unvisited nodes. for node in unseenNodes: shortest_distance[node] = infinity #print(node) #Dijkstra always starts at a position, so the start position weight must be 0. shortest_distance[start] = 0 #Creating a loop for every unseen node. while unseenNodes: #We do not know what node has a minimal value yet, so we set it to none. minNode = None for node in unseenNodes: if minNode is None: minNode = node #Now we visited the node and we know its weight. elif shortest_distance[node] < shortest_distance[minNode]: minNode = node #If our new node has a lesser value than our previous one, we have a new #minimal node. for childNode, weight in graph[minNode].items(): if weight + shortest_distance[minNode] < shortest_distance[childNode]: shortest_distance[childNode] = weight + shortest_distance[minNode] predecessor[childNode] = minNode #print(predecessor) #And then we remove the minNode from the stack. unseenNodes.pop(minNode) #Now we're finished with visiting nodes. #We will start retrieving our path from our end-point to the start-point. #We need to do this backwards because we will traverse through the predecessors #with lessr weights. currentNode = end while currentNode != start: try: path.insert(0,currentNode) currentNode = predecessor[currentNode] #If impossible to traverse the nodes, we raise an error. except KeyError: print('Path not reachable') break #Do not forget to include a start node to your path. path.insert(0,start) if shortest_distance[end] != infinity: print('Shortest distance is {}'.format(str(shortest_distance[end]))) print('And the path is {}'.format(str(path))) dijkstra(graph, 'a', 'b')
# Elena Voinu def raise_to_power(base_val, exponent_val): if exponent_val == 0: result_val = 1 else: result_val = base_val * raise_to_power(base_val, exponent_val-1) return result_val user_base = 4 user_exponent = 2 print('%d^%d = %d' % (user_base, user_exponent,raise_to_power(user_base, user_exponent)))
# Elena Voinu male_names = { 'Oliver', 'Declan', 'Henry' } # Remove 'Oliver' from the set, and add 'Atlas'. ''' Your solution goes here ''' male_names.remove('Oliver') # added print statement just to check that the right names are printed print("Oliver removed from na,es set:", male_names) male_names.add('Atlas') print("Atlas added to names set:", male_names)
#Write an expression using Boolean operators that prints "Eligible" #if user_age is greater than 17 and not equal to 25. #Ex: 17 prints "Ineligible", 18 prints "Eligible". user_age = 17 #''' Your solution goes here ''' if (user_age > 17) and (user_age != 25): print('Eligible') else: print('Ineligible')
#Elena Voinu #Create a conditional expression that evaluates to string "negative" if user_val is less than 0, #and "non-negative" otherwise. Example output when user_val is -9 #sample program: -9 is negative user_val = -9 #''' Your solution goes here ''' cond_str = "negative" if user_val < 0 else "non-negative" print(user_val, 'is', cond_str)
#Define a function pyramid_volume with parameters base_length, base_width, #and pyramid_height, that returns the volume of a pyramid with a rectangular base. #Relevant geometry equations: #Volume = base area x height x 1/3 #Base area = base length x base width. #''' Your solution goes here ''' def pyramid_volume(base_length, base_width, pyramid_height): pyramid_volume = base_length * base_width* pyramid_height * (1 / 3) return pyramid_volume print('Volume for 4.5, 2.1, 3.0 is:', pyramid_volume(4.5, 2.1, 3.0))
# Elena Voinu '''function number_of_pennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: 5 dollars and 6 pennies returns 506. ''' ''' Your solution goes here ''' def number_of_pennies(dollar=0,pennies=0): #declare variable total is 0 total_pennies = 0 #compute total pennies total_pennies=100*dollar+pennies return total_pennies print(number_of_pennies(5, 6)) # Should print 506 print(number_of_pennies(4)) # Should print 400
class Node: def __init__(self, init_data): # the data stored in the node self.data = init_data # the pointer to the next item in the list self.next = None """none is a null value. we assume that they don't point to anything yet (just creating nodes) if it doesn't point to anything - we know it's not in a list, or it's at the end""" self.prev = None def get_data(self): return self.data def get_next(self) -> object: return self.next def get_prev(self): return self.prev def set_data(self, new_data): self.data = new_data def set_next(self, next_node): self.next = next_node def set_prev(self, prev_node): self.prev = prev_node def main(): node1 = Node(23) # node1.set_data(2) print("node 1 data: {0}".format(node1.get_data())) node2 = Node(52) # node2.set_data(3) node3 = Node(89) print("node 3 data: {0}".format(node3.get_next())) current = node1 print("current data {0}".format(current.get_data())) node1.set_next(node2) print(node1.get_next()) # count nodes main()
""" Fibonacci Sequence """ import functools import unittest def memoise(function): function.cache = dict() @functools.wraps(function) def _memoise(*args): if args not in function.cache: function.cache[args] = function(*args) return function.cache[args] return _memoise @memoise def fibonacci(nterms: int) -> int: """ Returns the fibonacci number for nth term :param nterms: The n-th term till which fibonacci number would be computed :return: The Fibonacci number """ return nterms if nterms < 2 else fibonacci(nterms - 1) + fibonacci(nterms - 2) class TestFibonacci(unittest.TestCase): def testFibonacci(self): self.assertEqual(8, fibonacci(6)) def testFibonacciLarge(self): self.assertEqual(12586269025, fibonacci(50)) if __name__ == '__main__': unittest.main()
print("Digite uma sequencia de valores terminada por zero: ") produto = 1 valor = 1 while valor !=0: valor = int(input("Digite um valor a ser multiplicado: ")) produto = produto * valor print("A produto dos valores digitados eh: ", produto)
#!/usr/bin/env python3 # This is a timer. # It accepts args time in hh:mm:ss # and length in integer # and action (bash command) # and it prints time left and nice graphic representation of remainder. # Depending on command line arguments it executes a specified command upon # reaching the end of time. import os import getopt import sys import time as TIME # Command line arguments. args = sys.argv[1:] # Ignore script filename. optlist = getopt.getopt(args, 't:l:a:h', ['time=', 'length=', 'action=, help'])[0] help_string = """ Usage: timer [OPTIONS] Displays a countdown timer and executes a command when timer runs out. Arguments: -h, --help Prints this help message. -t, --time= Accepts time in format 'hh:mm:ss'. Sets timer to that time. Default is 25min. -a, --action= Command that will be executed when timer runs out. -l, --length= Length of grafical representation of time left. """ time = '00:25:00' length = 15 action = '' for optarg in optlist: if optarg[0] == '-t' or optarg[0] == '--time': if len(optarg[1]) == 8: # Careful because there is no input sanitation. time = optarg[1] elif optarg[0] == '-l' or optarg[0] == '--length': length = int(optarg[1]) elif optarg[0] == '-a' or optarg[0] == '--action': action = optarg[1] elif optarg[0] == '-h' or optarg[0] == '--help': print(help_string) exit() # Force exit. time_h = int(time[:2]) time_m = int(time[3:5]) time_s = int(time[-2:]) total_seconds = time_s + time_m * 60 + time_h * 3600 for remaining_seconds in range(total_seconds, -1, -1): factor = remaining_seconds / total_seconds special_string = int(length * factor) * '#' + int(length * (1 - factor)) * '-' while len(special_string) < length: special_string += '-' rem_h = remaining_seconds // 3600 rem_m = (remaining_seconds - rem_h * 3600) // 60 rem_s = remaining_seconds % 60 print('{} {:0>2}:{:0>2}:{:0>2}'.format(special_string, rem_h, rem_m, rem_s), end='\r') TIME.sleep(1) os.system(action)
# string # initialization a = 'hello' print(len(a), type(a)) # element indexing d = a[-6] print(d, type(d)) # slicing : substring from string data h = 'hello world' d = h[-3::1] print(d, type(d)) # type cast with string # number k = int('1010',8) print(k, type(k)) k = float('2.4') print(k, type(k)) # list st = '[2, 43, 4]' lst = list(st) print(lst, type(lst)) lst2 = eval(st) print(lst2, type(lst2)) hello = 10 k = eval('hello') print(k, type(k)) # list from from user lst = eval(input('enter the list ')) print(lst) # method # split k = '213 43 443 23 23 212' out = k.split() print(out, type(out)) # capitalize() k = '2hello world' out = k.capitalize() print(out) # upper k = '2hello world' out = k.upper() print(out) # output 2HELLO WORLD # lower k = '2Hello world' out = k.lower() print(out) # output 2hello world # center k = 'hello6' out = k.center(11, '*') print(out) # output hello***** # rjust k = 'hello' out = k.rjust(10, '*') print(out) # rjust k = 'hello' out = k.ljust(10, '*') print(out) # zfill k = '-12232' out = k.zfill(10) print(out) # output -000012232 # encode k = 'helloฯช' out = k.encode('utf', errors='replace') print(out, type(out)) out2 = out.decode('utf') print(out2, type(out2)) # maketrans, translate k = 'hello world' intab = 'abcdef' outab = '123456' trans = str.maketrans(intab, outab) out = k.translate(trans) print(out) # list # list creation a = [] # list format a = list() # using constructor print(a) # [] # init a list with single object a1 = [10] a2 = ['hello'] a3 = [[3,4]] # accessing the elements # 1. indexing : value at given position k = [2, 43, 'hello', 1+3J] d = k[-1] print(d, type(d)) # (1+3j) <class 'complex'> # 2. slicing: values at given range k = [2, 43, 'hello', 1+3J] d = k[10:1:-1] print(d, type(d)) # other operation # membership operator ls = [2, 4, 5] i = 3 out = i in ls print(out) # False out = i not in ls print(out) # True # concat l1 = [2, 5] l2 = [3] l = l1 + l2 print(id(l)) l += [10, 11] print(id(l)) print(l, type(l)) # [2, 5, 3, 8] <class 'list'> # multiplication ls = [2, 5] out = ls*2 print(out) # methods in list ip = '32 454 8 6' dp = ip.split() gen = map(int, dp) k = list(gen) # space separated elements def apnafun(u): return u-1 lst = [2, 4, 6, 9] gen = list(map(apnafun, lst)) print(gen) out = [i-1 for i in lst] for i in range(10): print(i, end='*\n*') a = 10 b = 20 c = a + b k = [20, 4, 7] print(a,"B ", sep='*') k = 0b1010 print(k)
def txt_to_string_arr(file_path): """ txt_to_string_arr :param file_path: ํŒŒ์ผ ์ฃผ์†Œ string ์ž„ :return: (1D-array) string ๋ฐฐ์—ด """ f = open(file_path, 'r') ret = [] while True: line = f.readline() if not line: break ret.append(line) f.close() return ret def str_arr_to_ascii_binary_arr(string_array): """ str_arr_to_ascii_binary_arr ์ฃผ์–ด์ง„ string ๋ฐฐ์—ด์„ ๋ฌธ์ž ๋‹จ์œ„๋กœ ์ ‘๊ทผํ•ด์„œ ๋ฐ”์ด๋„ˆ๋ฆฌ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค. ๋‚ด์žฅํ•จ์ˆ˜ ord ๋Š” ์ฃผ์–ด์ง„ ๋ฌธ์ž์˜ ์•„์Šคํ‚ค์ฝ”๋“œ ๊ฐ’์„ ๋ฆฌํ„ดํ•œ๋‹ค. ๋‚ด์žฅํ•จ์ˆ˜ bin ์€ ์ฃผ์–ด์ง„ ๊ฐ’์˜ ๋ฐ”์ด๋„ˆ๋ฆฌ ํ‘œํ˜„์„ ๋ฆฌํ„ดํ•œ๋‹ค. ์ด๋•Œ ์ ‘๋‘์‚ฌ๋กœ '0b'๊ฐ€ ๋ถ™์œผ๋ฉฐ, ํ‘œํ˜„ ์ž๋ฆฟ์ˆ˜๊ฐ€ ๊ณ ์ •๋˜์ง€ ์•Š๋Š”๋‹ค. ๋”ฐ๋ผ์„œ ์™ผ์ชฝ์— 0์„ ํ•„์š”ํ•œ๋งŒํผ ์ถ”๊ฐ€ํ•ด์„œ 8๋น„ํŠธ ํ‘œํ˜„์œผ๋กœ ๋งŒ๋“ ๋‹ค. :param string_array: string ๋ฐฐ์—ด :return: (1D-array) string ๋ฐฐ์—ด """ ret = [] for line in string_array: binary_line = "" for char in line: char_to_binary = bin(ord(char))[2:].zfill(8) binary_line += char_to_binary ret.append(binary_line) return ret def concat_binary_arr_with_zero_fill(binary_array): """ concat_binary_arr_with_zero_fill ์ฃผ์–ด์ง„ ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ฐฐ์—ด์„ ํ•˜๋‚˜์˜ string ์œผ๋กœ ํ•ฉ์นœ๋‹ค. ์ด๋•Œ, ๊ธธ์ด๊ฐ€ 3์˜ ๋ฐฐ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด, ํ•„์š”ํ•œ ๋งŒํผ 0์„ ๋ถ™์ธ๋‹ค. :param binary_array: string ๋ฐฐ์—ด :return: (string) string """ ret = "" for line in binary_array: ret += line while len(ret) % 3 != 0: ret += '0' return ret def convert_raw_to_base64(raw_data): """ convert_raw_to_base64 ์ฃผ์–ด์ง„ ๋ฐ”์ด๋„ˆ๋ฆฌ string ์„ base64 string ์œผ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค. ์ธ์ž๋กœ ์ „๋‹ฌ๋ฐ›๋Š” string ์˜ ๊ธธ์ด๊ฐ€ 3์˜ ๋ฐฐ์ˆ˜์ž„์ด ๋ณด์žฅ๋œ๋‹ค. ๋”ฐ๋ผ์„œ 6๊ฐœ ๋ฌธ์ž์”ฉ ์•ž์—์„œ๋ถ€ํ„ฐ ์ž˜๋ผ๋‚ด๊ณ , ๊ทธ ๊ฐ’์„ ์ •์ˆ˜๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค์Œ, base64 ๋ฌธ์ž ํ‘œ์—์„œ ์ฐพ์œผ๋ฉด ๋œ๋‹ค. :param raw_data: ๋ฐ”์ด๋„ˆ๋ฆฌ๋กœ ํ‘œํ˜„ ๋ฌธ์ž์—ด :return: (string) string """ # ์ฝ”๋“œ๋ถ์— ๋Œ€ํ•œ ๋‚ด์šฉ์€ base64_codebook ํŒŒ์ผ ์ฐธ๊ณ  from base64_codebook import base64_dictionary base64_table = list(base64_dictionary) ret = "" while len(raw_data) > 0: snip = raw_data[:6] raw_data = raw_data[6:] idx = int(snip, 2) ret += base64_table[idx] return ret def save_string_to_txt(string, path): """ save_string_to_txt :param string: ์ €์žฅํ•˜๋ ค๋Š” string :param path: ์ €์žฅํ•  ๊ฒฝ๋กœ :return: None """ f = open(path, 'w') f.write(string) f.close() return def decode_base64(string): """ decode_base64 base64 ํ‘œํ˜„ ๋ฌธ์ž์—ด์„ ๋””์ฝ”๋”ฉํ•œ๋‹ค. ์ฃผ์–ด์ง„ string ์„ ๋ฌธ์ž๋‹จ์œ„๋กœ ์ ‘๊ทผํ•ด์„œ 6์ž๋ฆฌ ๋ฐ”์ด๋„ˆ๋ฆฌ ํ‘œํ˜„์œผ๋กœ ๋ฐ”๊พผ๋‹ค. ์ด๋Ÿฐ์‹์œผ๋กœ ๋ชจ๋“  ๋‚ด์šฉ์„ ๋ณ€ํ™˜ํ•ด์„œ binary_exp ๋ฅผ ๋งŒ๋“ ๋‹ค. ์ด๋•Œ ์ฃผ์˜ํ•  ์ ์€, ํ•ด๋‹น ๋ฌธ์ž๋ฅผ ๊ณง์žฅ ์•„์Šคํ‚ค ๋ฐ”์ด๋„ˆ๋ฆฌ ํ‘œํ˜„์œผ๋กœ ๋ฐ”๊พธ๋ฉด ์•ˆ๋œ๋‹ค. ๊ฐ€๋ น base64 string ์— ๋“ฑ์žฅํ•˜๋Š” 'A'๋Š” 0b000000 ์œผ๋กœ ํ‘œํ˜„๋˜์–ด์•ผํ•œ๋‹ค. ๋ณ€ํ™˜ ๊ณผ์ •์—์„œ ์•ฝ๊ฐ„์˜ ๋””ํ…Œ์ผ๋งŒ ๋‹ค๋ฅผ๋ฟ, ์ธ์ฝ”๋”ฉ๊ณผ ๋””์ฝ”๋”ฉ์„ ์‚ฌ์‹ค์ƒ ๋™์ผํ•˜๋‹ค. :param string: ๋””์ฝ”๋”ฉ ํ•  string :return: (string) ๋””์ฝ”๋”ฉ ๋œ string """ # ์ฝ”๋“œ๋ถ์— ๋Œ€ํ•œ ๋‚ด์šฉ์€ base64_codebook ํŒŒ์ผ ์ฐธ๊ณ  from base64_codebook import base64_dictionary binary_exp = "" for char in string: val = base64_dictionary[char] binary_exp += bin(val)[2:].zfill(6) ret = "" while len(binary_exp) >= 8: snip = binary_exp[:8] binary_exp = binary_exp[8:] ret += chr(int(snip, 2)) return ret def main(): """ Main ๋ฉ”์ธ ํ•จ์ˆ˜๋Š” Base64 ์ธ์ฝ”๋”ฉ์˜ ๋ชจ๋“  ๊ณผ์ •์„ ์‹คํ–‰ํ•˜๋Š” ์—ญํ• ์„ ํ•œ๋‹ค. C ์–ธ์–ด์˜ ๊ตฌ์กฐ์ฒ˜๋Ÿผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ๋„์ž…ํ–ˆ์Œ. :return: None """ # input.txt ํŒŒ์ผ์„ ์ฝ์–ด์„œ string ๋ฐฐ์—ด๋กœ ์ž์žฅํ•จ str_array = txt_to_string_arr('data/input.txt') # string ๋ฐฐ์—ด์„ binary ํ‘œํ˜„ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•จ binary_array = str_arr_to_ascii_binary_arr(str_array) # binary ๋ฐฐ์—ด์„ ํ•˜๋‚˜์˜ string ๋กœ ํ•ฉ์นจ. # ๊ธธ์ด๊ฐ€ 3์˜ ๋ฐฐ์ˆ˜๊ฐ€ ๋˜๊ฒŒ ๋’ค์— 0์„ ์ถ”๊ฐ€ํ•จ raw_binary_data = concat_binary_arr_with_zero_fill(binary_array) # binary string ์„ base64 ์ธ์ฝ”๋”ฉํ•จ base64_result = convert_raw_to_base64(raw_binary_data) # ๊ฒฐ๊ณผ ์ถœ๋ ฅ print(base64_result) # ๊ฒฐ๊ณผ ์ €์žฅ save_string_to_txt(base64_result, 'data/output.txt') # base64๋ฅผ ๋””์ฝ”๋”ฉํ•˜๊ธฐ decoded_string = decode_base64(base64_result) # ๋””์ฝ”๋”ฉ ๊ฒฐ๊ณผ ์ถœ๋ ฅ ๋ฐ ์ €์žฅ print(decoded_string) save_string_to_txt(decoded_string, 'data/decoded.txt') if __name__ == '__main__': main()
# ๅƒ็จ‹ๅผ่จญ่จˆๅธซ้€™ๆจฃๆ€่€ƒ # Chapter 2 ๅ•้กŒ:Luhn Checksum ็ฌฌไบ”้ƒจๅˆ† positive or negative positive = 0 negative = 0 for i in range(1, 11): digit = int(input('ENTER the ' + str(i) + ' numbers:')) if (digit > 0): positive = positive + 1 else: negative = negative + 1 response = input('Do you want the (p)ositive or (n)egative count? : ') if (response == 'p'): print('There are ' + str(positive) + ' positive number(s)') if (response == 'n'): print('There are ' + str(negative) + ' negative number(s)')
import os from read_input import read_input_as_string def part_one(): abs_file_path = os.path.join(os.path.dirname(__file__), "input") input_data = read_input_as_string(abs_file_path) height_map = [[int(height) for height in line] for line in input_data] low_points = [] for y in range(0, len(height_map)): for x in range(0, len(height_map[y])): current_val = height_map[y][x] if ( is_lower_location(x, y, x, y - 1, height_map) and is_lower_location(x, y, x, y + 1, height_map) and is_lower_location(x, y, x + 1, y, height_map) and is_lower_location(x, y, x - 1, y, height_map) ): low_points.append(current_val) else: pass risk_level_total = sum(low_points) + len(low_points) print(f"Total risk level: {risk_level_total}") def is_lower_location(x, y, unsafe_x, unsafe_y, height_map): return ( (not (0 <= unsafe_y < len(height_map) and 0 <= unsafe_x < len(height_map[unsafe_y]))) or (height_map[y][x] < height_map[unsafe_y][unsafe_x]) ) # Press the green button in the gutter to run the script. if __name__ == '__main__': part_one()
def sanitize_ns(string): new_string = '' sanitized = False numbers = [str(num) for num in range(0, 10)] for char in string: if char not in numbers: sanitized = True continue new_string += char return [new_string, sanitized]
""" This TSP Problem implements local search algorihtm to find solution, through using AIMA-Python. Taek Soo Nam(tn32) 23rd Feb 2019 """ from tools.aima.search import Problem, hill_climbing, simulated_annealing, exp_schedule import random class TSP(Problem): def __init__(self, initial, distances, num_cities): self.initial = initial self.distances = distances self.num_cities = num_cities def actions(self, state): swap = [] for i in range (5): pairs = [random.sample(range(1, len(state) -1), 2)] swap.append (pairs) return swap def result(self, state, move): new_state = state[:] pairs1 = state[move[0][0]] pairs2 = state[move[0][1]] new_state[move[0][0]] = pairs1 new_state[move[0][1]] = pairs2 return new_state def value(self, state): distance = 0 for i in range(len(state) - 1): lst = [state[i], state[i+1]] lst.sort() distance += self.distances[tuple(lst)] return -1 * distance """ State: A complete city circuit, e.g., [0, 1, 2, 3, 0] (note that this starts and stops in the same, constant city) Distances: A dictionary city-pair-distances, e.g., {(1,2): 1.5, (2,3): 2.3, ...} actions(state) returns a list of pairs of cities to swap in the current state, e.g., [[1,2], [3,5], ...] result(state, action) returns the new state resulting from applying the given action to the given state. This must be a pure function. value(state) returns the sum of the distances between the cites in the given state, negated in order to reflect value. """ if __name__ == '__main__': num_cities = 5 path = ['1', '2', '3', '4', '5', '6', '1'] distances = {('1','2'): 1, ('1','3'): 2, ('1','4'): 3, ('1','5'): 4, ('1','6'): 5, ('2','3'): 1, ('2','4'): 2, ('2','5'): 3, ('2','6'): 4, ('3','4'): 1, ('3','5'): 2, ('3','6'): 3, ('4','5'): 1, ('4','6'): 2, ('5','6'): 1} print('Start: ' + str(path)) p = TSP(initial=path, distances=distances, num_cities=num_cities) print('Value: ' + str(p.value(path))) #hill_climbing solution hill_solution = hill_climbing(p) print('Hill-climbing:') print('\tSolution: ' + str(hill_solution)) print('\tValue: ' + str(p.value(hill_solution))) #simulated annealing solution annealing_solution = simulated_annealing(p, exp_schedule(k=20, lam=0.005, limit=10000) ) print('Simulated annealing:') print('\tSolution: ' + str(annealing_solution)) print('\tValue: ' + str(p.value(annealing_solution)))
from graphics import * def grid(win, nx, ny, w, h): ox = 10 oy = 10 total_height = oy + h * ny total_width = ox + w * nx for i in range(nx + 1): x = ox + i * w l = Line(Point(x, oy), Point(x, total_height)) l.setOutline('black') l.draw(win) for i in range(ny + 1): y = oy + i * h l = Line(Point(ox, y), Point(total_width, y)) l.setOutline('black') l.draw(win) for i in range(nx): for j in range(ny): x = ox + i * w + w/2 y = oy + j * h + h/2 c = Circle(Point(x,y), min(w,h) / 2 - 4) c.setOutline('black') c.setFill('red') c.draw(win) def main(): win = GraphWin("My Window", 500, 500) win.setBackground('pink') grid(win, 10, 10, 40, 40) win.getMouse() win.close() main()
# @Author: Antero Maripuu Github:<machinelearningxl> # @Date : 2019-05-17 13:46 # @Email: antero.maripuu@gmail.com # @Project: Coursera # @Filename : Exercise_1_Housing_Prices.py #In this exercise you'll try to build a neural network that predicts the price of a house according to a simple formula. #So, imagine if house pricing was as easy as a house costs 50k + 50k per bedroom, so that a 1 bedroom house costs 100k, # a 2 bedroom house costs 150k etc. #How would you create a neural network that learns this relationship so that it would predict a 7 bedroom house as costing close to 400k etc. #Hint: Your network might work better if you scale the house price down. You don't have to give the answer 400...it # might be better to create something that predicts the number 4, and then your answer is in the 'hundreds of thousands' etc. import tensorflow as tf import numpy as np from tensorflow import keras model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss='mean_squared_error') xs = np.array([1, 2, 3, 4, 5, 6], dtype=int) ys = np.array([100, 150, 200, 250, 300, 350], dtype=float) model.fit(xs, ys, epochs=900) print(model.predict([7])) ##
# ๅผ‚ๅธธ exception # ไฝฟ็”จtry .. except ๅค„็†ๅผ‚ๅธธ # the statements between the try and excep is executed # if no exception occurs , the except clause is skipped # and execuation of the try statment is finished try: text = input('Enter something-->') # Press ctrl + d except EOFError: print('Why did you do an EOF on me ?') # Press ctrl + c except KeyboardInterrupt: print('You cancelled the opreation.') else: print('You entered {}'.format(text)) # ๆŠ›ๅ‡บๅผ‚ๅธธ raise # the raise statement allows the programmer to force # a specified exception to ocurr # ๅผ•ๅ‘็š„้”™่ฏฏๆˆ–ๅผ‚ๅธธ็›ดๆŽฅๆˆ–้—ดๆŽฅๅฑžไบŽException็ฑป็š„ๆดพ็”Ÿ็ฑปsubclass class ShortInputException(Exception): def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: text = input('Enter something -->') if len(text) < 3: raise ShortInputException(len(text), 3) except EOFError: print('Why did you do an EOF on me?') except ShortInputException as ex: print( 'ShortInputException: The input was' + '{0} long, excepted at least {1}' .format(ex.length, ex.atleast)) else: print('No exception was raised') # try ... finally # ็จ‹ๅบๅœจ้€€ๅ‡บไน‹ๅ‰๏ผŒfinallyๅญๅฅๆ€ปไผš่ฟ่กŒ import sys import time f = none try: f = open(poem.text) while True: line = f.readline() if(len(line) == 0): break print(line, end = ' ') sys.stdout.flush() print('Press ctrl + c now') time.sleep(2) # 2็ง’ไผ‘็œ  except IOError: print('Could not find file poem.text') except KeyboardInterrupt: print('You cancellded the reading from the file.') finally: if f: f.close() print('Cleaning up: Closed the file') # with ่ฏญๅฅ with open('poem.text') as f: for line in f: print(line, end = ' ')
#!/usr/bin/env python3 # Import modules from the standard Python library import re # Import the regex module, this is for something later on # Import user defined modules import utilities # Setup our data and get some translation tables header, sequence, seq50 = utilities.setup() nucleotide_table, protein_dictionary = utilities.make_trans() # We have a fasta file containing a region of chromosome 10 of Zea mays # There are several things that this code will do once complete print("The first 50 nucleotides of this FASTA sequence are:") print(seq50) print("\n") # First, the sequence is in lowercase; convert the sequence to all uppercase and print off the first 50 nucleotides # Use the upper method of the string `sequence' to do this; store this as the variable sequence # Remember: Python starts counting at 0 and slices are partially inclusive # Use the upper method to change the sequence in to uppercase print("The first 50 nucleotides in upper case are:") # Print the first 50 nucleotides of the sequence in uppercase print("\n") # Second, is to get the length of the sequence using the `len()' function print("The length of the sequence is:") # Print the length of the sequence print("\n") # Third, we're going to get GC content of the sequence # Do this using a for loop and an if statement GC = 0 # A variable to hold the number of 'G's and 'C's we find in our sequence # Use a for loop and an if statement to find the number of 'G's and 'C's in our sequence # Calculate the percent of all nucleotides that are 'G' or 'C' # Remember, `GC' is an integer type, we can do division using the '/' operator GC_content = # Store the GC content here print("The GC content of this sequence is: " + str(round(GC_content, 1))) print("\n") # Fourth, convert this DNA sequence into it's complementary RNA sequence and print the last 50 nucleotides # Use the translate *method* of the string `sequence' to conver from DNA nucleotides to RNA nucleotides # The translate method takes one argument, a translation table # The translation table has been made for you, it's called `nucleotide_table' # Remember to reverse the sequence, otherwise your RNA sequence will be backwards # Hint: use a slice to reverse the sequence # Use the translate method of the string `sequence' to convert your DNA sequence into RNA, don't forget to reverse the sequence to get the complementary sequence! print("The last 50 nucleotides of the RNA sequence are:") # Print the last 50 nucleotides of the RNA sequence print("We're now checking if this is correct...") utilities.check_RNA(RNA_sequence) # We're checking your work... print("\n") # Finally, write a function to translate an RNA sequence into a protein sequence # We recommend solving this problem in YY steps: # First, figure out where the start codon occurs in the RNA sequence # Do this using the find method of strings # This takes a query string as an argument and outputs the position where that starts # Next, create a new sequence that starts at this position, use a slice for this # The next step is to split the sequence up into codons # We've taken care of this for you, as it involves regular expressions # The output of this step is a list of codons # Finally, use a for loop to iterate over the codon list and translate each codon into an amino acid # This amino acid should be appended to the full protein sequence # All codon:amino acid pairs are stored in the `protein_dictionary' dictionary # You can search for an amino acid given a codon with the following command: 'protein_dictionary[codon] # Be aware: some of the codons in the dictionary are Stop codons: these are written as 'Stop' # Make sure that you check to see if the codon is a stop codon or not before adding it to the protein sequence # Convert an RNA sequence into a protein sequence def RNA_to_Protein(RNA): '''This function converts an RNA sequence into a protein sequence''' protein = '' # An empty string to hold the protien sequence # Get the start position of the translated region # Get sequence above the 5' untranslated region byCodon = re.compile(r'...', re.M) # A regex object to split our sequence into codons sequence_in_codons = byCodon.findall(translated_sequence) # Get the sequence as a list of codons # Create a for loop to look up each codon in the protein dictionary and add the amino acid to the protein sequence # Remember to check for stop codons return(protein) # Return the protein sequence # Run your function, and check the results protein_sequence = RNA_to_Protein(RNA_sequence) print("Your protein sequence is:") print(protein_sequence) print("We're now checking if your protein sequence is correct...") utilities.check_protein(protein_sequence) # We're now checking your protein sequence print("\n") print("Congratulations! You've successfully completed the introduction to Python!")
#importing lib's #they are all built in lib's import random import string #asking the user qustions times = input('Enter The Nuber Of Password(s) You Want To Genarate: ') length = input('Enter The Length Of the Password(s): ') wantLower = input('Do you want lower case letters in the password(s) (y/n)') wantUpper = input('Do you want upper case lestters in the password(s) (y/n)') wantNum = input('Do you want numbers in the password(s) (y/n)') wantPunc = input('Do you want punctuation in the password(s (y/n))') #checking to make sure that at least one option is on if wantLower == 'n' and wantUpper == 'n' and wantNum == 'n' and wantPunc == 'n': print('Cant have all digets and charecters set to no') quit() #setting all b and i to 0 b = 0 i = 0 #setting the first rand int c = random.randint(1,4) while b < int(times): while i < int(length): if c == 1 and wantLower == 'y': print(random.choice(string.ascii_lowercase), end='') i = i+1 elif c == 2 and wantNum == 'y': print(random.randint(1,9), end='') i = i+1 elif c == 3 and wantUpper == 'y': print(random.choice(string.ascii_uppercase), end='') i = i+1 elif c == 4 and wantPunc == 'y': print(random.choice(string.punctuation), end='') i = i+1 elif wantPunc == 'n' or wantNum == 'n' or wantUpper == 'n' or wantLower == 'n': pass else: print('error invalid value') c = random.randint(1,4) print('') i = 0 b = b+1
#!/usr/bin/python3 import sys def count(text): lst = text.split(' ') print(len(lst) - lst.count ("'\\n',")) def main(): print("insert text here and finish it with endl(control D)") text = str(sys.stdin.readlines()) count(text) if __name__ == "__main__": main()
""" number = int(input("Gimme a number")) while number != 1: print (number) if number == 1: break if number%2 == 0: number = number/2 elif number%2 != 0: number = (number *3)+1 print (number) """ ''' def Graph(t,x): Space = [] for i in range (len(x)): a = x[i] while (True): if t == a: a -= 1 else: Space.append(a) print (Space) break return (Space) ''' def space(x,t): for l in range (t): a = '' for i in range (len(x)): if t - x[i] <= l: a += "*\t" else: a += "\t" print (a) x = [7,1,8,3] t = 0 for i in range (len(x)): if t < x[i]: t = x[i] space(x,t) h = '' for z in range (len(x)): h += (str(x[i]),"\t")
# FizzBuzz, Accumalative calculator, FizzBuzz Accumalative and Prime. #FIZZBUZZ """ for Number in range (1,10): if Number % 3 == 0 and Number % 5 == 0: print ("FizzBuzz!!!") elif Number % 3 == 0: print ("Fizz!") elif Number % 5 == 0: print ("Buzz!") else: print ("Oof big neck! The number was: "+ str(Number)) """ """ #ACCUMALATIVE CALCULADORA Number = int(input("Number? ")) Calculate = 0 Number = Number + 1 for N in range (0,Number): Calculate = Calculate + N print (Calculate) """ #FIZZBUZZ ACCUMALATIVE """ Calculate = 0 Store = 0 for Number in range (1,1000): if Number % 3 == 0 and Number % 5 == 0: Store = Number + Store elif Number % 3 == 0: Store = Store + Number elif Number % 5 == 0: Store = Store + Number else: Calculate = Number + Calculate print (Calculate) print (Store) """ #PRIME NUMBRE" N = int(input("Give me a number")) if N > 1: for X in range(2,N): print () if (N % X) == 0: print(N,"is not a Prime number.") break else: print ("It's Prime.") else: print(N, "is not a Prime number, it's Composite.")
import csv #csv่ชญใฟ่พผใ‚“ใงใ€œ f = open('stock.csv', 'r') #ใƒ•ใ‚กใ‚คใƒซ้–‹ใ„ใฆใ€œ reader = csv.reader(f) header = next(reader) for row in reader: #1่กŒใฅใค่ชญใฟ่พผใ‚€ใ‚ˆ print(row) f.close() #ใŠใพใ‘ CsvFile = csv.reader(open('stock.csv'),delimiter=',') #csvใƒ•ใ‚กใ‚คใƒซใ‚’่ชญใฟ่พผใ‚€ CsvList = [] #็ฉบใฎcsvใƒ•ใ‚กใ‚คใƒซใ‚’็”จๆ„ใ—ใฆใ‚ใ’ใฆ for i in CsvFile: CsvList.append(i) print(CsvList)
for i in range(5, 10): print(i) print() for i in range(0, 10, 3): print(i) print() for i in range(-10, -100, -30): print(i) print() a = ['I', 'have', 'a', 'pen'] for i in range(len(a)): print(i, a[i])
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import sys ''' ๆ•ฐๆฎๆ ผๅผ่ฝฌๆข ''' def character_tagging(input_file, output_file): input_data = codecs.open(input_file, 'r', 'utf-8') output_data = codecs.open(output_file, 'w', 'utf-8') for line in input_data.readlines(): word_list = line.strip().split() for word in word_list: word=word.replace('/',' ') output_data.write(word + u"\n") output_data.write(u"\n") input_data.close() output_data.close() if __name__ == '__main__': if len(sys.argv) == 3: print ("pls use: python make_crf_train_data.py input_file output_out_file") # sys.exit() input_file = sys.argv[1] output_file = sys.argv[2] else: input_file = './data/train-2.txt' output_file = './data/train_out.txt' character_tagging(input_file, output_file)
def get_level(bmi): if bmi <= 18.5: level = '์ €์ฒด์ค‘' elif 18.5 <= bmi < 23: level = '์ •์ƒ' elif 23 <= bmi < 25: level = '๊ณผ์ฒด์ค‘' elif 25 <= bmi < 30: level = '๋น„๋งŒ' else: level = '๊ณ ๋„๋น„๋งŒ' # return : level๊ฐ’ ํ˜ธ์ถœ return level while True: height = input('Write your height:') weight = input('Write your weight:') bmi = float(weight) / float(height) ** 2 * 10000 BMI_TEXT = '[์ €์ฒด์ค‘-18.5-์ •์ƒ-23-๊ณผ์ฒด์ค‘-25-๋น„๋งŒ-30-๊ณ ๋„๋น„๋งŒ]' # print screen print('{}\nYour BMI is {:.2f} \n๋‹น์‹ ์€ {}์ž…๋‹ˆ๋‹ค.'.format(BMI_TEXT, bmi, get_level(bmi)))
''' Author: c17hawke Name: Sunny Bhaveen Chandra Date: Nov 15 2019 Time: 1351 hrs IST Problem Statement:- Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. ''' import numpy as np def getResults(randomList, guess): ''' figures out whether any two nos. in the list sum to our guessed no. ''' for num in randomList: no_A = num no_B = guess - no_A if (no_A in randomList) and (no_B in randomList): return True return False def main(): # generating some random integre list of 20 nos. randomList = np.random.randint(1,100,20) print("random list: ",randomList) guess = int(input("Enter you choice of no.\n>> ")) result = getResults(randomList, guess) #print the results print("Found two nos." if result else "Nos not found") if __name__ == '__main__': main()