text
stringlengths
37
1.41M
def Diameter(graph): return Max(AllShortestDistance(graph)) def AllShortestDistance(graph): """Compute the shortest distance between all pairs of vertices. Args: graph: Adjacency matrix, where entries are non-negative distance or None if there is no edge between the pair of vertices. Returns: distance: where distances[i][j] = the shortest distance between V_i and V_j. """ INF = float('Inf') V = len(graph) # Shortest distance between pairs of vertices with no intervening vertices. d = [[INF for col in row] for row in graph] for i in xrange(V): for j in xrange(V): if i == j: d[i][j] = 0 elif graph[i][j] is None: d[i][j] = INF else: d[i][j] = graph[i][j] for k in xrange(V): # d has shortest distance between pairs of vertices with intervening # vertices in {V_n : 0 <= n < k} only. for i in xrange(V): for j in xrange(V): # V_k introduce another path candidate for shortest path between V_i # and V_j. new_route = d[i][k] + d[k][j] if new_route < d[i][j]: d[i][j] = new_route return d def Max(d): return max([max(row) for row in d]) import unittest class TestAllShortestDistance(unittest.TestCase): def test_Example(self): graph = [ [None, 1, 1, 1], [1, None, None, None], [1, None, None, None], [1, None, None, None], ] self.assertEqual( [ [0, 1, 1, 1], [1, 0, 2, 2], [1, 2, 0, 2], [1, 2, 2, 0] ], AllShortestDistance(graph)) class TestDiameter(unittest.TestCase): def test_Example(self): graph = [ [None, 1, 1, 1], [1, None, None, None], [1, None, None, None], [1, None, None, None], ] self.assertEqual(2, Diameter(graph))
def InversionCountSq(values): inversion_count = 0 for i in xrange(len(values)): for j in xrange(i + 1, len(values)): if values[i] > values[j]: inversion_count += 1 return inversion_count def InversionCountFast(values): _, inversion_count = MergeSort(values) return inversion_count def MergeSort(values): if len(values) <= 1: return values, 0 a_values, a_inversion_count = MergeSort(values[:len(values)/2]) b_values, b_inversion_count = MergeSort(values[len(values)/2:]) merged_values, merged_inversion_count = Merge(a_values, b_values) return merged_values, ( a_inversion_count+b_inversion_count+merged_inversion_count) def Merge(xs, ys): zs = [] i = j = 0 inversion_count = 0 while i < len(xs) and j < len(ys): if xs[i] < ys[j]: zs.append(xs[i]) i += 1 else: zs.append(ys[j]) j += 1 inversion_count += len(xs) - i while i < len(xs): zs.append(xs[i]) i += 1 while j < len(ys): zs.append(ys[j]) j += 1 return zs, inversion_count import unittest class TestInversionCount(unittest.TestCase): def setUp(self): self.tests = [ {'seq': [2, 4, 1, 3, 5], 'expected': 3}, {'seq': [1, 2, 3, 4, 5], 'expected': 0}, {'seq': [5, 4, 3, 2, 1], 'expected': 10}, ] def test_Square(self): for test in self.tests: self.assertEqual(test['expected'], InversionCountSq(test['seq'])) def test_Fast(self): for test in self.tests: self.assertEqual(test['expected'], InversionCountFast(test['seq']))
"""Minimum path of letter replacements to translate from one string to another. First solution is A*search. Second solution is much faster and simpler. """ from typing import List, Set, Dict, Callable, TypeVar, Tuple import string T = TypeVar('T') class PathData(object): def __init__(self, parent: T, distance_from_start: int): # The parent of this node on the shortest path so far. self.parent = parent # The distance from start to this node on the shortest path so far. self.distance_from_start = distance_from_start class PendingData(object): def __init__(self, node: T, estimated_total_distance: int): # Node pending for expansion. self.node = node # Estimated distance from start to end via this node. self.estimated_total_distance = estimated_total_distance def retrace_path(paths: PathData, end: T) -> List[T]: """Shortest path from start to end given the computation from A*Search.""" route = [end] node = end while True: parent = paths[node].parent if not parent: return route route.insert(0, parent) node = parent def update_pending(pending: List[PendingData], node: T, estimated_total_distance: int) -> None: """Add or update a node for expansion later.""" # Delete old one if exists. i = 0 while i < len(pending): if pending[i].node == node: del pending[i] break i += 1 # Insert new node. i = 0 while i < len(pending): if pending[i].estimated_total_distance >= estimated_total_distance: break i += 1 pending.insert(i, PendingData(node, estimated_total_distance)) def update_paths( paths: Dict[T, PathData], parent: T, child: T, edge_dist: int) -> None: """Update the shortest paths given a new found edge.""" distance_from_start = ( paths[parent].distance_from_start if parent in paths else 0) + edge_dist if child not in paths: paths[child] = PathData(parent, distance_from_start) elif paths[child].distance_from_start > distance_from_start: paths[child].parent = parent paths[child].distance_from_start = distance_from_start def a_star_search( start: T, end: T, expand: Callable[[T], List[Tuple[T,int]]], a_star_distance: Callable[[T, T], int]): """Generic A*Search from start to end.""" paths = {start: PathData(parent=None, distance_from_start=0)} expanded: Set[T] = set() pending = [PendingData(node=start, estimated_total_distance=a_star_distance(start, end))] num_explored = 0 while pending: parent = pending.pop(0).node num_explored += 1 if parent == end: return retrace_path(paths, end), num_explored for child, dist in expand(parent): if child in expanded: continue update_pending(pending, child, paths[parent].distance_from_start + dist + a_star_distance(child, end)) update_paths(paths, parent, child, dist) expanded.add(parent) # Could not find a path. return [], 0 def substitute(node: str, original_letter: str, new_letter: str) -> str: return node.replace(original_letter, new_letter) def letter_set(node: str) -> Set[str]: return set(list(node)) def my_expand(node: str) -> List[Tuple[str, int]]: """Find all possible transformed string over a single substitution.""" children = [] for original_letter in letter_set(node): for new_letter in string.ascii_lowercase: if new_letter == original_letter: continue children.append((substitute(node, original_letter, new_letter), 1)) return children def my_a_star_distance(a: str, b: str) -> int: """Heuristic distance function for the letter substitution graph.""" assert len(a) == len(b) return sum(c != d for c, d in zip(a, b)) # Tests. tests = [ ('a', 'b'), ('ab', 'ba'), ('abc', 'ccc'), ('abc', 'bca'), ('abc', 'bcd'), ('abc', 'baa'), ('aab', 'abc'), ('abc', 'bcb'), ('abcdefg', 'bcdefga'), ] print('A*Search approach') for start, end in tests: path, num_explored = a_star_search(start, end, my_expand, my_a_star_distance) if path: print('{} -> {} needs {} steps {}, explored {} nodes'.format( start, end, len(path) - 1, path, num_explored)) else: print('{} -> {} is impossible.'.format(start, end))
def BinarySearch(values, key): left, right = 0, len(values) while left < right: mid = (left + right) / 2 if key < values[mid]: right = mid elif key > values[mid]: left = mid + 1 else: return (mid, True) else: if left == 0: return (0, False) if left == len(values): return (len(values) - 1, False) else: if abs(values[left-1] - key) < abs(values[left] - key): return (left - 1, False) else: return (left, False) import unittest class TestBinarySearch(unittest.TestCase): def test_Example(self): values = [10, 50, 90] self.assertEqual((0, True), BinarySearch(values, 10)) self.assertEqual((1, True), BinarySearch(values, 50)) self.assertEqual((2, True), BinarySearch(values, 90)) self.assertEqual((0, False), BinarySearch(values, 9)) self.assertEqual((0, False), BinarySearch(values, 11)) self.assertEqual((1, False), BinarySearch(values, 49)) self.assertEqual((1, False), BinarySearch(values, 51)) self.assertEqual((2, False), BinarySearch(values, 89)) self.assertEqual((2, False), BinarySearch(values, 91))
import matplotlib.pyplot as plt import numpy as np def plotdata(x,y,line=False): plt.plot(x, y, 'rx') plt.ylabel('h(heta) or y ') plt.xlabel('feature x') plt.xticks(np.arange(min(x), max(x)+1, 2)) plt.yticks(np.arange(min(y), max(y)+1, 2)) if line: l1 = np.linspace(min(x),max(x)) l2 = THETA[1]*l1+THETA[0] plt.plot(l1, l2, '-b', label='y=2x+1') plt.show() def gradientDescent(X, y, theta, alpha, iterations):#if ever confused do the math again and it will make sense for i in range(iterations): H=X.dot(theta) l=np.array(H-y) r=l*X theta=theta-r*(alpha/m) theta=np.array([theta[0,0],theta[0,1]]) return(theta) def computeCost(X,y,THETA): H=X.dot(THETA) l=np.array(H-y)**2 j=np.sum(l)/(2*m) return(j) def gradientDescentMulti(): pass def computeCostMulti(): pass def featureNormalize(): pass def normalEqn(): pass def predict(X): return np.array(X).dot(THETA) data = open('ex1data1.txt', 'r').read().replace('\n',',').split(',') m=len(data)//2 x,y=[float(data[i*2]) for i in range(m)],[float(data[i*2+1]) for i in range(m)] #plotdata(x,y) print(x) #------------------------------ single only X=np.matrix( [ [1,i] for i in x ]) n=X[0].shape[1] THETA=np.array( [0 for i in range(n)] ).transpose() cost=computeCost(X,y,THETA) iterations,alpha=1500,0.01 THETA = gradientDescent(X, y, THETA, alpha, iterations); plotdata(x,y,True)
from typing import List def three_sum(nums:List[int])->List[List[int]]: if len(nums) < 3: return [] nas = [] nums.sort() for first in range(len(nums)-2): if nums[first] > 0: break if first > 0 and nums[first] == nums[first-1]: continue target = -nums[first] three = len(nums) - 1 for second in range(first+1, len(nums)-1): if second > 0 and nums[second] == nums[second-1]: continue while second < three and nums[second]+nums[three]>target: three -= 1 if second == three: break if nums[second] + nums[three] == target: nas.append([nums[first], nums[second], nums[three]]) return nas
name = input("Enter the your name : ") num1 = int(input("Enter the number : ")) for i in range(0,num1): for n in name: print(n)
input_surname = input("사용자의 성을 입력하세요 : ") input_firstname = input("사용자의 이름을 입력하세요 : ") print('Hello, '+ input_surname + input_firstname)
#day calculator day = int(input('예정일까지 얼마나 남았습니까? : ')) hours = day * 24 minutes = hours * 60 seconds = minutes * 60 print(hours, "시간 남으셨습니다.") print(minutes, "분 남으셨습니다.") print(seconds, "초 남으셨습니다.")
input_name = input('당신의 이름은? : ') input_age = input('당신의 나이는? : ') print(input_name, 'next birthday you will be', input_age)
import random color = random.choice(["black", "white" ,"purple", "orange", "green"]) print(color) #알고리즘 확인을 위해 삽입. a_color = input('Choose one of the following colors.\n"Black", "White" ,"Purple", "Orange", "Green" : ') a_color = a_color.lower() answer = True while answer == True: if color == a_color: print('"Well done!"') answer = False elif a_color == "Black": a_color = input('"Is your heart Black?"\nEnter the color again : ') answer = True elif a_color == "White": a_color = input('"You are as pure as white."\nEnter the color again : ') answer = True elif a_color == "Purple": a_color = input('"Purple is the color of nobility."\nEnter the color again : ') answer = True elif a_color == "Orange": a_color = input('"Have you been eating oranges for a long time?"\nEnter the color again : ') answer = True elif a_color == "Green": a_color = input('"I bet you are Green with envy"\nEnter the color again : ') answer = True else: a_color = input('"Enter the color again" : ')
import operator d = {'java':10, 'r':6, 'python':18, 'firebase':16 } print('Original dictionary : ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(1)) print('Dictionary in ascending order by value : ',sorted_d)
def del_key(n): dic = {"r":1, "python":5, "java":3, "swift":4, "flutter":2} del dic[n] return dic l = input("eneter one key value:") print(del_key(l))
#输出9*9乘法口诀表。 def mul(n): for i in range(1,n): for j in range(1,n): print(i,'*',j,'=',i*j) mul(10)
#学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。 def stratified(x): if x>=90: return 'A' elif x>=60: return 'B' else: return 'C' n=int(input()) print(stratified(n))
#一个5位数,判断它是不是回文数。 def Five_number_Palindrome(x): if x < 100000 and x>9999: sum=[] while x>9: mid=x%10 x=int(x/10) sum.insert(0,mid) sum.insert(0,x) else: print('input error number') sys.exit() return sum n=int(input()) s=Five_number_Palindrome(n) if s[0]==s[4] and s[1]==s[3]: print('Yes,%d is palindrome'%n) else: print('No,%d is not palindrome'%n)
# coding:utf-8 class Person(object): def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex print(name, age, sex) # @property修饰的函数:定义时只要self参数 # 调用时不要传递任何参数,并且不能写括号 @property def get_age(self): pass xiaohong = Person("小红", 18, "girl") xiaoming = Person("小明", 18, "boy") xiaoming.get_age # dir()函数:返回当前范围内的变量、方法和定义的类型变量 print(dir()) print(dir(xiaohong)) print(xiaohong.__dict__)
#coding: utf8 import sys import math print "S-Salir" print "1-Sumar" print "2-Restar" print "3-Multiplicar" print "4-Dividir" opcionmain = raw_input("Introduzca una opcion :") while (opcionmain == False): print "Continue" if (opcionmain == 'S' or opcionmain == 's'): print "Adios" salir = True if (opcionmain == 1): variable1 = input("Introduzca el numero :") variable2 = input("Introduzca el numero :") print "El resultado es :" , variable1 + variable2 if (opcionmain == 2): variable1 = input("Introduzca el numero :") variable2 = input("Introduzca el numero :") print "El resultado es :" , variable1 - variable2 if (opcionmain == 3): variable1 = input("Introduzca el numero :") variable2 = input("Introduzca el numero :") print "El resultado es :" , variable1 * variable2 if (opcionmain == 4): variable1 = input("Introduzca el numero :") variable2 = input("Introduzca el numero :") print "El resultado es :" , variable1 / variable2
n=int(input("How many names will you input?" )) for i in range(0,n): name=input() print("Hello {}".format(name))
""" 一个回合制游戏,2个角色都有hp和power myhp = hp - enemy_power enemyhp = hp - my_power """ class First(): hp = 2000 def __init__(self, enemy_power, my_power): self.enemy_power = enemy_power self.my_power = my_power def first_battle(self): for i in range(1, 10): myhp = self.hp - self.enemy_power enemyhp = self.hp - self.my_power if myhp > enemyhp: print("我赢了!!\n我的血值:%d,\n敌人的血值:%d" % (myhp, enemyhp)) elif myhp < enemyhp: print("敌人赢了\n我的血值:%d,\n敌人的血值:%d" % (myhp, enemyhp)) else: raise Exception("平局异常") enemy_power = int(input("请输入敌人的攻击力:")) my_power = int(input("请输入我的攻击力:")) first = First(enemy_power, my_power) first.first_battle()
import random questions = { "strong": "Do ye like yer drinks strong?", "salty": "Do ye like it with a salty tang?", "bitter": "Are ye a lubber who likes it bitter?", "sweet": "Would ye like a bit of sweetness with yer poison?", "fruity": "Are ye one for a fruity finish?" } ingredients = { "strong": ["glug of rum", "slug of whisky", "splash of gin"], "salty": ["olive on a stick", "salt-dusted rim", "rasher of bacon"], "bitter": ["shake of bitters", "splash of tonic", "twist of lemon peel"], "sweet": ["sugar cube", "spoonful of honey", "spash of cola"], "fruity": ["slice of orange", "dash of cassis", "cherry on top"] } ###Setting global drink variable global your_drink your_drink = {} def check_YN(n): """Function to Verify user input is valid""" ### Ensures the value entered is not an integer or float while True: try: int(n) n = (raw_input("Please enter [y/n]")) except ValueError: break ### Ensures the input is valid and capitalizes for uniformity while True: if n.upper() == "Y" or "YES" or "N" or "NO": break else: n = (raw_input("Please enter [y/n]")) def what_do_you_like(): """Function to ask user about drink preferences""" ### Asks each question listed in questions dictionary for key in questions: n = (raw_input(questions[key])) n = n.upper() check_YN(n) ### Assigns ingregient value a Boolean depending on user answer if n == "Y": your_drink[key] = True else: your_drink[key] = False def drink_maker(): """Function to construct drink from questions asked""" mixed_drink = [] ### Checks drink selection dictionary for users desired drink attributes, ### Selects one ingredient at random from desired category ### and appends ingredient to drink list. for key in your_drink: if your_drink[key] == True: mixed_drink.append(random.choice(ingredients[key])) else: continue ### Convert list to string drink = '\n'.join(mixed_drink) print"Here is what you should put in your drink!!!" print drink if __name__ == '__main__': what_do_you_like() drink_maker()
numero = int(input("Dime un numero: ")) palabra="" c=0 for i in range (1,numero+1): c=i+c print(f"{c}")
import random def drawBoard(board): # "board" is a list of 10 strings representing the board (ignore index 0) print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('----------------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('----------------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') def inputPlayerLetter(): letter = 'X' while not(letter == 'X' or letter == 'O'): letter = input('Do you want to be X or O? ').upper() # the first element in the list is the player’s letter, the second is the computer's letter. if letter == 'X': return ['X', 'O'] else: return ['O', 'X'] def whoGoesFirst(): # Randomly choose the player who goes first. if random.randint(0, 1) == 0: return 'computer' else: return 'player' def playAgain(): # This function returns True if the player wants to play again, otherwise it returns False. return input('Do you want to play again?(y or n) ').lower().startswith('y') def isWinner(bo, le): return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal (bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal def getBoardCopy(board): # Make a duplicate of the board list and return it the duplicate. duplicateBoard = [] for i in board: duplicateBoard.append(i) return duplicateBoard def isSpaceFree(board, move): return board[move] == ' ' def makeMove(board, letter, move): board[move] = letter def getPlayerMove(board): # Let the player type in their move. move = '' while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)): move = input('What is your next move? (1-9) ') return int(move) def chooseRandomMoveFromList(board, movesList): # Returns a valid move from the passed list on the passed board # return none if there is no valid move possibleMoves = [] for i in movesList: if isSpaceFree(board, i): possibleMoves.append(i) if(len(possibleMoves) != 0): return random.choice(possibleMoves) else: return None def isForkMove(board, letter, move): # we check if a move creates a fork copy = getBoardCopy(board) makeMove(copy, letter, move) winningMoves = 0 for i in range(1, 10): if isSpaceFree(copy, i) and testWinMove(copy, letter, i): winningMoves += 1 return winningMoves >= 2 def testWinMove(board, letter, move): copy = getBoardCopy(board) copy[move] = letter return isWinner(copy, letter) def getComputerMove(board, computerLetter): # Given a board and the computer's letter, we determine where to move and return that move. if computerLetter == 'X': playerLetter = 'O' else: playerLetter = 'X' # Tic Tac Toe AI Algorithm # 1) We check if we can win in the next move for i in range(1, 10): copy = getBoardCopy(board) if isSpaceFree(copy, i): makeMove(copy, computerLetter, i) if isWinner(copy, computerLetter): return i # 2) We check if there is a move the player can make that will cause computer to lose game. # If there is, the computer should move there to block the player. for i in range(1, 10): copy = getBoardCopy(board) if isSpaceFree(copy, i): makeMove(copy, playerLetter, i) if isWinner(copy, playerLetter): return i # 3) We check computer forks for i in range(1, 10): if isSpaceFree(board, i) and isForkMove(board, computerLetter, i): return i # 4) We check player forks playerForks = 0 tempMove = None for i in range(1, 10): if isSpaceFree(board, i) and isForkMove(board, playerLetter, i): playerForks += 1 tempMove = i if playerForks == 1: return tempMove elif playerForks == 2: return chooseRandomMoveFromList(board, [2, 4, 6, 8]) # 5) We check if the center space is free. if isSpaceFree(board, 5): return 5 # 6) We check if any of the corner spaces are free. move = chooseRandomMoveFromList(board, [1, 3, 7, 9]) if move != None: return move # 7) Lastly, we choose randomly any of the side spaces that are free return chooseRandomMoveFromList(board, [2, 4, 6, 8]) def isBoardFull(board): for i in range(1, 10): if isSpaceFree(board, i): return False return True
def heapyfy(arr,n,i): largest=i left=2*i+1 right=2*i+2 if(left<n and arr[largest]<arr[left]): largest=left if(right<n and arr[largest]<arr[right]): largest=right if(largest!=i): arr[i],arr[largest]=arr[largest],arr[i] heapyfy(arr,n,largest) def heapsort(arr,n): for i in range(n,-1,-1): heapyfy(arr,n,i) for i in range(n-1,-1,-1): arr[0],arr[i]=arr[i],arr[0] heapyfy(arr,i,0) arr=list(map(int,input().split())) n=len(arr) heapsort(arr,n) print(arr)
from utils import create_lsystem, Position import turtle """ F - moving forward [ - push current posiotion to stack ] - pop position from stack + - rotate to left - - rotate to right """ axiom = 'X' angle = 20 length = 30 def create_turtle(): sticks = turtle.Turtle() sticks.pensize(2) sticks.speed(0) sticks.up() screen = sticks.getscreen() turtle.setup(1000,1000) iter = screen.textinput("Iterations", "Number of iterations:") sticks.goto(0, -400) sticks.down() return sticks, int(iter) def draw_fractal(axiom='X', angle=angle, length=length, num_iters=5): stack = [] sticks, num_iters = create_turtle() screen = sticks.getscreen() if num_iters>=8: length = 2 sticks._tracer(0) elif num_iters >= 6: length = 7 sticks._delay(0) else: length = 20 sticks._delay(2) # sticks._tracer(0) sticks.hideturtle() sticks.left(90) generated_string = create_lsystem(axiom=axiom, num_iters=num_iters) print('Generated string: {}'.format(generated_string)) for i, char in enumerate(generated_string): if char == 'F': sticks.forward(length) elif char == '+': sticks.left(angle) elif char == '-': sticks.right(angle) elif char == '[': position = sticks.pos() state = Position(position[0], position[1], sticks.heading()) stack.append(state) elif char == ']': state = stack.pop() position = (state.x, state.y) ang = state.angle sticks.up() sticks.goto(position) sticks.setheading(ang) sticks.down() screen.exitonclick() if __name__ == "__main__": draw_fractal(length=10)
# 사전 키를 사용해 값을 불러오는 예제 dic = {"boy": "소년", "school": "학교", "book": "책"} print(dic["boy"]) # print(dic["student"]) # KeyError print(dic.get("boy")) print(dic.get("student")) print(dic.get("student", "사전에 없는 단어입니다.")) # in, not in 사용하여 사전에 단어가 있는지 알아보자. dic = {"boy": "소년", "school": "학교", "book": "책"} if "student" in dic: print("사전에 있는 단어입니다.") else: print("사전에 없는 단어입니다.") if "boy" not in dic: print("사전에 없는 단어입니다.") else: print("사전에 있는 단어입니다.") # 사전에 값을 변경해보자. dic = {"boy": "소년", "school": "학교", "book": "책"} dic["boy"] = "남자애" dic["girl"] = "여자애" print(dic) del dic['book'] print(dic) # 키와 값을 가져와 보자 dic = {"boy": "소년", "school": "학교", "book": "책"} print(dic.keys()) print(dic.values()) print(dic.items()) # 두개의 사전을 병합해보자. dic = {"boy": "소년", "school": "학교", "book": "책"} dic2 = {"student": "학생", "teacher": "선생님", "book": "서적"} dic.update(dic2) print(dic) # 팝송 가사에 등장하는 알파벳 문자의 출현 횟수를 세어 보자. song = """by the rivers of babylon, there we sat down yeah we wept, when we remember zion. when the wicked carried us away in captivity required from us a song new how shall we sing the lord's song in a strange land """ alphabet = dict() for c in song: if c.isalpha() == False: continue c = c.lower() if c in alphabet: alphabet[c] += 1 else: alphabet[c] = 1 print(alphabet) # 알파벳 문자수를 정렬해서 값을 확인해보자. key = list(alphabet.keys()) key.sort() for c in key: print(c, "=>", alphabet[c])
# 일련의 문자를 따옴표(“, ‘)로 감싸 나열해 놓은 것이다. print("Hello World!") a = "Hello World!" print(a) print('Hello World!') a = 'Hello World!' print(a) # 따옴표(“, ‘) 잘 못 사용한 예 # print("Hello World!') # SyntaxError # print('Hello World!") # SyntaxError # # print("I Say "Help" to you") # SyntaxError # print('I Say 'Help' to you') # SyntaxError # # print("Let's go") # 따옴표를 같이 사용 하는 방법 print("I Say \"Help\" to you") print('I Say \'Help\' to you') print("Let's go") # 확장열 사용 예제 print("first\nsecond") print("old\nnew") print("c:\temp\new.text") # 예상 결과가 다름 print("c:\\temp\\new.text") print(r"c:\temp\new.text") # 확장열을 적용하지 않음 # 긴 문자열 s = """강나루 건너서 밀받 길을 구름에 달 가듯이 가는 나그네 길은 외줄기 남도 삼백리 술 익는 마을마다 타는 저녁놀 구름에 달 가듯이 가는 나그네""" print(s) # 긴 문자열 개행 방지 s = """강나루 건너서 밀받 길을 구름에 달 가듯이 가는 나그네 \ 길은 외줄기 남도 삼백리 술 익는 마을마다 타는 저녁놀 \ 구름에 달 가듯이 가는 나그네""" print(s) # 문자열 합치기 s = "korea" "japan" "2002" print(s) s = ( "korea" "japan" "2002" ) print(s)
''' *Team id:eYRC-LM#448 *Author List: Akhil Guttula, Sai Kiran, Sai Gopal, Mohan *Filename: algo_mod *Theme: Launch a Module *Functions:find_route,delete_point,insert_point,ext_route,graph_dist,minDistance,set_objects_positions,get_objects_positions,set_free_loc,get_neighbours,dijkistra *Global Variables: graph,parent,objects_position,V ''' import cv2, time, sys import numpy as np ''' *Function Name: find_route *Input: position-1(source),position-2(destination),comparision details for source and destination *Output: route between the source and destination using dijkistra algorithm *Logic: uses dijkistra's algorithm to find the shortest path *Example Call: find_route(9,46,1,1) ''' # finds the route between the source and destination using dijkistra algorithm def find_route(p1, p2, details_src, details_dest): global graph, parent, parentx, pathx_list #for adjacent objects if details_src == details_dest and (abs(p1-p2) == 9 or abs(p1-p2) == 1): if(p1 % 9 != 0 and p2 % 9 != 0): return[p1, p2] #inserting the points insert_point(p1) insert_point(p2) #reset parent list for x in range(55): parent[x] = -1 parentx[x] = [] pathx_list = [] dijkistra(graph, p1) #deleting the points after algo delete_point(p1) delete_point(p2) #finding the route that has minimum number of turns #short_len: has the shortest distance length obtained from dijkistra's algorithm short_len = len(ext_route(p2)) #obtains all the paths using shortest path - dijkistra's algorithm printAllPaths(p2, p1, short_len) #selecting the path which has minimum number of turns min_pts = len(pathx_list[0]) route = pathx_list[0] for obj in pathx_list: temp_pts = find_critical_pts(obj) if len(temp_pts) < min_pts: route = obj route = list(route) route.reverse() return route ''' *Function Name: delete_point *Input: position *Output:removes the point from the grid(considers the point as an obstacle) *Logic: deletes the point and also removes its existance from adjacent graph points *Example Call:delete_point(22) ''' #eliminates the point from the grid(use it to remove obstacle) def delete_point(pos): #find it's adjacent points and eliminate the point from it global graph for x in graph[pos]: graph[x].remove(pos) graph[pos] = [] ''' *Function Name:insert_point *Input: position *Output:inserts the point in the graph *Logic:inserts the point in the graph and also includes as the neighbours in the adjacent graph points *Example Call:insert_point(32) ''' # inserts the point def insert_point(x): global objects_position temp = [] if x % 9 != 1: #left sided objects try: objects_position.index(x - 1) except ValueError: temp.append(x - 1) graph[x - 1].append(x) else: pass if x % 9 != 0: #right sided objects try: objects_position.index(x + 1) except ValueError: temp.append(x + 1) graph[x + 1].append(x) else: pass if x - 9 > 0 and x - 9 < 55: #for objects in between try: objects_position.index(x - 9) except ValueError: temp.append(x - 9) graph[x - 9].append(x) else: pass if x+9 > 0 and x + 9 < 55: try: objects_position.index(x + 9) except ValueError: temp.append(x + 9) graph[x + 9].append(x) else: pass graph[x] = temp ''' *Function Name: ext_route *Input: destination point *Output: a route depicting from which node the destination is reach *Logic: uses parent array to find the parent node(node that is traversed before the destination node) *Example Call:ext_route(11) ''' #routes the path from source to destination def ext_route(ptr): global parent route = [] reroute = [] route.append(ptr) while parent[ptr] > 0: route.append(parent[ptr][0]) ptr = parent[ptr][0] route.reverse() return route ''' *Function Name: graph_dist *Input: graph,position-1,position-2 *Output:returns 1 as distance between two positions if there exists a link between the two positions *Logic: checks if the the other position exists as neighbour point in the graph *Example Call:graph_dis(graph,23,24) ''' #graph[u][v] == distance between vertices u and v def graph_dist(graph, p1, p2): for x in graph[p1]: if x == p2: return 1 ''' *Function Name: minDistance *Input: arrays named dist(distance),sptSet(shortest path set) *Output: *Logic: *Example Call: ''' #finds the minimum distance(code part of dijkistra's algo) def minDistance(dist,sptSet): min = 999 global V for v in range(V+1): if sptSet[v] == 0 and dist[v] <= min: min = dist[v] min_index = v return min_index ''' *Function Name: set_objects_positions *Input: an array of positions where the objects or obstacles are present *Output: None *Logic: sets the locations where there are objects or obstacles so that bot cannot traverse through it *Example Call:set_objects_positions([11,16,23,34,48]) ''' #includes both objects and obstacles def set_objects_positions(arr): global objects_position for x in arr: objects_position.append(x) delete_point(x) ''' *Function Name: get_objects_positions *Input: NULL *Output: array of positions where the objects or obstacles are present *Logic: return global array objects_position which stores the positions where the objects or obstacles are present *Example Call:get_objects_positions() ''' def get_objects_positions(): global objects_position arr = objects_position return arr ''' *Function Name: set_free_loc *Input: source position *Output:sets the location free i.e includes the point in the graph so that bot can traverse through it *Logic: It is used when the specified position is made empty i.e after picking up the object from the point *Example Call:set_free_loc(23) ''' def set_free_loc(pos): global graph try: ind = objects_position.index(pos) del(objects_position[ind]) except ValueError: pass insert_point(pos) ''' *Function Name: get_neighbours *Input: source position *Output:returns the neighbouring positions of the source positions *Logic: return the neighbouring positions of the current position *Example Call:get_neighbours(34) ''' #returns the neighbouring points to the current block def get_neighbours(pos): global graph return graph[pos] ''' *Function Name: dijkistra *Input: graph,source position *Output: finds the shortest distance from the source position to all other positions *Logic: standard dijkistra's graph algorithm *Example Call:dijkistra(graph,2) ''' #main dijkistra's function def dijkistra(graph, src): global V, parent, parentx dist = [] sptSet = [] for i in range(V + 1): dist.append(999) sptSet.append(0) dist[src] = 0 for count in range(1, V): u = minDistance(dist, sptSet) sptSet[u] = 1 for v in range(1, V + 1): if(not sptSet[v]) and graph_dist(graph, u, v) and dist[u] != 999 and dist[u] + graph_dist(graph, u, v) <= dist[v]: dist[v] = dist[u] + graph_dist(graph, u, v) parent[v] = [u] parentx[v].append(u) def printAllPathsUtil(ux, dx, visitedx, pathx, short_len): global parentx, pathx_list # Mark the current node as visited and store in path visitedx[ux]= 1 pathx.append(ux) # If current vertex is same as destination, then print # current path[] #print pathx if ux == dx and len(pathx) == short_len: pathx_list.append(tuple(pathx)) else: # If current vertex is not destination #Recur for all the vertices adjacent to this vertex for i in parentx[ux]: if visitedx[i]== -1: printAllPathsUtil(i, dx, visitedx, pathx, short_len) # Remove current vertex from path[] and mark it as unvisited pathx.pop() visitedx[ux]= -1 # Prints all paths from 's' to 'd' def printAllPaths(sx, dx, short_len): global pathx_list # Mark all the vertices as not visited visitedx = [] for x in range(55): visitedx.append(-1) # Create an array to store paths pathx = [] # Call the recursive helper function to print all paths printAllPathsUtil(sx, dx, visitedx, pathx, short_len) def find_critical_pts(route): target_pts = [] diff = 99999 temp_diff = 99999 target_pts.append(route[0]) for i in range(1,len(route)): temp_diff = route[i] - route[i-1] if diff != 99999: if diff != temp_diff: target_pts.append(route[i-1]) diff = temp_diff diff = temp_diff target_pts.append(route[-1]) return target_pts ########################################################################################################### #GLOBAL VARIABLES ########################################################################################################### # graph: stores the graph(grid) of the arena along with its neighbouring positions graph = [] #'1' based index but its constituents are absolute # parent: used to store the parent node from which the current node has been travered parent = [] parentx = [] pathx_list = [] # objects_position: used to store the positions at which objects are present objects_position = [] # V: No of vertices in the graph(grid) V = 54 ########################################################################################################### # defining boundaries for the grid graph.append(-1) for x in range(1, 55): temp = [] if x % 9 != 1: #left boundary condition temp.append(x - 1) if x % 9 != 0: #right boundary condition temp.append(x + 1) if x - 9 >0 and x - 9 < 55: #upper boundary condition temp.append(x-9) if(x + 9 > 0 and x + 9 < 55: #right boundary condition temp.append(x + 9) graph.append(temp) #initialising parent array for x in range(55): parent.append(-1) parentx.append([]) #using algo module #step1: call set_objects_positoins(arr[]) #step2: call find_route(source,destination,details_src(color,shape),details_dest(color,shape)) #step3:call insert to add that point of the arena i.e free space
in_x, in_y = input("Enter x, y. eg: 5 27\n").strip().split(" ") def find_min_step(x, y): """Return min step between x, y when x become y. In one step x just eq x*2 or x-=1""" if x > y: exit(1) counter = 0 for i in range(y): if y % 2 != 0: y += 1 y = y / 2 counter += 2 else: y = y / 2 counter += 1 if y <= x: counter = counter + x - y break return int(counter) print(find_min_step(int(in_x), int(in_y)))
import pygame import sys import random # CONSTANTS SCREEN_W = 640 SCREEN_H = 480 BRICK_W = 60 BRICK_H = 15 PADDLE_W = 60 PADDLE_H = 12 BALL_DIAMETER = 16 BALL_RADIUS = int (BALL_DIAMETER / 2) MAX_PADDLE_X = SCREEN_W - PADDLE_W MAX_BALL_X = SCREEN_W - BALL_DIAMETER # State Machine S_BALL_IN_PADDLE = 0 S_PLAYING = 1 S_WON = 2 S_GAME_OVER = 3 MAX_PADDLE_X = SCREEN_W - PADDLE_W MAX_BALL_X = SCREEN_W - BALL_DIAMETER MAX_BALL_Y = SCREEN_H - BALL_DIAMETER PADDLE_Y = SCREEN_H - PADDLE_H - 10 # Induce Seizure r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) # Colors BLACK = (0,0,0) GRAY = (102,102,102) WHITE = (255,255,255) RED = (255,0,0) GREEN = (0,255,0) BLUE = (0,0,255) GOLD = (135,113,72) DANK_MAGENTA = (255,0,255) SEIZURE = (r,g,b) class OUBreakout(object): def __init__(self): # Initialize pygame and clock pygame.init() self.screen = pygame.display.set_mode((SCREEN_W, SCREEN_H)) pygame.display.set_caption("OU Breakout") self.clock = pygame.time.Clock() # Make sure we can use fonts if pygame.font: self.font = pygame.font.Font(None, 30) else: self.font = None # Initialize game data self.initialize_game() # Setup the game variables. This function will be called whenever we restart the game. def initialize_game(self): self.lives = int(input("How many lives do you want? More = easier ;) ")) self.score = 0 self.state = S_BALL_IN_PADDLE self.paddle = pygame.Rect(300, PADDLE_Y, PADDLE_W, PADDLE_H) self.ball = pygame.Rect(300, PADDLE_Y - BALL_DIAMETER, BALL_DIAMETER, BALL_DIAMETER) self.ball_velocity = [5, -5] self.create_bricks() # Create the bricks (pygame.Rects) for the current level. # The 10 and 5 are spacers to make sure bricks aren't touching. def create_bricks(self): y_ofs = 35 self.bricks = [] for i in range(7): # Iterate over rows x_ofs = 35 for j in range(8): # Iterate over columns self.bricks.append(pygame.Rect(x_ofs,y_ofs,BRICK_W,BRICK_H)) x_ofs += BRICK_W + 10 y_ofs += BRICK_H + 5 # Handle user keyboard input def check_input(self): keys = pygame.key.get_pressed() # Exit game if keys[pygame.K_ESCAPE]: sys.exit() # Move paddle left if keys[pygame.K_LEFT]: self.paddle.left -= 5 if self.paddle.left < 0: self.paddle.left = 0 # Move paddle right if keys[pygame.K_RIGHT]: self.paddle.left += 5 if self.paddle.left > MAX_PADDLE_X: self.paddle.left = MAX_PADDLE_X # Shoot ball if keys[pygame.K_SPACE] and self.state == S_BALL_IN_PADDLE: self.ball_velocity = [5, -5] self.state = S_PLAYING # Restart game if won/lost elif keys[pygame.K_RETURN] and (self.state == S_GAME_OVER or self.state == S_WON): self.initialize_game() # Move the ball within the bounds of the screen def move_ball(self): self.ball.left += self.ball_velocity[0] self.ball.top += self.ball_velocity[1] # Check ball location to ensure it is in a valid state, bounce otherwise # A bounce means flipping the sign of the velocity of the direction it was going if self.ball.left <= 0: self.ball.left = 0 self.ball_velocity[0] = -self.ball_velocity[0] elif self.ball.left >= MAX_BALL_X: self.ball.left = MAX_BALL_X self.ball_velocity[0] = -self.ball_velocity[0] if self.ball.top < 0: self.ball.top = 0 self.ball_velocity[1] = -self.ball_velocity[1] # Check if ball collides with (1) bricks or (2) paddle def handle_collisions(self): # Check every brick until a collision is found, then bail out for brick in self.bricks: if self.ball.colliderect(brick): self.score += 1 self.ball_velocity[1] = -self.ball_velocity[1] self.bricks.remove(brick) break # No more bricks? You won! if len(self.bricks) == 0: self.state = S_WON # Paddle collision if self.ball.colliderect(self.paddle): self.ball.top = PADDLE_Y - BALL_DIAMETER self.ball_velocity[1] = -self.ball_velocity[1] elif self.ball.top > self.paddle.top: self.lives -= 1 if self.lives > 0: self.state = S_BALL_IN_PADDLE else: self.state = S_GAME_OVER # Draw player stats to screen def show_stats(self): if self.font: font_surface = self.font.render("Blocks Hit: " + str(self.score) + " | " "Lives Left: " + str(self.lives), False, WHITE) self.screen.blit(font_surface, (185,5)) # Show a message to the user def show_message(self,message): if self.font: size = self.font.size(message) font_surface = self.font.render(message, False, WHITE) x = (SCREEN_W - size[0]) / 2 y = (SCREEN_H - size[1]) / 2 self.screen.blit(font_surface, (x,y)) # Draw active bricks to screen def draw_bricks(self): for brick in self.bricks: pygame.draw.rect(self.screen, SEIZURE, brick) # Our main game function def run(self): while True: # Forever loop # Handle clicking the 'X' to close for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # Lock to 60FPS and redraw screen self.clock.tick(60) self.screen.fill(DANK_MAGENTA) # Handle user input self.check_input() # Game state machine if self.state == S_PLAYING: # ball in play self.move_ball() self.handle_collisions() elif self.state == S_BALL_IN_PADDLE: # waiting to launch self.ball.left = self.paddle.left + self.paddle.width / 2 self.ball.top = self.paddle.top - self.ball.height self.show_message("Press space to launch the ball.") elif self.state == S_GAME_OVER: # game over - no more lives self.show_message("You lost...press enter to restart or esc to quit") elif self.state == S_WON: # game over - no more bricks self.show_message("Yay! You won. Press enter to play again! (or press esc to quit)") # Draw bricks, paddle, ball self.draw_bricks() pygame.draw.rect(self.screen, SEIZURE, self.paddle) pygame.draw.circle(self.screen, WHITE, (self.ball.left + BALL_RADIUS, self.ball.top + BALL_RADIUS), BALL_RADIUS) # Show the player statistics self.show_stats() # Finish the drawing process (flip drawing buffer) pygame.display.flip() ### MAIN if __name__ == '__main__': breakout = OUBreakout() breakout.run()
#python 3 userEntry = input() userAge = int(userEntry) if userAge > 18: print("Adult. Congrats.") elif (userAge > 10 and userAge <= 18): print("Teen. Rad, yo.") elif (userAge < 10): print("Child. Cool.")
import censusdata from gather_data import * import os import argparse parser = argparse.ArgumentParser() parser.add_argument('--search', action='store_true', help="To perform a search for variables") parser.add_argument('--get', action='store_true', help="To load variables data from the CENSUS data and store to csv") parser.add_argument('--store', action='store_true', help="To load data from csv into the database") args = parser.parse_args() if args.search: # to search for variables in CENSUS data vars = censusdata.search('acs5', 2018, 'label', 'race', tabletype='detail') print(f"Found {len(vars)} matching variables.") # prints all retrieved census data variables to file with open("search_results.txt", "w") as f: for v in vars: f.write(str(v)+"\n") if args.get: # to download the data from the CENSUS df = download_data('useful_variables.txt') # saves the retrieved data to a csv df.to_csv('data.csv', index=False) if args.store: table_name = "acs_upper_chamber_illinois" schema_name = "sketch" conn = open_db_connection() cur = conn.cursor() # creating schema schema_command = f"CREATE SCHEMA IF NOT EXISTS {schema_name};" print(schema_command) cur.execute(schema_command) # drop table if it exists already drop_command = f"DROP TABLE IF EXISTS {schema_name}.{table_name};" print(drop_command) cur.execute(drop_command) # creating table create_command = os.popen(f"cat data.csv | tr [:upper:] [:lower:] | tr ' ' '_' | sed 's/#/num/' | " + \ f"csvsql -i postgresql --db-schema {schema_name} --tables {table_name} ").read() print(create_command) cur.execute(create_command) # building primary index for table with open("data.csv", "r") as f: header = f.readlines()[0].split(",") if header[0] == 'state': keys = 'state' else: keys = 'us' if header[1] in ['county', 'state_legislative_district_upper_chamber', 'state_legislative_district_lower_chamber']: keys += f', {header[1]}' if header[2] == 'tract': keys += ', tract' if header[3] == 'block_group': keys += ", block_group" elif header[3] == 'block': keys += ', block' index_command = f"ALTER TABLE {schema_name}.{table_name} ADD PRIMARY KEY ({keys})" print(index_command) cur.execute(index_command) # copying data to table with open("data.csv", "r") as f: next(f) #ignore header cur.copy_from(f, f"{schema_name}.{table_name}", sep=',') # Close communication with the database cur.close() conn.commit() conn.close()
def rsum(list1): '''(list of int) -> int ''' # this will check if there only one item if len(list1) == 1: # thats the only sum result = list1[0] else: # recursilvy calls the list and adds them up result = list1[0] + rsum(list1[1:]) return(result) def rmax(list1): '''(list of int) -> int ''' # if there nothing the automatically makes it equal to 0 if (list1 == []): result = int(0) else: # checks to run if any inner list if isinstance(list1[0], list): max1 = rmax(list1[0]) else: # first part of list max1 = list1[0] # rest of list recursively left_max = rmax(list1[1:]) # compares if one greater than the other if (max1 > left_max): result = max1 else: result = left_max # returns the highest value return(result) def second_smallest(list1): '''(list of int) -> int ''' # finds min number min_num = rmin(list1) # base case only two elements if len(list1) == 2: if list1[0] > list1[1]: return(list1[0]) else: return(list1[1]) else: # recursivly calls until second ''' x = second_smallest(list1[1:]) y = list1[1] if min_val < x: if list1[1] < x: second_smallest = x else: second_smallest = -2 return(second_smallest) ''' x = -2 return(x) def sum_max_min(list1): ''' (list) -> int ''' # gets the maximum number max_val = rmax(list1) # gets the minimum number min_val = rmin(list1) # adds them up and returns result = max_val + min_val return(result) def rmin(list1): ''' HELPPER FUNCTION TO FIND THE MINIMUM NUMBER IN LIST ''' # if only one element if len(list1) == 1: return(list1[0]) else: # recursivley callls itself m = rmin(list1[1:]) # compares and set min val if m > list1[0]: min_val = list1[0] else: min_val = m return(min_val)
class Solution(object): def merge_sort(self,array): """ :type nums: List[int] ex:[3,2,-4,6,4,2,19],[5,1,1,2,0,0] :rtype: List[int] ex:[-4,2,2,3,4,6,19],[0,0,1,1,2,5] """ if len(array) <= 1: return array else: #####拆到只剩下一個,這裡是不耗時的 middle=len(array)//2 left_array=array[:middle] right_array=array[middle:] L=self.merge_sort(left_array) R=self.merge_sort(right_array) i=0 j=0 a=[] while i < len(L) and j < len(R): #####在左右陣列都還有東西的情況下 if L[i] <= R[j]: ####左右比完放入新的陣列 a.append(L[i]) i+=1 else: a.append(R[j]) j+=1 a+=L[i:]+R[j:] return a
import sys # Autor: Mailson Felipe # Data: 26/03/2021 def main(): padrao = input("Insira a string padrao (DDMMM:HHmm): ") flag = 0 dia = padrao[0]+padrao[1] mes = padrao[2]+padrao[3]+padrao[4] hora = padrao[06]+padrao[7] minutos = padrao[8]+padrao[9] if(len(dia) == 2): flag = 0; else: flag = 1 print('False') sys.exit() if(len(mes) == 3 and (mes == 'JAN' or mes == 'FEV' or mes == 'MAR' or mes == 'APR' or mes == 'MAY' or mes == 'JUN' or mes == 'JUL' or mes == 'AUG'or mes == 'SEP' or mes == 'OCT'or mes == 'NOV' or mes == 'DEC')): flag = 0 else: flag = 1; print('False') sys.exit() if (padrao[5] == ':'): flag = 0 else: flag = 1 print('False') sys.exit() if(len(hora) == 2): flag = 0 else: flag = 1 print('False') sys.exit() if (len(minutos) == 2): flag = 0 else: flag = 1 print('False') sys.exit() print('True') if __name__ == "__main__": main()
# Autor: Mailson Felipe # Data: 26/03/2021 def main(): data = input("Digite uma data no formato DD/MM/AAAA: ") dia = data.split('/')[0] mes = data.split('/')[1] ano = data.split('/')[2] auxDia = int(data.split('/')[0]) auxMes = int(data.split('/')[1]) if (auxDia < 1 or auxDia > 31): print('Dia invalido') return 0 elif(len(ano) != 4): print('Ano invalido') return 0 elif (auxMes < 1 and auxMes > 12): print('Mes invalido') return 0 if(mes == 1): mes = 'Janeiro' elif(mes == 2): mes = 'Fevereiro' elif(mes == 3): mes = 'Marco' elif(mes == 4): mes = 'Abril' elif(mes == 5): mes = 'Maio' elif(mes == 6): mes = 'Junho' elif(mes == 7): mes = 'Julho' elif(mes == 8): mes = 'Agosto' elif(mes == 9): mes = 'Setembro' elif(mes == 10): mes = 'Outubro' elif(mes == 11): mes = 'Novembro' elif(mes == 12): mes = 'Dezembro' print('Data: '+dia+' de '+mes+ ' de '+ano) if __name__ == "__main__": main() #'12/11/1212'
#!/usr/bin/env python # coding: utf-8 # In[3]: #1.Write a program in python to check whether a person is eligible for voting or not using if-else age=int(input("enter age : ")) if age >= 18 : print("eligible to vote") else: print("not eligible to vote") # In[4]: #2.Write a program in python to check whether a number is even or odd using if-else num = int(input("Enter a number: ")) if (num % 2) == 0: print("even") else: print("odd") # In[6]: #3.Write a program to print the string in reverse order by using string indexing s=("hello") a=s[::-1] print(a) # In[7]: #4.Write a python program to check whether a number is positive or not using if-else num = float(input("Enter a number: ")) if num >= 0: print("Positive number") else: print("Negative number") # In[8]: #5.Write a python program to find the roots of a quadratic equation using elif from math import sqrt print("Quadratic function : (a * x^2) + b*x + c") a = float(input("a: ")) b = float(input("b: ")) c = float(input("c: ")) r = b**2 - 4*a*c if r > 0: num_roots = 2 x1 = (((-b) + sqrt(r))/(2*a)) x2 = (((-b) - sqrt(r))/(2*a)) print("There are 2 roots: %f and %f" % (x1, x2)) elif r == 0: num_roots = 1 x = (-b) / 2*a print("There is one root: ", x) else: num_roots = 0 print("No roots, discriminant < 0.") exit() # In[9]: #6.Write a program in python using nested-if to check whether a number is positive or negative or zero num = float(input("Enter a number: ")) if num >= 0: if num == 0: print("Zero") else: print("Positive number") else: print("Negative number") # In[10]: #7.Write a program to accept a number(1-5) and print the given number in words x=int(input("accept a number ")) if x==1: print("ONE") elif x==2: print("TWO") elif x==3: print("THREE") elif x==4: print("FOUR") elif x==5: print("FIVE") else: print("the given number is not in 1-5") # In[11]: #8.Write a program in python to read a character and print the given character is vowel or consonant ch = input("Enter a character: ") if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I' or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'): print(ch, "is a Vowel") else: print(ch, "is a Consonant") # In[ ]:
# 객체변수 value가 100 이상의 값은 가질 수 없도록 제한하는 MaxLimitCalculator클래스 만들기 class Calculator: def __init__(self): self.value = 0 def add(self, val): self.value += val return self.value class MaxLimitCalculator(Calculator): def add(self, num): self.value += num if self.value >= 100: self.value = 100 return self.value cal = MaxLimitCalculator() cal.add(50) # 50더하기 cal.add(60) # 60더하기 print(f"\n한정된 두 수의 최대값: {cal.value}") # 100출력
import sys import csv # 목적: 열의 헤더를 사용하여 특정 열을 선택하기 # 열의 헤드명으로 검색하는 것은 새로운 열이 추가및 삭제 되었을 경우에 # input_file = sys.argv[1] # output_file = sys.argv[2] input_file = "supplier_data.csv" output_file = "./output_files/7csv_reader_column_by_name.csv" my_columns = ['Invoice Number', 'Purchase Date'] my_columns_index = [] with open(input_file, 'r', newline='') as csv_in_file: with open(output_file, 'w', newline='') as csv_out_file: filereader = csv.reader(csv_in_file) filewriter = csv.writer(csv_out_file) header = next(filereader) # print(header) for index_value in range(len(header)): if header[index_value] in my_columns: my_columns_index.append(index_value) filewriter.writerow(my_columns) for row_list in filereader: row_list_output = [] for index_value in my_columns_index: row_list_output.append(row_list[index_value]) # print(row_list_output) filewriter.writerow(row_list_output)
# coding: cp949 print("I eat %d apples."%3) # ˽Ʈ ٷ print str = " In addition, I eat %d bananas"%2 # Ʈ ڿ Ȯϴ ̽ print(str) number = 4 print("Further more, I eat %d mangoes" %number) number = "five" print("Moreover, I eat %s tangerine" % number) number = 0.25 print("At the end, I eat %s melon" %number) # %s ⺻ ڿ ִ. print("My Satisfaction Rate for the dessert is 98%") # ÿ %d % %% . print("My Satisfaction Rate for the dessert is %d%%"%98)
# 목적: 날짜 형식 할당 import pandas as pd # input_file = sys.argv[1] # output_file = sys.argv[2] input_file = 'sales_2013.xlsx' output_file = 'output_files/3output_pandas.xls' data_frame = pd.read_excel(input_file, sheet_name='january_2013') # 이동평균 열 추가 연습 # data_frame['Acc'] = data_frame['Sale Amount'].rolling(window=3).mean() # print(data_frame) # data_frame = data_frame[data_frame['Acc'] != 'Null'] # print(data_frame) writer = pd.ExcelWriter(output_file) data_frame.to_excel(writer, sheet_name='jan_13_output', index=False) writer.save()
import datetime import time day_time = time.strftime("%H%M", time.localtime(time.time())) print(day_time) print("==="*10) cur_time = datetime.datetime.now() cur_time = cur_time.strftime("%Y%m%d %H%M") ymd = cur_time.split(" ")[0] print(ymd) print(cur_time) print(cur_time.split(" ")[1]) # day_time = datetime.datetime.now().strftime("%H%M") # print(day_time) # yymmdd = day_time.strftime("%Y%m%d") # print(yymmdd) # cur_day = datetime.datetime.now() # print(cur_day) # yymmdd = cur_day.strftime("%Y%m%d") # print(yymmdd) # day_time = cur_day.strftime("%H%M") # print(HM) # cur_time_min = cur_day.strftime("%M") # # print(cur_time) # print(cur_time_min) # # print(cur_time) # # print(cur_day.strftime("%H%M")) # past_15 = cur_day - datetime.timedelta(minutes=15) # print(past_15)
# class Calculator를 상속하는 UpgradeCalculator를 만들고 값을 뺄 수 있는 minus메서드를 추가 class Calculator: def __init__(self): self.value = 0 def add(self, val): self.value += val return self.value class UpgradeCalculator(Calculator): def minus(self, val): self.value -= val return self.value cal = UpgradeCalculator() cal.add(10) cal.minus(7) print(f"\n상속후 minus메서드 추가한 결과: {cal.value}")
import sys # csv모듈 없이 파이썬 기본으로 파일읽고, 쓰기 # input_file = sys.argv[1] # output_file = sys.argv[2] input_file = "supplier_data.csv" output_file = "./output_files/1output_index_false.csv" with open(input_file, 'r', newline='') as filereader: with open(output_file, 'w', newline='') as filewriter: header = filereader.readline() # 한줄읽고, header = header.strip() # \n제거 header_list = header.split(',') print(header_list) filewriter.write(','.join(map(str, header_list))+'\n') # 원본과 동일한 상태로 저장 for row in filereader: # print(len(row)) row = row.strip() # \n제거, 길이가 -2, # print(len(row)) row_list = row.split(',') print(row_list) filewriter.write(','.join(map(str,row_list))+'\n')
# Enter your code here. Read input from STDIN. Print output to STDOUT size1 = int(input()) li1 = list(map(int, input().split())) size2 = int(input()) li2 = list(map(int, input().split())) final_list = [] for i in li1: if i not in li2 and i not in final_list: final_list.append(i) for i in li2: if i not in li1 and i not in final_list: final_list.append(i) final_list.sort() for i in final_list: print(i)
# Enter your code here. Read input from STDIN. Print output to STDOUT size = int(input()) details = {} for i in range(size): s = input() price = int(s.split(" ")[-1]) ss = s.split(" ") name = " ".join(ss[:len(ss) - 1]) if name not in details: details[name] = price else: details[name] = details.get(name) + price for key, value in details.items(): print(key, value)
import random from Chromosome import Chromosome def single_point(parents): """Single point crossover. Creates a new Chromosome by combining the genes of both parents. A crossover point is found and the crossover is performed as follows: Parent A genes: AAAA AAAA Crossover point: ↕ Parent B genes: BBBB BBBB ========= Child: AAAA BBBB Arguments: parents {[Chromosome]} -- A list containing two Chromosomes from which the genes will be taken. Returns: Chromosome -- The baby made from the two parents. """ parents.sort(key=lambda chromo: len(chromo.genes)) crossover_point = random.randint(0, len(parents[0].genes)-1) genes = parents[0].genes[:crossover_point] + parents[1].genes[crossover_point:] return Chromosome(genes)
a = [5,1,1,19,29,2,0,0, 3, 34,23] def qsort(arry, low, high): left = low right = high key = arry[low] while low<high: while right >= key: right -= 1 arry[low] = arry[right] while left < low: left += 1 arry[high] = arry[left] arry[left] = key #1111 print(123)
'''Maximum of two number in python''' def maximum(a,b): if a>=b: print(a) else: print(b) a = 12 b = 14 print(maximum(a,b)) ''' Python program to find the maximum of two number using max function''' a = 14 b = 16 print(max(a,b)) c = 70 d = 90 maximum = max(c,d) print(maximum) #Ternary Method a = 2 b = 4 print(a if a>=b else b)
""" """ class Contact(object): def __init__(self,name,hpnum,email,age): self.name = name self.hpnum = hpnum self.email = email self.age = age def to_string_(self): return self.name + ";" + self.hpnum + ";" \ + self.email + ";" + str(self.age) if __name__ == "__main__": print("실행 모듈이 아닙니다")
import random import copy class Graph(object): class Edge(object): def __init__(self, source, destination, weight): """ DO NOT EDIT! Class representing an Edge in a graph :param source: Vertex where this edge originates :param destination: Vertex where this edge ends :param weight: Value associated with this edge """ self.source = source self.destination = destination self.weight = weight self.explored = False def __eq__(self, other): return self.source == other.source and self.destination == other.destination def __repr__(self): return f"Source: {self.source} Destination: {self.destination} Weight: {self.weight}" __str__ = __repr__ class Path(object): def __init__(self, vertices=list(), weight=0): """ DO NOT EDIT! Class representing a path in a graph :param vertices: Ordered list of vertices that compose the path :param weight: Total weight of the path """ self.vertices = vertices self.weight = weight def __eq__(self, other): return self.vertices == other.vertices and self.weight == other.weight def __repr__(self): return f"Weight:{self.weight} Path: {' -> '.join([str(v) for v in self.vertices])}\n" __str__ = __repr__ def add_vertex(self, vertex): """ Add a vertex id to the path :param vertex: id of a vertex :return: None """ self.vertices.append(vertex) def add_weight(self, weight): """ Add weight to the path :param weight: weight :return: None """ self.weight += weight def remove_vertex(self): """ Remove the most recently added vertex from the path :return: None """ if not self.is_empty(): self.vertices.pop() def remove(self, w): if not self.is_empty(): self.vertices.pop() self.weight -= w def add(self, vid, w): self.vertices.append(vid) self.weight += w def is_empty(self): """ Check if the path object is empty :return: True if empty, False otherwise """ return len(self.vertices) == 0 class Vertex(object): def __init__(self, number): """ Class representing a vertex in the graph :param number: Unique id of this vertex """ self.edges = [] self.id = number self.visited = False def __repr__(self): return f"Vertex: {self.id}" __str__ = __repr__ def add_edge(self, destination, weight): self.edges.append(Graph.Edge(self.id, destination, weight )) def degree(self): return len(self.edges) def get_edge(self, destination): found = False i = 0 while not found and i < len(self.edges): if self.edges[i].destination == destination: found = True else: i += 1 return self.edges[i] if found else None def clear(self): self.visited = False for edge in self.edges: edge.explored = False def get_edges(self): return self.edges def generate_edges(self): """ DO NOT EDIT THIS METHOD Generates directed edges between vertices to form a DAG :return: List of edges """ random.seed(10) edges = [] for i in range(self.size): for j in range(i + 1, self.size): if random.randrange(0, 100) <= self.connectedness * 100: edges.append([i, j, random.randint(-10, 50)]) return edges def __init__(self, size=0, connectedness=0): """ DO NOT EDIT THIS METHOD Construct a random DAG :param size: Number of vertices :param connectedness: Value from 0 - 1 with 1 being a fully connected graph """ assert connectedness <= 1 self.adj_list = {} self.size = size self.connectedness = connectedness self.construct_graph() def construct_graph(self): for source, dest, weight in self.generate_edges(): self.adj_list[source] = self.adj_list.get(source, self.Vertex(source)) self.adj_list[dest] = self.adj_list.get(dest, self.Vertex(dest)) self.adj_list[source].add_edge(dest, weight) self.size = len(self.adj_list) def vertex_count(self): return self.size def vertices(self): return list(self.adj_list.values()) def insert_edge(self, source, dest, weight): self.adj_list[source] = self.adj_list.get(source, self.Vertex(source)) self.adj_list[dest] = self.adj_list.get(dest, self.Vertex(dest)) self.adj_list[source].add_edge(dest, weight) def clear(self): for v in self.adj_list.values(): v.clear() def preprocess(self,vertex): return list(edge for edge in vertex.get_edges() if not edge.explored) def find_valid_paths(self, source, dest, limit): # DFS stack = [self.Edge(None, source, 0)] paths = [] path = self.Path() while stack: update = False edge= stack[-1] vertex = self.adj_list[edge.destination] if len(path.vertices) and path.vertices[-1] == vertex.id: update = True else: path.add(vertex.id, edge.weight) final = vertex.get_edge(dest) if final: final.explored = True path.add(dest , final.weight) if path.weight <= limit: paths.append(self.Path(path.vertices[:], path.weight)) path.remove(final.weight) children = self.preprocess(vertex) if children: stack.extend(children) else: update = True if update: edge.explored = True path.remove(edge.weight) stack.pop() vertex.clear() return paths def find_shortest_path(self, source, destination, limit): paths = self.find_valid_paths(source, destination, limit) return min(paths , key =lambda p: p.weight ) def find_longest_path(self, source, destination, limit): paths = self.find_valid_paths(source, destination, limit) return max(paths , key =lambda p: p.weight ) def find_most_vertices_path(self, source, destination, limit): paths = self.find_valid_paths(source, destination, limit) return max(paths , key =lambda p: len(p.vertices) ) def find_least_vertices_path(self, source, destination, limit): paths = self.find_valid_paths(source, destination, limit) return min(paths , key =lambda p: len(p.vertices) ) def check_path(self, path): summ = 0 for i in range(len(path.vertices)-1): summ += self.adj_list[path.vertices[i]].get_edge(path.vertices[i +1]).weight print( self.adj_list[path.vertices[i]].get_edge(path.vertices[i +1])) return f" Real Weight: {summ}"
''' Scaffolding code for the Machine Learning assignment. You should complete the provided functions and add more functions and classes as necessary. You are strongly encourage to use functions of the numpy, sklearn and tensorflow libraries. You are welcome to use the pandas library if you know it. ''' # Scikit-Learn ≥0.20 is required import sklearn assert sklearn.__version__ >= "0.20" # Common imports import numpy as np # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def my_team(): ''' Return the list of the team members of this assignment submission as a list of triplet of the form (student_number, first_name, last_name) ''' return [ (9879120, 'Payagalagae', 'Fernando'), (9860665, 'Manavdeep', 'Signh') ] # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def prepare_dataset(dataset_path): ''' Read a comma separated text file where - the first field is a ID number - the second field is a class label 'B' or 'M' - the remaining fields are real-valued Return two numpy arrays X and y where - X is two dimensional. X[i,:] is the ith example - y is one dimensional. y[i] is the class label of X[i,:] y[i] should be set to 1 for 'M', and 0 for 'B' @param dataset_path: full path of the dataset text file @return X,y ''' #A seperate extraction is done to ensure that the string is extractable mydatastring=np.genfromtxt(dataset_path,delimiter=",",dtype="U1") #Another array is created to extract data in the float64 data type mydata=np.genfromtxt(dataset_path,delimiter=",") #Conduting the appropriate array slicing #X is a 2D array that includes respective attributes excluding the ID number X=mydata[:,2:] #y is a one dimensional array containing the classes M or B y=mydatastring[:,1] #Converting M-->1 B-->0 for i in range(len(y)): if y[i]=="M": y[i]=1 else: y[i]=0 y = y.astype(np.float) return X,y # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def build_DecisionTree_classifier(X_training, y_training): ''' Build a Decision Tree classifier based on the training set X_training, y_training. @param X_training: X_training[i,:] is the ith example y_training: y_training[i] is the class label of X_training[i,:] @return clf : the classifier built in this function ''' ## "INSERT YOUR CODE HERE" from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier # Create Decision Tree classifer object clf = DecisionTreeClassifier() # Train Decision Tree Classifer clf=DecisionTreeClassifier(criterion = "gini") clf = clf.fit(X_training,y_training) return clf raise NotImplementedError() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def build_NearrestNeighbours_classifier(X_training, y_training): ''' Build a Nearrest Neighbours classifier based on the training set X_training, y_training. @param X_training: X_training[i,:] is the ith example y_training: y_training[i] is the class label of X_training[i,:] @return clf : the classifier built in this function ''' ## "INSERT YOUR CODE HERE" raise NotImplementedError() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def build_SupportVectorMachine_classifier(X_training, y_training): ''' Build a Support Vector Machine classifier based on the training set X_training, y_training. @param X_training: X_training[i,:] is the ith example y_training: y_training[i] is the class label of X_training[i,:] @return clf : the classifier built in this function ''' ## "INSERT YOUR CODE HERE" raise NotImplementedError() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def build_NeuralNetwork_classifier(X_training, y_training): ''' Build a Neural Network with two dense hidden layers classifier based on the training set X_training, y_training. Use the Keras functions from the Tensorflow library @param X_training: X_training[i,:] is the ith example y_training: y_training[i] is the class label of X_training[i,:] @return clf : the classifier built in this function ''' ## "INSERT YOUR CODE HERE" raise NotImplementedError() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if __name__ == "__main__": pass # Write a main part that calls the different # functions to perform the required tasks and repeat your experiments. X,y=prepare_dataset('medical_records.data'); def optimal_Max_branch_DT(): ''' Plots graphs and demonstrates the nature in which the optimal value of man_branch have been obtained for a Decision Tree Classifier. @param X_training: X_training[i,:] is the ith example raining: y_training[i] is the class label of X_training[i,:] @return clf : the classifier built in this function ''' from sklearn.model_selection import train_test_split ratio_train, ratio_test = 0.8 , 0.2 #Creating the training data set 80% of the data X_training, X_testandVal, y_training, y_testandVal = train_test_split(X, y, train_size=ratio_train,test_size=ratio_test, shuffle=False) #The validation and testing sets are created #from th remaining 20% by splitting that in to two 10% parts test_ratio=0.5 X_validation,X_test,y_validation,y_test=train_test_split(X_testandVal,y_testandVal,test_size=test_ratio,shuffle=False) # call your functions here clf=build_DecisionTree_classifier(X_training, y_training) #Predict the response for test dataset y_pred = clf.predict(X_test) from sklearn.model_selection import cross_val_score print(cross_val_score(clf, X_training, y_training, cv=3, scoring="accuracy")) #Tuning the max_depth hyper parameter for the decision tree classifier #The area under the curve will be used as a metric since this is a binary #classification problem from sklearn.metrics import roc_curve, auc false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, y_pred) roc_auc = auc(false_positive_rate, true_positive_rate) #Creating an array of max_depths to loop through to find #optimal hyper parameter max_depths = np.linspace(1, 30, 30) training_results = [] testing_results = [] testing_meanScoreresults = [] training_meanScoreresults = [] cross_Vals=[] from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import cross_val_score #Iterating through max_depths array to find the optimal value of max_depth for i in max_depths: dt = DecisionTreeClassifier(max_depth=i) #Building the classifier from the training data sets dt.fit(X_training, y_training) #Predicting the response of training data set train_pred = dt.predict(X_training) #A Reciever Operating Characteristic Curve is computed false_positive_rate, true_positive_rate, thresholds = roc_curve(y_true=y_training,y_score=train_pred) #Area under the Reciever Operating Characteristic Curve is computed from the #prediction scores roc_auc = auc(false_positive_rate, true_positive_rate) # Add auc score to previous train results training_results.append(roc_auc) #Predicting the response of the test data set y_pred = dt.predict(X_test) #A Reciever Operating Characteristic Curve is computed from the result of # false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, y_pred) #Area under the Reciever Operating Characteristic Curve is computed from the #prediction scores roc_auc = auc(false_positive_rate, true_positive_rate) # Add auc score to previous test results testing_results.append(roc_auc) #Getting Mean Score Results for Training #This is the mean accuracy on the given test data and labels #Training data and Training labels l=dt.score(X_training, y_training) training_meanScoreresults.append(l) #Getting Mean Score Results for Testing #This is the mean accuracy on the given training data and labels #Testing data and Testing labels s=dt.score(X_test, y_test) testing_meanScoreresults.append(s) #Obtain cross_val_score for DecisionTree classifier with max_depth=i crossvals=cross_val_score(dt, X_training, y_training, cv=5,scoring='accuracy') #Appending the mean score to the scores list cross_Vals.append(crossvals.mean()) import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerLine2D #Plotting the the respective areas under the curve line1, = plt.plot(max_depths, training_results, 'b', label='Train AUC') line2, = plt.plot(max_depths, testing_results, 'r', label='Test AUC') plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)}) plt.ylabel('Score') plt.xlabel('Tree depth') plt.show() #Plotting the the respective mean score results line3, = plt.plot(max_depths, testing_meanScoreresults, 'g', label='Testing Mean Score Results') line4, = plt.plot(max_depths, training_meanScoreresults, 'y', label='Training Mean Score Results') plt.legend(handler_map={line3: HandlerLine2D(numpoints=2)}) plt.ylabel('Mean Accuracy Score') plt.xlabel('Tree depth') plt.show() #Plotting the the mean cross valuation score as tree depth changes line5,= plt.plot(max_depths,cross_Vals,'c',label='Mean Cross Val Score') plt.legend(handler_map={line5: HandlerLine2D(numpoints=1)}) plt.ylabel('Cross Validated Accuracy Score') plt.xlabel('Tree depth') plt.show() #We decicde that the optimal hyper parameter for this instance is max_depth=5 #Creating the classifier with above said hyper parameter dt_optimal = DecisionTreeClassifier(max_depth=5) #Building the classifier from the training data sets dt_optimal.fit(X_training,y_training) #should I use X_test or X_validation????? #Predicting the class for X y_pred_optimal=dt_optimal.predict(X_validation) from sklearn.metrics import accuracy_score #Computing the accuracy score by comparing the predicted set #with the validation set print ("Accuracy is", accuracy_score(y_validation,y_pred_optimal)*100)
import time def factorial(N) : fac = 1 for i in range(1,N+1) : fac*=i return fac def main() : n = 50000 k = 50000 j = 50000 start = time.time() results = [factorial(n),factorial(j),factorial(k)] print ("time 1 = %s"%(time.time()-start)) if __name__ == '__main__': main()
from functools import wraps def decorator(func): @wraps(func) def wraper(*args, **kwargs): print(type(args), args) print(type(kwargs), kwargs) print('hey, you') ret = func(*args, **kwargs) print('processing', ret) print('ok, done') return ret return wraper @decorator def fun1(x, y, extraneous=1): return x+y @decorator def fun2(x, y, extraneous=2): return x-y print('result:', fun1(1,2)) print('result:', fun2(1,2))
def getIndexOf(s, m): if s == None or m == None or len(m)< 1 or len(s)<len(m): return -1 str1 = list(s) str2 = list(m) x = 0 # str1中比对到的位置 y = 0 # str2中比对到的位置 next_list = getNextArray(str2) # 这个next_list既表示长度,也表示你该往哪儿跳 while x < len(str1) and y< len(str2): # 跳出while的条件,要么x越界,要么y越界。y越界说明找到了,x越界说明没找到 if str1[x] == str2[y]: x += 1 y += 1 elif next_list[y] == -1: x += 1 else: y = next_list[y] return x-y if y == len(str2) else -1 def getNextArray(ms): if len(ms) == 1: return [-1] next_list = [None]*len(ms) next_list[0] = -1 next_list[1] = 0 i = 2 cn = 0 # cn位置,是当前和i-1位置比较的字符 while i < len(next_list): if ms[i-1] == ms[cn]: cn += 1 next_list[i] = cn i += 1 elif cn>0: cn = next_list[cn] else: next_list[i] = 0 i+= 1 return next_list if __name__ == "__main__": s = 'abacabxfabacabaE' print(getNextArray(s)) s1 = 'abacaaabcsexaaas' s2 = 'abcs' print(getIndexOf(s1,s2))
def LeftToRight(N: int): """ N层汉诺塔从左到右的过程 """ if N == 1: print("Move 1 From Left to Right.") return else: LeftToMid(N-1) print("Move %d from Left to Right." % N) MidToRight(N-1) def LeftToMid(N): if N == 1: print("Move 1 From Left to Mid") return else: LeftToRight(N-1) print("Move %d from Left to Mid" % N) RightToMid(N-1) def MidToRight(N): if N == 1: print("Move 1 From Mid to Right") return else: MidToLeft(N-1) print("Move %d from Mid to Right" % N) LeftToRight(N-1) def RightToMid(N): if N == 1: print("Move 1 From Right to Mid") return else: RightToLeft(N-1) print("Move %d from Right to Mid" % N) LeftToMid(N-1) def MidToLeft(N): if N == 1: print("Move 1 From Mid to Left") return else: MidToRight(N-1) print("Move %d from Mid to Left" % N) RightToLeft(N-1) def RightToLeft(N): if N == 1: print("Move 1 From Right to Left") return else: RightToMid(N-1) print("Move %d from Right to Left" % N) MidToLeft(N-1) if __name__ == "__main__": LeftToRight(3)
def divide(arr, num): flag = -1 for i in range(len(arr)): if arr[i]<= num: arr[flag+1], arr[i] = arr[i], arr[flag+1] flag += 1 else: pass if __name__ == "__main__": arr = [1,5,2,3,5,2,1,6] divide(arr,2) print(arr)
class UnionFindSet: def __init__(self, value_list): self.elementMap = {} # 点和节点的对应关系,相当于一个注册表 self.fatherMap = {} # 父节点对映关系 self.sizeMap = {} # sizeMap中每一个key都是集合的头节点,也叫做代表节点 for v in value_list: element = Element(v) self.elementMap[v] = element self.fatherMap[element] = element self.sizeMap[element] = 1 def getSizeNum(self): return len(self.sizeMap) def findHead(self, element): # 从element出发,找到不能再网上的头节点 # 把网上找沿途的路径全都记录下来 path = [] while element != self.fatherMap[element]: path.append(element) element = self.fatherMap[element] while path: self.fatherMap[path.pop()] = element return element def isSameSet(self, a, b): if a in self.elementMap and b in self.elementMap: return self.findHead(self.elementMap.get(a)) == self.findHead(self.elementMap.get(b)) def union(self, a, b): if a in self.elementMap and b in self.elementMap: aF = self.findHead(self.elementMap.get(a)) bF = self.findHead(self.elementMap.get(b)) if aF != bF: big = aF if self.sizeMap.get(aF) >= self.sizeMap.get(bF) else bF small = bF if big == aF else aF self.fatherMap[small] = big self.sizeMap[big] = self.sizeMap[aF] = self.sizeMap[bF] del self.sizeMap[small] class Element: def __init__(self, value): self.value = value if __name__ == "__main__": a = UnionFindSet([1,2,4,5,3])
from 大根堆的heapify import heapify def popmax(arr, heap_size): """ 找到最大值返回,并删掉该值 """ t = arr[0] arr[0] = arr[heap_size-1] heap_size -= 1 heapify(arr, 0, heap_size) return t if __name__ == "__main__": a = [8,7,5,6,4,3] heap_size = len(a) print(a[:heap_size]) print(popmax(a,len(a))) heap_size-=1 print(a[:heap_size])
class Program: def __init__(self, start, end): self.start = start self.end = end def __lt__(self, other): return self.end < other.end def bestArrange(programs, timePoint ): programs.sort() ret = 0 for program in programs: if timePoint <= program.start: ret += 1 timePoint = program.end return ret if __name__ == "__main__": p = [] p.append(Program(6, 12)) p.append(Program(7, 8)) p.append(Program(8, 9)) p.sort() print(bestArrange(p,0))
class Solution: def rotate(self, nums, k): """ Do not return anything, modify nums in-place instead. """ length =len(nums) t = k%length for i in range(t): nums.insert(0,nums.pop()) def rotate1(self, nums, k): """ Do not return anything, modify nums in-place instead. """ length =len(nums) t = k%length for i in range(t): pre = nums[length-1] for j in range(length): temp = nums[j] nums[j] = pre pre = temp def rotate2(self, nums, k): """ 环状替换 """ length =len(nums) t = k%length count = 0 for i in range(length): current = i pre = nums[i] if count == length: break while 1: next1 = (current +t) % length temp = nums[next1] nums[next1] = pre pre = temp current = next1 count += 1 if i == current : break if __name__ == '__main__': a =Solution() nums =[1,2,3,4,5,6,7] print(nums) a.rotate2(nums,3) print(nums)
def heapify(arr, index, heapSize): """ 查看index是否能够下沉 """ left = index *2+1 while left<heapSize: largest = left+1 \ if left+1 < heapSize and arr[left+1] > arr[left] else left largest = largest if arr[largest] > arr[index] else index if largest == index: break arr[index],arr[largest] = arr[largest] , arr[index] index = largest left = index *2 +1 if __name__ == "__main__": a = [5,9,8,4,6] print(a) heapify(a, 0, 5) print(a)
class Solution: def arrangeCoins1(self, n: int) -> int: i = 1 count = 0 while n>=0: n -= i count += 1 i += 1 if n<0: count -= 1 return count def arrangeCoins(self, n: int) -> int: # i = 1 count = 0 while n>=0: n -= count count += 1 # i += 1 count -= 1 if n<0: count -= 1 return count if __name__ == "__main__": a = Solution() print(a.arrangeCoins(8))
from 链表类 import ListNode class Solution: def getIntersectionNode1(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: return node_a = headA node_b = headB len_a = 1 while node_a.next: len_a += 1 node_a = node_a.next len_b = 1 while node_b.next: len_b += 1 node_b = node_b.next node_a = headA node_b = headB while len_a >len_b: node_a = node_a.next len_a -= 1 while len_b >len_a: node_b = node_b.next len_b -= 1 while node_a: if node_a is node_b: return node_a else: node_a = node_a.next node_b = node_b.next return def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: ha, hb = headA, headB while ha != hb: ha = ha.next if ha else headB hb = hb.next if hb else headA return ha if __name__ == "__main__": a = Solution()
class Solution: def lengthOfLastWord(self, s: str) -> int: if not s: return 0 len_s = len(s) start = len_s-1 while not ( (s[start] >= 'A' and s[start] <='Z') or (s[start] >= 'a' and s[start] <='z') ): start -= 1 if start <0: return 0 for i in range(start,-1,-1): if s[i] == ' ': return start -i return start+1 if __name__ == "__main__": a = Solution() # print(a.lengthOfLastWord('Hello World')) print(a.lengthOfLastWord(' '))
class RandomPool: def __init__(self): self.keyIndexMap = {} self.indexKeyMap = {} self.size = 0 def insert(self, key): if not key in self.keyIndexMap: self.keyIndexMap[key] = self.size self.indexKeyMap[self.size] = key self.size += 1 def delete(self, key): if key in self.keyIndexMap: deleteIndex = self.keyIndexMap[key] self.size -= 1 lastIndex = self.size lastKey = self.indexKeyMap[lastIndex] self.keyIndexMap[lastKey] = deleteIndex self.indexKeyMap[deleteIndex] = lastKey del self.keyIndexMap[key] del self.indexKeyMap[lastIndex] def getRandom(self): import random if self.size == 0: return None randomIndex = int(random.random()*self.size) # 0~size-1 return self.indexKeyMap[randomIndex] if __name__ == "__main__": d = RandomPool() d.insert("123") d.insert("345") print(d.getRandom()) print(d.getRandom()) print(d.getRandom()) print(d.getRandom()) print(d.getRandom()) print(d.getRandom()) print('='*10) d.delete("123") print(d.getRandom()) print(d.getRandom()) print(d.getRandom()) print(d.getRandom()) print(d.getRandom()) print(d.getRandom())
class Solution: def findWords(self, words): """ 给定一个单词列表,返回可以用同一行字母打印的单词 """ l= ['qwertyuiop','asdfghjkl','zxcvbnm'] ret=[] for word in words: for line in l: found = True for c in word.lower(): if c not in line: found = False break if found == True: ret.append(word) break return ret if __name__ == "__main__": print(Solution().findWords(['Hello','Alska','Dad','Peace']))
class Solution: def countPrimes1(self, n: int) -> int: if n<=2: return 0 if n == 3: return 1 count = 1 l = [2] for m in range(3,n): Flag = True for j in range((len(l))): if m % l[j] == 0: Flag = False break if Flag: count +=1 l.append(m) print(l) return count def countPrimes(self,n): """ 求n以内的所有质数个数(纯python代码) """ # 最小的质数是 2 if n < 2: return 0 isPrime = [1] * n isPrime[0] = isPrime[1] = 0 # 0和1不是质数,先排除掉 # 埃式筛,把不大于根号n的所有质数的倍数剔除 for i in range(2, int(n ** 0.5) + 1): if isPrime[i]: isPrime[i * i:n:i] = [0] * ((n - 1 - i * i) // i + 1) return sum(isPrime) if __name__ == "__main__": a = Solution() print(a.countPrimes(100))
from 链表类 import ListNode class Solution: def middleNode(self, head: ListNode) -> ListNode: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow if __name__ == "__main__": a = Solution() l = ListNode([1,2,3,4,5]) print(a.middleNode(l))
class Solution: def maxCount(self, m: int, n: int, ops) -> int: """ 在执行给定的一系列操作后,你需要返回矩阵中含有最大整数的元素个数。 """ min_x = m min_y = n for op in ops: min_x = min(min_x, op[0]) min_y = min(min_y, op[1]) return min_x * min_y if __name__ == "__main__": m = 3 n = 3 operations = [ [2,2], [3,3] ] print(Solution().maxCount(m,n, operations))
def divide(arr, num): l_arr = -1 r_arr = len(arr) i = 0 while i<r_arr: if arr[i]< num: arr[l_arr+1], arr[i] = arr[i], arr[l_arr+1] l_arr += 1 i+=1 elif arr[i] == num: i+=1 else: arr[r_arr-1], arr[i] = arr[i], arr[r_arr-1] r_arr -= 1 if __name__ == "__main__": arr = [1,5,2,3,5,2,1,6] divide(arr,5) print(arr)
def heapSort(arr, asec=1, order_fun=lambda x: x): if not arr and len(arr)<2: return for i in range(len(arr)-1, -1,-1): heapify(arr,i,len(arr), asec, order_fun=order_fun) heap_size = len(arr) arr[0], arr[heap_size-1] = arr[heap_size-1], arr[0] heap_size -= 1 while heap_size>0: heapify(arr, 0, heap_size, asec, order_fun=order_fun) arr[0], arr[heap_size-1] = arr[heap_size-1], arr[0] heap_size -= 1 def heapify(arr, index, arr_size, asec, order_fun=lambda x: x): factor = 1 if asec==0 else -1 left = index * 2+1 while left<arr_size: if left+1<arr_size and factor* order_fun(arr[left+1]) < factor*order_fun(arr[left]): smallest = left+1 else: smallest = left if factor* order_fun(arr[index]) > factor* order_fun(arr[smallest]): arr[index], arr[smallest] = arr[smallest], arr[index] index = smallest left = index*2+1 else: break if __name__ == "__main__": a = [3,9,2,6,7,4,2,1] print(a) heapSort(a, asec = 1) print(a)
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # def process(head): # if head == None: # return # # 1 # # 先序 print(head.val) # process(head.left) # # 2 # # 中序 print(head.val) # process(head.right) # # 后序 print(head.val) # # 3 def morris(head): if head == None: return cur = head mostRight = None while cur != None: mostRight = cur.left if mostRight != None: while mostRight.right != None and mostRight.right != cur: mostRight = mostRight.right if mostRight.right == None: # d mostRight.right = cur cur = cur.left continue else: mostRight.right = None cur = cur.right def morrisPre(head): if head == None: return cur = head mostRight = None while cur != None: mostRight = cur.left if mostRight != None: # 可以来到自己两次的节点 while mostRight.right != None and mostRight.right != cur: mostRight = mostRight.right if mostRight.right == None: print(cur.val) mostRight.right = cur cur = cur.left continue else: mostRight.right = None else: # 只能来到自己一次的节点 print(cur.val) cur = cur.right def morrisIn(head): # 中序遍历 if head == None: return cur = head mostRight = None while cur != None: mostRight = cur.left if mostRight != None: # 可以来到自己两次的节点 while mostRight.right != None and mostRight.right != cur: mostRight = mostRight.right if mostRight.right == None: mostRight.right = cur cur = cur.left continue else: print(cur.val) mostRight.right = None else: # 只能来到自己一次的节点 print(cur.val) cur = cur.right def morrisPos(head): # 后序遍历 if head == None: return cur = head mostRight = None while cur != None: mostRight = cur.left if mostRight != None: # 可以来到自己两次的节点 while mostRight.right != None and mostRight.right != cur: mostRight = mostRight.right if mostRight.right == None: mostRight.right = cur cur = cur.left continue else: mostRight.right = None printEdge(cur.left) else: # 只能来到自己一次的节点 pass cur = cur.right printEdge(head) def printEdge(head): """ 以head为头的树,逆序打印该树右边界 """ tail = reverseEdge(head) cur = tail while cur != None: print(cur.val) cur = cur.right reverseEdge(tail) def reverseEdge(fromNode): preNode = None nextNode = None while fromNode != None: nextNode = fromNode.right fromNode.right = preNode preNode = fromNode fromNode = nextNode return preNode if __name__ == "__main__": b = TreeNode(1) b.left = None b.right = TreeNode(2) b.right.left = TreeNode(3) b.right.right = TreeNode(4) b.right.left.left = TreeNode(5) from 二叉树_打印二叉树 import printTree printTree(b) from 二叉树的前序遍历 import Solution ans = Solution().preorderTraversal(b) print(ans) morrisPre(b) from 二叉树的中序遍历 import Solution ans = Solution().inorderTraversal(b) print(ans) morrisIn(b) from 二叉树的后序遍历 import Solution ans = Solution().postorderTraversal(b) print(ans) morrisPos(b)
from queue import PriorityQueue import heapq class KthLargest: def __init__(self, k: int, nums): self.h = nums[:] self.k = k # self.pq = PriorityQueue(maxsize=k) # for i in nums: # self.addpq(i) heapq.heapify(self.h) k1 = len(nums)-k while k1>0: heapq.heappop(self.h) k1 -= 1 def add(self, val: int) -> int: if len(self.h) < self.k: heapq.heappush(self.h, val) ret = heapq.heappop(self.h) heapq.heappush(self.h, ret) return ret temp = heapq.heappop(self.h) if temp < val: heapq.heappush(self.h, val) ret = heapq.heappop(self.h) heapq.heappush(self.h, ret) return ret heapq.heappush(self.h, temp) return temp # def addpq(self, val: int) -> int: # if len(self.h) < self.k: # return val # else: # temp = heapq.heappop(self.h) # if temp < val: # pass # # heapq.heappush(self.h) # return None if __name__ == "__main__": k = 3 l = [4,5,8,2] kthLargest = KthLargest(k, l) print(kthLargest.add(3)) # returns 4 print(kthLargest.add(5)) # returns 5 print(kthLargest.add(10)) # returns 5 print(kthLargest.add(9)) # returns 8 print(kthLargest.add(4)) # returns 8
class Node: def __init__(self, p, c): self.p = p self.c = c class NodeP(Node): def __lt__(self, other): return other.p < self.p class NodeC(Node): def __lt__(self, other): return self.c < other.c def findMaximizedCapital(k, W, profits, capital): from queue import PriorityQueue minCostq = PriorityQueue() maxProfitQ = PriorityQueue() for p,c in zip(profits, capital): minCostq.put(NodeC(p,c)) for i in range(k): while (not minCostq.empty()): temp = minCostq.get() if temp.c > W: minCostq.put(temp) break maxProfitQ.put(NodeP(temp.p, temp.c)) if maxProfitQ.empty(): return W temp = maxProfitQ.get().p print(temp) W += temp return W if __name__ == "__main__": k = 3 W = 2 profits =[5,1,7,9,400] capital = [3,7,1,6,100] print(findMaximizedCapital(k,W, profits, capital))
from 用列表实现栈 import MyStack class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.stack = MyStack() self.helper = MyStack() def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.stack.push(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ while not self.stack.empty(): self.helper.push(self.stack.pop()) ret = self.helper.pop() while not self.helper.empty(): self.stack.push(self.helper.pop()) return ret def peek(self) -> int: """ Get the front element. """ while not self.stack.empty(): self.helper.push(self.stack.pop()) ret = self.helper.top() while not self.helper.empty(): self.stack.push(self.helper.pop()) return ret def empty(self) -> bool: """ Returns whether the queue is empty. """ return self.stack.empty() def __str__(self) -> str: """ Returns whether the queue is empty. """ return self.stack.__str__() if __name__ == "__main__": queue = MyQueue() queue.push(1) queue.push(2) queue.push(3) print(queue) queue.pop() print(queue) print(queue.peek()) queue.push(4) print(queue) print(queue.empty())
from 二叉树类 import TreeNode class Solution: def invertTree(self, root: TreeNode) -> TreeNode: def helper(root): if not root: return None root.left, root.right =helper(root.right), helper(root.left) return root return helper(root) if __name__ == "__main__": a = Solution() t = TreeNode([4,2,7,1,3,6,9]) ret = a.invertTree(t) ret._print()
class Solution: def intersect(self, nums1, nums2) : ret = [] for i in nums1: if i in nums2: ret.append(i) nums2.pop(nums2.index(i)) return ret if __name__ == "__main__": a = Solution() print(a.intersect([1,2,2,1,3], [2,3,3]))
import nltk from nltk import sent_tokenize from nltk import word_tokenize from nltk.stem import WordNetLemmatizer text = "I love Python Programming Language. I love to work with it. It is very easy to all for all ages peoples" words = nltk.word_tokenize(text) lemmatizer = WordNetLemmatizer() print(words) print([lemma.lemmatize(word) for word in words]) lemmatization = [lemma.lemmatize(word) for word in words] print(" ".join(lemmatization))
import os import sys import tempfile import ConfigParser class OneTimePad(): def __init__(self): # Read settings from config file parse = ConfigParser.ConfigParser() parse.read("config/app.ini") self.block_size = int(parse.get("settings", "otp.block_size")) self.prng = parse.get("settings", "otp.prng") """ Given a filename, return the filesize """ def get_filesize(self, fd): fd.seek(0, 2) n = fd.tell() fd.seek(0, 0) return n """ Encrypt takes the name of the plaintext file to encrypt and the name of the ciphertext. It creates a padfile, processes them to get the resulting ciphertext. The padfile and ciphertext in the form of temporary, named file descriptors, are returned as a tuple. """ def encrypt(self, temp_plain_file): temp_plain_file.seek(0) # TODO: only need to pass in file size here temp_key = self.generate_padfile(temp_plain_file) temp_ct = self.process(temp_plain_file, temp_key) return (temp_key, temp_ct) """ Given a filename, return a temporary named padfile. This padfile will be a non-readable binary file. """ def generate_padfile(self, plain_file): temp_key = tempfile.NamedTemporaryFile() size = self.get_filesize(plain_file) block_size = self.block_size while size > 0: rand_fd = open(self.prng, 'r') block = rand_fd.read(min(block_size, size)) temp_key.write(block) size = size - len(block) temp_key.seek(0) return temp_key """ Decrypt behavior is a little bit strange. Takes multiple open temporary files """ def decrypt(self, plain_file, key, ciphertext): return self.process(ciphertext, key) # Takes three file descriptors. Reads from the input file and the pad file # and writes to the output file # # HOW IT WORKS: # zip takes the iterables a and b and then creates an iterator of tuples, # where the ith tuple contains the ith element of each arg a and b # # ord(i) converts a single character to its corresponding ASCII value # chr(i) returns the string representing a character whose Unicode codepoint is i # # Basically, each corresponding byte of the two files are converted into their # ascii values, which are then bitwise XORed and converted back into string form. # Each of these new bytes is appended to the final processed string and written to file. def process(self, in_file, pad_file): temp_out_file = tempfile.NamedTemporaryFile() while True: block_size = self.block_size #print "block size: " + self.block_size #print "2 block size: " + block_size data = in_file.read(self.block_size) if not data: break pad = pad_file.read(len(data)) encoded = ''.join([chr(ord(a) ^ ord(b)) for a, b in zip(data, pad)]) temp_out_file.write(encoded) temp_out_file.seek(0) pad_file.seek(0) return temp_out_file def main(): pt = "dog.txt" ct = "mycreds.cipher" key_file = "mycreds-padfile.txt" otp = OneTimePad() # otp.generate_padfile(pt, key_file) otp.encrypt(pt, key_file, ct) # otp.encrypt(pt, key_file, ct) # otp.decrypt("mycreds.decrypt", key_file, ct) if __name__ == '__main__': main()
#!/usr/bin/env python # encoding: utf-8 str_input = raw_input("pls input sth >") str_encode = str_input.decode(encoding="utf-8") flag = True for i in range(len(str_encode)/2): if str_encode[i] != str_encode[len(str_encode)-i-1]: flag = False print u"是回文序列" if flag else u"不是回文序列"
x = [ [5,2,3], [10,8,9] ] students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } z = [ {'x': 10, 'y': 20} ] # How would you change the value 10 in x to 15? Once you're done x should then be [ [5,2,3], [15,8,9] ]. x = [ [5,2,3], [10,8,9] ] x[1][0]=15 print(x) # How would you change the last_name of the first student from 'Jordan' to "Bryant"? students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] students[0]["first_name"] = "Bryant" print(students) # For the sports_directory, how would you change 'Messi' to 'Andres'? sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } sports_directory['soccer']=['Andres', 'Ronaldo', 'Rooney'] print(sports_directory) or sports_directory["soccer"][0]='Andres' print(sports_directory) # For z, how would you change the value 20 to 30? z = [ {'x': 10, 'y': 20} ] z[0]['y']=30 print(z) # 2. Create a function that given a list of dictionaries, it loops through each dictionary in the list and prints each key and the associated value. For example, given the following list: students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def keyvals(): for i in range(len(students)): for key, val in students[i].items(): print(key, " = ", val) keyvals() # Create a function that given a list of dictionaries and a key name, it outputs the value stored in that key for each dictionary. For example, iterateDictionary2('first_name', students) should output students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def iterateDictionary2('keyval, dictionary): for i in range(len(dictionary)) print(students[i][keyval]) iterateDictionary2('first_name', students) # Create a function that prints the name of each location and also how many locations the Dojo currently has. Have the function also print the name of each instructor and how many instructors the Dojo currently has. For example, printDojoInfo(dojo) should output dojo = { 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'], 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon'] } def printDojoInfo(dict): for key, val in dict.items(): print(len(val), key) for i in range(len(val)): print(val[i]) printDojoInfo(dojo)
# Biggie Size def posbig(arr): for i in range(len(arr)): if(arr[i]>0): arr[i]='pos' print(arr) posbig([-1,2,5,-6,-9]) # Count Positives def lastposval(arr): count = 0 for i in range(len(arr)): if(arr[i]>0): count = count +1 arr[len(arr)-1] = count print(arr) return arr lastposval([1,-3,5,6,1,3]) # SumTotal def sumallvals(arr): sum= 0 for i in range (len(arr)): sum = sum + arr[i] print(sum) return sum sumallvals([1,2,3,4,5]) # Length def length(arr): print(len(arr)) # Minimum def minimum(arr): print(min(arr)) # or def minimum(arr): min=arr[0] for i in range(len(arr)): if(arr[i]<min): min=arr[i] print(min) # Maximum def maximum(arr): print(min(arr)) # or def maximum(arr): max=arr[0] for i in range(len(arr)): if(arr[i]<max): max=arr[i] print(max) # UltimateAnalyze def arrtodict(arr): totalsum=sum(arr) avg= sum(arr)/len(arr) minimum = min(arr) maximum = max(arr) length=len(arr) dictionary={totalsum, avg, minimum, maximum, length} print(dictionary) arrtodict([1,2,3,4]) # ReverseArr def ReverseArr(arr): arr.reverse() print(arr) # or # def ReverseArr(arr): # temp=0 # for i in range(0,(int(len(arr)/2))): # temp=arr[i] # arr[i]= arr[(len(arr)-1)] # arr[(len(arr)-1)]=temp # print(arr) # return arr # ReverseArr([1,2,3,4,5,6])
#!/usr/bin/env python3 def main(): limit = 1000 a = sum(x for x in range(limit) if x % 2 == 0 and fib(x)) print(a) print(a) def fib(a): return if __name__ == "__main__": main()
#-*- coding: utf-8 -*- class Singleton(type): def __init__(cls,name,bases,dict): super(Singleton,cls).__init__(name,bases,dict) cls.instance=None def __call__(cls,*args,**kw): if cls.instance is None: cls.instance=super(Singleton,cls).__call__(*args,**kw) return cls.instance class MyClass: __metaclass__=Singleton print MyClass() print MyClass() def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] else: raise Exception("This is a singleton class." + cls.__name__) return getinstance @singleton class MyClass1: pass print MyClass1() print MyClass1()
# 建立整个无环有向图 graph = {} graph["start"] = {} graph["start"]["a"] = 5 graph["start"]["b"] = 2 graph["a"] = {} graph["a"]["c"] = 4 graph["a"]["d"] = 2 graph["b"] = {} graph["b"]["a"] = 8 graph["b"]["d"] = 7 graph["c"] = {} graph["c"]["fin"] = 3 graph["c"]["d"] = 6 graph["d"] = {} graph["d"]["fin"] = 1 graph["fin"] = {} # 维护开销的散列表,一开始到终点的开销为无穷大 infinity = float("inf") costs = {} costs["a"] = 5 costs["b"] = 2 costs["c"] = infinity costs["d"] = infinity costs["fin"] = infinity # 构建父节点的散列表 parents = {} parents["a"] = "start" parents["b"] = "start" parents["c"] = None parents["d"] = None parents["fin"] = None # 构建一个数组,用于存放已经处理过的节点 processed = [] def find_lowest_cost_node(costs): lowest_cost = float("inf") # 将 cost 定义为最大数,发现更小的cost就更新lowest_cost lowest_cost_node = None for node in costs: cost = costs[node] if cost < lowest_cost and node not in processed: lowest_cost = cost lowest_cost_node = node return lowest_cost_node node = find_lowest_cost_node(costs) # 找到未处理的节点中开销最少的 while node is not None: cost = costs[node] # 返回开销表中的从起点到node节点的开销 neighbors = graph[node] # neighbors也是一个散列表,找到node节点的邻居 for nbs in neighbors.keys(): # neighbors.keys()函数返回散列表的键,也即邻居,这个for循环跑完了,将node的邻居的开销都更新了一遍,包括父节点,这个node节点也就处理完了 new_cost = cost + neighbors[nbs] # 更新其邻居的开销 if costs[nbs] > new_cost: # 如果到其邻居的开销小于开销散列表中存储的,更新 costs[nbs] = new_cost parents[nbs] = node processed.append(node) node = find_lowest_cost_node(costs) # 继续找到未处理的节点中开销最少的 print(costs["fin"])
__author__ = 'azmi' ''' British mathematician John Conway developed in 1970 so-called "Game of life". A simplified simulation of the development of cell colonies, of which various properties were the subject of discussion of mathematicians and computer scientists. The game is played on a rectangular board divided into fields. Each field can be alive (there is a cell on it) or dead. In one unit of time each field checks the status of its neighbours and determines its own value. If an alive cell is surrounded by less than 2 or more than 3 cells it dies of loneliness or lack of living space. If a dead cell is surrounded by exactly three cells it comes back to life. The "surrounding" is defined by eight fields adjacent to the cell. In addition, our simulation takes place on 5x5 board, where the boundaries come together (so for example the last cell is first cell's neighbour). ''' import itertools class Game(object): def __init__(self, sizex, sizey): self.sizex = sizex self.sizey = sizey self.livecells = set() def advance(self, livecells=None): if livecells is not None: self.livecells = livecells else: newlivecells = set() neighbours = [self.neighbours(point) for point in self.livecells] uniqueneighbours = set(itertools.chain(*neighbours)) cellstotransit = self.livecells.union(uniqueneighbours) for point in cellstotransit: liveneighbours = [(neighbour in self.livecells) \ for neighbour in self.neighbours(point)] count = sum(liveneighbours) if count == 3 or (count == 2 and point in self.livecells): newlivecells.add(point) self.livecells = newlivecells def neighbours(self, point): col, row = point leftcol = (col == 0 and [self.sizex - 1] or [col - 1])[0] rightcol = (col == self.sizex - 1 and [0] or [col + 1])[0] toprow = (row == 0 and [self.sizey - 1] or [row - 1])[0] bottomrow = (row == self.sizey - 1 and [0] or [row + 1])[0] yield rightcol, row yield leftcol, row yield col, bottomrow yield col, toprow yield rightcol, bottomrow yield rightcol, toprow yield leftcol, bottomrow yield leftcol, toprow t = int(raw_input()) startsetlist = [] for _ in range(t): startset = set() for j in range(5): k = 0 gamerow = raw_input() for c in gamerow: if c == '1': startset.add((k, j)) startsetlist.append(startset) for start in startsetlist: game = Game(5, 5) game.advance(start) for i in range(100): game.advance() print 'YES' if len(game.livecells) > 0 else 'NO'
__author__ = 'azmi' def checkpossibility(bh, gh): if len(gh) < len(bh): return False if bh[0] <= gh[0]: return False for a, b in zip(bh, gh): if b > a: return False return True t = int(raw_input()) for _ in range(t): m, n = map(int, raw_input().split()) boysheights = sorted(map(int, raw_input().split())) girlsheights = sorted(map(int, raw_input().split())) possible = checkpossibility(boysheights, girlsheights) print 'YES' if possible else 'NO'
import tkinter as tk window = tk.Tk() window.title('my window') window.geometry('200x200')#这里是字母x不是乘号 var=tk.StringVar() l=tk.Label(window,bg='yellow',width=20,text='empty') l.pack() def print_selection(): l.config(text='youn have selected'+var.get()) rl=tk.Radiobutton(window,text='Option A', variable=var,value='A', command=print_selection) rl.pack() r2=tk.Radiobutton(window,text='Option B', variable=var,value='B', command=print_selection) r2.pack() r3=tk.Radiobutton(window,text='Option C', variable=var,value='C', command=print_selection) r3.pack() window.mainloop()
import tkinter from tkinter import * root=Tk() e=Entry(root,width=50) e.pack() e.insert(0,"Enter Your Name") #function defination def myClick(): myLabel2=Label(root,text="Hello "+e.get()) myLabel2.pack() mylabel1=Label(root,text='Welcome in GoDigital ') button=Button(root,text='Enter Your Name ',command=myClick) #showing it onto window mylabel1.pack() button.pack() root.mainloop()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 2 15:16:25 2018 @author : gaurav gahukar : caffeine110 AIM : To Predict the Stock PRice of a perticular stock Using Recurrent Neural Network : Implimentation of RNN using LSTM layers """ #Phase - 1 : importing dependencies #importting import pandas as pd import numpy as np import matplotlib.pyplot as plt #Phase - 1 : #impotting traing datasets training_set = pd.read_csv('Google_Stock_Price_Train.csv') training_set = training_set.iloc[:,1:2].values #feature sclling from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler() training_set = sc.fit_transform(training_set) #getting the inputs and output x_train = training_set[0:1257] y_train = training_set[1:1258] #reshaping x_train = np.reshape(x_train, (1257, 1,1)) # PART 2 - BUILDING OF RNN FOR DATA FEEDING #importing the keras libraries and packages from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM #initializing the RNN model_rnn_regressor = Sequential() #adding the input layer and Lstm Layer model_rnn_regressor.add(LSTM(units = 4, activation = 'sigmoid', input_shape = (None, 1))) #adding the output layer model_rnn_regressor.add(Dense(units = 1)) #Compiling the RNN and... model_rnn_regressor.compile(optimizer= 'adam', loss= 'mean_squared_error') #fitting the RNN to the Training set model_rnn_regressor.fit(x_train, y_train, batch_size = 32, epochs = 200) # part getting the real stolck ptice of test_set = pd.read_csv('Google_Stock_Price_Test.csv') real_stock_price = test_set.iloc[:,1:2].values #Phase - 3 : #getting the prodicted stock price of inputs = real_stock_price inputs = sc.transform(inputs) inputs = np.reshape(inputs, [20,1,1]) predicted_stock_price = model_rnn_regressor.predict(inputs) predicted_stock_price = sc.inverse_transform(predicted_stock_price) #Phase - 4 : Visualisation of Resultss #Visualisation the result plt.plot(real_stock_price, color='red', label ='Real GoogleStock Price') plt.plot(predicted_stock_price, color='blue', label= 'Predicted Google Stock price') plt.title('Google Stock ptice Prediction ') plt.xlabel('time') plt.ylabel('Google Stock PRice ') plt.legand() plt.show()
#Find GST Usign Python #By Programmers0_0; op = int(input("Enter Original Price:")) gst = int(input("Enter GST:")) cal = op * gst / 100 total = op + cal print("Total:", total)
# Function to find contiguous sublist with the largest sum # in a given set of integers def kadane(A): # stores the sum of maximum sublist found so far max_so_far = 0 # stores the maximum sum of sublist ending at the current position max_ending_here = 0 # traverse the given list for i in range(len(A)): # update the maximum sum of sublist "ending" at index `i` (by adding the # current element to maximum sum ending at previous index `i-1`) max_ending_here = max_ending_here + A[i] # if the maximum sum is negative, set it to 0 (which represents # an empty sublist) max_ending_here = max(max_ending_here, 0) # update result if the current sublist sum is found to be greater max_so_far = max(max_so_far, max_ending_here) return max_so_far # Function to find the maximum sum circular sublist in a given list def runCircularKadane(A): # empty array has sum of 0 if len(A) == 0: return 0 # find the maximum element present in a given list maximum = max(A) # if the list contains all negative values, return the maximum element if maximum < 0: return maximum # negate all elements in the list for i in range(len(A)): A[i] = -A[i] # run Kadane’s algorithm on the modified list neg_max_sum = kadane(A) # restore the list for i in range(len(A)): A[i] = -A[i] ''' return the maximum of the following: 1. Sum returned by Kadane’s algorithm on the original list. 2. Sum returned by Kadane’s algorithm on modified list + the sum of all elements in the list. ''' return max(kadane(A), sum(A) + neg_max_sum) if __name__ == '__main__': A = [2, 1, -5, 4, -3, 1, -3, 4, -1] print("The sum of the sublist with the largest sum is", runCircularKadane(A))
#program for checking an integer is palindrome or not ''' a=int(input("Enter number of string you wanted to run:-")) list1=[] for i in range(a): a=str(input()) list1.append(a) print(list1) for index,items in enumerate(list1): if items==items[::-1]: print (items,",yes It is palindrome") else: print(items,",No, it is not palindrome") ''' #program to find next palindrome of given integer n; def palindrome(n): n+=1 if(n<10): a=10-n b=n+a+1 while not is_palindrome(b): b+=1 return b else: while not is_palindrome(n): n+=1 return n def is_palindrome(n): return str(n)==str(n)[::-1] if __name__ == '__main__': try: n=int(input("Enter Numbers you want to print ")) numbers=[] list=[] for i in range(n): number=int(input("Enter number ")) numbers.append(number) for i in range(n): print(f"Next Palindrome of {numbers[i]} is {palindrome(numbers[i])}" ) list.append(palindrome(numbers[i])) print(list) except Exception as e: print(e)
# the mathematics problem in x+y movie def mainFunc(cards): for c in range(0, len(cards)-1): if cards[c] == 1: cards[c] = 0 if cards[c+1] == 0: cards[c+1] = 1 else: cards[c+1] = 0 return cards if __name__ == "__main__": cards = list("100111100101010111000101110101110110101") while cards != mainFunc(cards.copy()): cards = mainFunc(cards) print(cards)
MAX = 50 # Function to print Excel column name # for a given column number def printString(n): # To store result (Excel column name) string = ["\0"] * MAX # storing current index in str which is result i = 0 while n > 0: # Find remainder rem = n % 26 # if remainder is 0, then a # 'Z' must be there in output if rem == 0: string[i] = 'Z' i += 1 n = (n / 26) - 1 else: string[i] = chr((rem - 1) + ord('A')) i += 1 n = n / 26 string[i] = '\0' # Reversing the string string = string[::-1] print "".join(string) # Examples of the program printString(26) printString(702) printString(705)
import turtle PIXEL_POSITION = [(0, 0), (-20, 0), (-40, 0)] # positions for the 3 square pixels MOVE_DISTANCE = 20 UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 class Snake: def __init__(self): self.snake_segment = [] self.create_snake() self.head = self.snake_segment[0] def create_snake(self): # creates the initial 3 pixel snake # this loop creates the starting snake that is 3 square pixels positioned side by side for index in PIXEL_POSITION: self.add_segment(index) def add_segment(self, index): snake_pixel = turtle.Turtle(shape="square") snake_pixel.color("white") snake_pixel.penup() snake_pixel.goto(index) self.snake_segment.append(snake_pixel) def extend(self): self.add_segment(self.snake_segment[-1].position()) def move_snake(self): for segment in range(len(self.snake_segment) - 1, 0, -1): # start = len -1 because list starts from 0. # the next line is used to give the x and y coordinates of the further element to the element before # that is the coordinates of 2nd pixel is given to 3rd pixel, 1st to 2nd and so on. self.snake_segment[segment].goto(self.snake_segment[segment - 1].xcor(), self.snake_segment[segment - 1].ycor()) self.head.forward(MOVE_DISTANCE) def up(self): if self.head.heading() != DOWN: self.head.setheading(90) def down(self): if self.head.heading() != UP: self.head.setheading(270) def left(self): if self.head.heading() != RIGHT: self.head.setheading(180) def right(self): if self.head.heading() != LEFT: self.head.setheading(0)
""" Dictionary of PC Games """ d = {"MAX":"PAYNE", "STAR":"WARS", "CONTROL":1, "GTA":5, "FARCRY":3, "WITCHER":"GERALT OF RIVIA"} print("Enter a word") w = input().upper() # print(len(d)) print(w,d[w]) # print(d[w].lower().capitalize())
# Python code to convert temperature from celsius to fahrenheit temp_c = int(input("Enter temperature (in celsius):")) temp_f = ((temp_c/5)* 9 ) + 32 print("Temperature in Fahrenheit:", temp_f )
# Wave Print # For a given two-dimensional integer array/list of size (N x M), print the array/list in a sine wave order, i.e, print the first column top to bottom, next column bottom to top and so on. # Input format : # The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. # First line of each test case or query contains two integer values, 'N' and 'M', separated by a single space. They represent the 'rows' and 'columns' respectively, for the two-dimensional array/list. # Second line onwards, the next 'N' lines or rows represent the ith row values. # Each of the ith row constitutes 'M' column values separated by a single space. # Output format : # For each test case, print the elements of the two-dimensional array/list in the sine wave order in a single line, separated by a single space. # Output for every test case will be printed in a seperate line. # Constraints : # 1 <= t <= 10^2 # 0 <= N <= 10^3 # 0 <= M <= 10^3 # Time Limit: 1sec # Sample Input 1: # 1 # 3 4 # 1 2 3 4 # 5 6 7 8 # 9 10 11 12 # Sample Output 1: # 1 5 9 10 6 2 3 7 11 12 8 4 # Sample Input 2: # 2 # 5 3 # 1 2 3 # 4 5 6 # 7 8 9 # 10 11 12 # 13 14 15 # 3 3 # 10 20 30 # 40 50 60 # 70 80 90 # Sample Output 2: # 1 4 7 10 13 14 11 8 5 2 3 6 9 12 15 # 10 40 70 80 50 20 30 60 90 def waveprint(li, row, col): top = 0 bottom = row-1 left = 0 right = col - 1 dir = 1 while left<=right: if dir == 1: for i in range(top,bottom+1): print(li[i][left], end =" ") left+=1 dir=-1 elif dir ==-1: for i in range(bottom, top -1 ,-1): print(li[i][left],end =" ") left+=1 dir = 1 print() t = int(input()) for p in range(t): str = input().split() n,m = int(str[0]), int(str[1]) li = [] for i in range(n): row = [int(x) for x in input().split()] li.append(row) waveprint(li,n,m)