text
stringlengths
37
1.41M
# # @lc app=leetcode id=674 lang=python3 # # [674] Longest Continuous Increasing Subsequence # # @lc code=start class Solution: # def findLengthOfLCIS(self, nums: List[int]) -> int: # """ Strategy 1: Dynamic Programming # Runtime: O(n) # Space:O(n) # Args: # nums (List[int]): a list of integers # Returns: # int: the length of the longest continuous increasing subsequence # """ # n = len(nums) # if n <= 1: # return n # longest = 1 # dp = [1] * n # for i in range(1, n): # if nums[i-1] < nums[i]: # dp[i] = dp[i-1] + 1 # longest = max(longest, dp[i]) # return longest def findLengthOfLCIS(self, nums: List[int]) -> int: """ Strategy 1: sliding window Runtime: O(n) Space:O(1) Args: nums (List[int]): a list of integers Returns: int: the length of the longest continuous increasing subsequence """ n = len(nums) if n <= 1: return n anchor = longest = 0 for i in range(n): if i and nums[i - 1] >= nums[i]: anchor = i longest = max(longest, i - anchor + 1) return longest # @lc code=end
from typing import List class Solution: def formatRange(self, num1: int, num2: int): if num1 == num2: return str(num1) return str(num1) + "->" + str(num2) def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: """Strategy 1: Liner Scan Args: nums (List[int]): a list of integers lower (int): lower bound upper (int): upper bound Returns: List[str]: return a list of ranges of missing numbers """ n = len(nums) if n == 0: return [self.formatRange(lower, upper)] ranges = [] if nums[0] > lower: ranges.append(self.formatRange(lower, nums[0]-1)) for i in range(1, n): if nums[i] - nums[i-1] > 1: ranges.append(self.formatRange(nums[i-1]+1, nums[i]-1)) if nums[n-1] < upper: ranges.append(self.formatRange(nums[n-1]+1, upper)) return ranges
# # @lc app=leetcode id=103 lang=python3 # # [103] Binary Tree Zigzag Level Order Traversal # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque class Solution: # def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: # """ Strategy 1: BFS # Runtime: O(n), where n is the # of nodes in the tree # Space:O(n) # Args: # root (TreeNode): the root of the tree # Returns: # List[List[int]]: nodes in a 2d array in zig zag order # """ # if not root: # return None # output = cur_lvl = [] # next_lvl = [root] # l_or_r = 0 # while next_lvl: # cur_lvl = next_lvl # next_lvl = [] # temp = deque() # while cur_lvl: # node = cur_lvl.pop(0) # if not l_or_r: # temp.append(node.val) # else: # temp.appendleft(node.val) # for child in [node.left, node.right]: # if child: # next_lvl.append(child) # l_or_r ^= 1 # output.append(temp) # return output def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: """ Strategy 1: DFS Runtime: O(n), where n is the # of nodes in the tree Space:O(n) Args: root (TreeNode): the root of the tree Returns: List[List[int]]: nodes in a 2d array in zig zag order """ output = [] def dfs(node: 'TreeNode', level: int) -> None: if not node: return if level >= len(output): output.append(deque([node.val])) else: if level % 2: output[level].appendleft(node.val) else: output[level].append(node.val) for child in [node.left, node.right]: if child: dfs(child, level+1) return dfs(root, 0) return output # @lc code=end
# # @lc app=leetcode id=98 lang=python3 # # [98] Validate Binary Search Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import math class Solution: def validate(self, node: 'TreeNode', low=-math.inf, hi=math.inf) -> bool: if not node: return True if node.val <= low or node.val >= hi: return False return self.validate(node.left, low, node.val) and self.validate(node.right, node.val, hi) def isValidBST(self, root: TreeNode) -> bool: """Strategy 1: DFS Runtime: O(n), where n is the number of nodes Space: O(h), where h is the height of the tree Args: root (TreeNode): [description] Returns: bool: [description] """ return self.validate(root) # @lc code=end
# # @lc app=leetcode id=415 lang=python3 # # [415] Add Strings # # @lc code=start class Solution: def addStrings(self, num1: str, num2: str) -> str: """Strategy 1: Linear Scan Args: num1 (str): number 1 in string num2 (str): number 2 in string Returns: str: num1 + num2 in string """ n = len(num1) - 1 m = len(num2) - 1 output = "" carry = 0 while m >= 0 or n >= 0: x1 = ord(num1[n]) - ord('0') if n >= 0 else 0 x2 = ord(num2[m]) - ord('0') if m >= 0 else 0 print(x1, x2) output = str((x1 + x2 + carry) % 10) + output carry = (x1 + x2 + carry) // 10 n -= 1 m -= 1 return "1" + output if carry > 0 else output # @lc code=end
# # @lc app=leetcode id=350 lang=python3 # # [350] Intersection of Two Arrays II # from collections import Counter from typing import List # @lc code=start class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: """ Strategey 1: Counter Runtime: O(n + m), where n is the size of nums1, m is the size of nums2 Args: nums1 (List[int]): list of integers nums2 (List[int]): list of integers Returns: List[int]: the intersection of nums1 and nums2 """ counter1 = Counter(nums1) counter2 = Counter(nums2) output = [] for num, count in counter1.items(): if num in counter2: minCount = min(count, counter2[num]) output += [num] * minCount return output # @lc code=end
# # @lc app=leetcode id=10 lang=python3 # # [10] Regular Expression Matching # # @lc code=start from abc import abstractmethod class Solution: def isMatch(self, s: str, p: str) -> bool: """ Strategy 1: Dynamic Programming Runtime: O(n * m), where n is the length of s and m is the length of p Space: O(n * m) Args: s (str): the string to be matched p (str): a regex pattern Returns: bool: determine whether s can be matched by p """ s_len = len(s) p_len = 0 isFirst = True pattern = list(p) for _, c in enumerate(p): if c == "*": if isFirst: pattern[p_len] = c p_len += 1 isFirst = False else: pattern[p_len] = c p_len += 1 isFirst = True if s == p or pattern == [".", "*"]: return True # print(pattern) dp = [[False] * (p_len+1) for _ in range(s_len+1)] dp[0][0] = 1 for i in range(2, p_len+1): if pattern[i-1] == "*": dp[0][i] = dp[0][i-2] for y in range(1, s_len+1): for x in range(1, p_len+1): if pattern[x-1] == "." or s[y-1] == pattern[x-1]: dp[y][x] = dp[y-1][x-1] elif pattern[x-1] == "*": dp[y][x] = dp[y][x-2] if pattern[x-2] == "." or pattern[x-2] == s[y-1]: dp[y][x] = dp[y][x] or dp[y-1][x] return dp[s_len][p_len] # @lc code=end
# # @lc app=leetcode id=69 lang=python3 # # [69] Sqrt(x) # from math import e, log # @lc code=start class Solution: # def mySqrt(self, x: int) -> int: # """ Startegey 1: Pocket Calculator # Runtime: O(1) # Space: O(1) # Args: # x (int): the number x # Returns: # int: sqaure root of x with truncated part # """ # if x < 2: # return x # left = int(e ** (0.5 * log(x))) # right = left + 1 # return left if right ** 2 > x else right def mySqrt(self, x: int) -> int: """ Startegey 1: Binary Search Runtime: O(log(x)) Space: O(1) Args: x (int): the number x Returns: int: sqaure root of x with truncated part """ if x < 2: return x low, high = 0, x//2 while low <= high: mid = low + (high - low)//2 num = mid**2 if num > x: high = mid-1 elif num < x: low = mid + 1 else: return mid return high # * Newton method is has the least # of iteration when computing this problem # @lc code=end
""" 797. All Paths From Source to Target For a node: add node to path if node is target, add to path to result visit all neightbors remove node from path return result: Time : 2^N """ class Solution(object): def allPathsSourceTarget(self, graph): """ :type graph: List[List[int]] :rtype: List[List[int]] """ self.src = 0 self.dest = len(graph)-1 self.result = [] def visitAllNs(index,path): path.append(index) if index == self.dest: self.result.append(list(path)) for x in graph[index]: visitAllNs(x,path) path.pop() visitAllNs(0,[]) return self.result
""" Brute Force TLE: 1. At each day check if curr day is in range of last bought ticket 2. If oppurtunity to buy, try all 3 options """ class Solution(object): def mincostTickets(self, days, costs): """ :type days: List[int] :type costs: List[int] :rtype: int """ self.m = sys.maxsize def decision(lastcost,curr,passDaysMin,passDaysMax): if curr == len(days): self.m = min(lastcost,self.m) return if passDaysMin<=days[curr]<=passDaysMax: currcost = 0 decision(lastcost+currcost,curr+1,passDaysMin,passDaysMax) return #buy 1 day pass currcost = costs[0] passDays = 0 decision(lastcost+currcost,curr+1,0,0) #buy 7 day pass currcost = costs[1] passDays = 6 decision(lastcost+currcost,curr+1,days[curr],days[curr]+6) #buy 30 day pass currcost = costs[2] passDays = 29 decision(lastcost+currcost,curr+1,days[curr],days[curr]+29) decision(0,0,0,0) return self.m
""" 939. Minimum Area Rectangle 1. for a point r1,c1 and r2,c2 check if point r1,c2 and r2,c1 exist 2. if it does, find the area 3. if area less than prev value, update the area value to be returned. Runtime: O(N^2) space : O(N) """ from collections import Counter class Solution(object): def minAreaRect(self, points): """ :type points: List[List[int]] :rtype: int """ p = Counter() for x in points: r = x[0] c = x[1] p[r,c]+=1 def k(p): return p[1],p[0] points = sorted(points,key = k) def getarea(r1,r2,c1,c2): return abs(r1-r2)*abs(c1-c2) ar = sys.maxsize for i,col1 in enumerate(points): for j,col2 in enumerate(points): if i==j: continue r1 = col1[0] c1 = col1[1] r2 = col2[0] c2 = col2[1] if r1 == r2 or c1 == c2: continue if p[r1,c2]==1 and p[r2,c1]==1: d = getarea(r1,r2,c1,c2) if d < ar: ar=d if ar == sys.maxsize: return 0 return ar
# 2.2 Write a program that uses input to prompt a user for their name and then welcomes them. # Note that input will pop up a dialog box. Enter Sarah in the pop-up box when you are prompted # so your output will match the desired output. # The code below almost works name = input("Enter your name") print("Hello", name)
# Preberemo input # Splitamo po vrsticah # Gremo vrstico po vrstico # ! Izvedi naslednji ukaz # Stroj mora vedeti: # - vrednost -> OK # - v kateri vrstici je -> OK # - vse vrstice, ki jih je ze izvedel # - Seznam ukazov -> OK class Ukaz: def __init__(self, tip_ukaza, stevilka): self.tip_ukaza = tip_ukaza self.stevilka = stevilka class Machine: def __init__(self, ukazi): self.ukazi = ukazi self.akumulator = 0 # To je tisto kar se spreminja self.line = 0 # Index ukaza na katerem smo def naredi_korak(self): pass def pozeni_do_konca(self): # Naj vrne: Ali se zacikla, ali pa se izvede do konca pass ukazi = [ # Ukaz("nop", 0), # Ukaz("acc", 1), ] for ukaz in ukazi: if hocemo_zamenjati(ukaz): zamenjani = ukazi.zamenjaj(ukaz) stroj = Machine(zamenjani) stroj.pozeni_do_konca() # Preberemo ukaze # za vsako vrstico, splitaš po presledku, # dam v ukaz, potem pa ta ukaz dodam v seznam ukazov a = [1, 5, -3, 5, 6, 19] a.sort(reverse=True) print(a)
# Sprasuj uporabnika po stevilkah in jih # dodajaj v seznam dokler ni 0 seznam_stevil = [] vpisano_stevilo = int(input("Vnesi stevilo")) stevilo_vpisanih = 1 while stevilo_vpisanih != 10 and vpisano_stevilo != 0: # Enako kot pri if stavku # zamaknemo stvari noter seznam_stevil.append(vpisano_stevilo) stevilo_vpisanih = stevilo_vpisanih + 1 vpisano_stevilo = int(input("Vnesi stevilo")) print("Vpisal si števila") print(seznam_stevil)
# Funkcije # Izracunaj fakulteto stevila n n = 50 zmnozek_fakultete = 1 fakulteta = 1 for j in range(n): zmnozek_fakultete *= fakulteta fakulteta += 1 # V zmnozek_fakultete je skrit rezultat za n! # Tukaj pa izracunamo vsoto # Spiši na ta način še funkcijo ki sešteje števke # x%10 x// 10 def loop_pure (n): def = 40 if n == 100: return () else: return loop_pure(n-1) def test_pure(n): return loop_pure(n)
from random import randint import Player import Board class Chess(): def whatColor(self): return randint(0, 9) def newgame(self): m = Chess() print (""" "Welcome, please enter your names in order to start the game and press the enter key. """) player1, player2 = m.getPlayers() player1.setOpp(player2) player2.setOpp(player1) game = Board.Board(player1, player2) menu = """ Player 1: {} - Will use uppercase lettering Player 2: {} - Will use lowercase lettering (Move format is 'a2b3'. Type 'exit' to quit the game.""".format(player1.name, player2.name, player1, player2) print (menu) input("\n\nHit the Enter button to play") randNum = m.whatColor() if (randNum == 0): player = player1 else: player = player2 try: result, player = game.run(player) except TypeError: pass else: print (game.end(player, result)) input("\n\nPress any key to continue") def getPlayers(self): loop1 = True loop2 = True while loop1: name1 = input("\nPlayer 1 (white): ") if not name1: print ("Try again") else: player1 = Player.Player('white', name1) loop1 = False while loop2: name2 = input("\nPlayer 2 (black): ") if not name2: print ("Try again") else: player2 = Player.Player('black', name2) loop2 = False return player1, player2 def chess(self): m = Chess() endGame="""To play again press enter. To quit type 'exit' >> """ try: while True: m.newgame() choice=input(endGame) if choice == 'exit': print ("\nNew Chess Game!") break except KeyboardInterrupt: sys.exit("\n\nErrorl. Abort.") m = Chess() m.chess()
x=int(15) flag = 0 for num in range (2,x + 1): for num1 in range (2,int(num/2)): if num%num1 == 0: flag = flag + 1 break if flag == 0: print(num,"is a prime number") flag=0
a=20 def sum(a): a=a+1 b=20 print(a) sum(a) print("a=",a)
# add, mul ,div ,sub def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def div(a,b): return a/b def main(): ch = int(input("press 1 for add \n 2 for sub \n 3 for mul \n 4 for div \n press 0 to exit \n")) while ch!=0: a = int(input("Enter num1 value: ")) b = int(input("Enter num2 value: ")) if ch == 1: print(add(a,b)) elif ch == 2: print(sub(a,b)) elif ch == 3: print(mul(a,b)) else: print(div(a,b)) ch = int(input("press 1 for add \n 2 for sub \n 3 for mul \n 4 for div \n press 0 to exit \n")) main()
__author__ = 'tales.cpadua' class SnakeSegment(): def __init__(self, pos_x, pos_y): self.pos_x = pos_x self.pos_y = pos_y class Snake(): def __init__(self, display, block_size, pos_x=300, pos_y=300): self.color = (0, 155, 0) self.display = display self.block_size = block_size self.x_velocity = 0 self.y_velocity = (-1)*self.block_size self.segments = [] self.segments.append(SnakeSegment(pos_x, pos_y)) self.prev_x_vel = 0 self.prev_y_vel = 0 # To turn, we keep velocity variables for x and y direction, and then we sum it to the position # The snake will be always moving, so the event handler will only change the movement direction # The snake cannot go directly to the opposite direction. The first if of these methods assure this def turn_left(self): if self.x_velocity > 0: return self.x_velocity = (-1)*self.block_size self.y_velocity = 0 def turn_right(self): if self.x_velocity < 0: return self.x_velocity = self.block_size self.y_velocity = 0 def turn_down(self): if self.y_velocity < 0: return self.y_velocity = self.block_size self.x_velocity = 0 def turn_up(self): if self.y_velocity > 0: return self.y_velocity = (-1)*self.block_size self.x_velocity = 0 def add_segment(self): self.segments.append(SnakeSegment(self.segments[-1].pos_x, self.segments[-1].pos_y)) # Here we sum the velocity to the position. Note that negative values will decrease the position value, since # sum negative number is the same as subtracting a positive one # def move(self): next_x_pos = self.segments[0].pos_x + self.x_velocity next_y_pos = self.segments[0].pos_y + self.y_velocity self.segments.pop() self.segments.insert(0, SnakeSegment(next_x_pos, next_y_pos)) #reset snake to initial values def reset_snake(self): self.segments = [] self.segments.append(SnakeSegment(300, 300)) self.x_velocity = 0 self.y_velocity = (-1)*self.block_size
#!usr/bin/python # -*- coding: utf-8 -*- import numpy as np class Perceptron(object): """Perceptron classifier. Parameters ------------ n_rate : float, Learning rate(between 0,0 and 1.0) n_iter : int, Passes over the training dataset. Attributes ------------ w_n : 1d-array, Weights after fitting errors_n :list, Number of misclassifications in every epoch. """ def __init__(self, n_rate=0.01, n_iter=10): self.n_rate = n_rate self.n_iter = n_iter def fit(self, x, y): """Fit training data.先对权重参数初始化,然后对训练集中得每一个参数进行初始化,根据感知机算法规则对群众进行更新 :param x: array-like, shape = [n_samples, n_features], Training vectors, where n_samples is the number of sampl es and n_features is the number of features. :param y: array-like, shape = [n_samples], Target values. :return: self: object """ self.w_n = np.zeros(1 + x.shape[1])
num = int(input('get the value:')) for i in range(2,num+1): count = 0 for j in range(2,i): if i%j != 0: count += 1 if count == i-2: print (i)
import os import imageio from PIL import Image images = [] size = (150, 150) for filename in os.listdir("images"): # only consider the extensions below when creating the gif if filename.endswith(".png") or filename.endswith( ".jpg") or filename.endswith(".jpeg") or filename.endswith( ".tiff") or filename.endswith(".tif"): im = Image.open("images/{filename}".format(filename=filename)) # decreases the image in quality in order to reduce gif's size im = im.resize((im.size[0] // 2, im.size[1] // 2), Image.ANTIALIAS) im.save("images/temporary.jpg", optimize=True, quality=85) print("Appending file {filename}...".format(filename=filename)) images.append(imageio.imread("images/temporary.jpg")) os.remove("images/temporary.jpg") print("Generating GIF...") imageio.mimsave('my.gif', images) print("Your GIF was generated!")
import asyncio from time import time class Clock: """ Abstraction measuring elapsed time and waiting """ def now(self): """ Measure the current time, in seconds """ raise NotImplemented() async def sleep(self, n): """ Waits until the specified amount of time has elapsed """ raise NotImplemented() class SystemClock: def now(self): return time() async def sleep(self, n): await asyncio.sleep(n) class TestClock: def __init__(self): self.t = 0 def now(self): return self.t async def sleep(self, n): self.t += n
import re from solutionP1 import Queue, Stack def check_palindrom(text): # clean data text = str(text).lower() text = re.sub('[^a-z0-9]+', '', text) mid = len(text) // 2 is_even = True if len(text) % 2 != 0: is_even = False first_half = text[:mid] second_half = text[mid:] # put first half in stack first to last stack = Stack() for char in first_half: stack.push(char) # put other half in queue last to first queue = Queue() for char in second_half: queue.enqueue(char) # remove middle char if not is_even: queue.dequeue() # compare stack and queue for i in range(mid): if stack.pop() != queue.dequeue(): return False return True def test(): cases = [] cases.append("Ni talar bra latin") cases.append("Able was I ere I saw Elba!") cases.append("A man, a plan, a canal – Panama") cases.append(123321) cases.append("Not a palindrom") for case in cases: print(case) if check_palindrom(case): print("Palindrom") else: print("NOT Palindrom") print("-------------------") test()
def findNonDuplicate(A): # empty list if len(A) == 0: return None # no duplicate value if len(A) == 2 and A[0] == A[1]: return None # Recursive case if len(A) > 2: mid = len(A) // 2 if mid % 2 != 0: mid += 1 right = A[mid:] left = A[:mid] if left[-1] == left[-2]: return findNonDuplicate(right) else: return findNonDuplicate(left) # Base case return A[0] def findNonDuplicateVerifiedInput(A): for a in A: if not a.isalnum(): return f"{a} is not a valid input value" return findNonDuplicate(A) if __name__ == "__main__": assert findNonDuplicate(['c', 'c', 'd', 'd', 'f', 'f', 'z']) == 'z' assert findNonDuplicate( ['a', 'a', 'b', 'b', 'c', 'd', 'd', 'e', 'e', 'r', 'r']) == 'c' assert findNonDuplicate( ['a', 'a', 'b', 'b', 'd', 'd', 'e', 'e', 'r', 'r']) == None assert findNonDuplicateVerifiedInput( ['c', 'c', 'd', 'd', 'f', '&', 'z']) == '& is not a valid input value'
import numpy as np import matplotlib.pyplot as plt def generate_point(func, num_point): # func: the parameter of function # num_point: the number of points needing to generate # generate point of x randomly point_x = np.random.random((num_point, 1)) * 6 point_y = func(point_x) return point_x, point_y def add_Gaussian_noise_on_points(point, num_point): # point: given point_x and point_y # para: the intensity of noise mu, sigma = 0, 0.1 noise = np.random.normal(mu, sigma, num_point) return noise + point if __name__ == "__main__": func = lambda x: np.sin(x) num_point = 10 # # generate points which obeys the sin(x) computation point_x, point_y = generate_point(func, num_point) # Because those points generated by this method are too disperse, # so I use the next method that using the fixed interval. # 1. generate the points with fixed interval point_x = np.linspace(0, 6, 10) point_y = np.sin(point_x) print point_x, point_y
s = raw_input().strip() i = 0 target = 0 temp =0 default = "SOS" while i<len(s): for x in s[i:i+3]: if x!=default[temp]: target=target+1 temp=temp+1 else: temp=temp+1 temp=0 i=i+3 print target
def merge(array1, array2): ''' :param array1: sorted list :param array2: sorted list :return: list, merged from 2 arrays ''' res = [] pointer1 = 0 pointer2 = 0 while pointer1 < len(array1) and pointer2 < len(array2): if array1[pointer1] <= array2[pointer2]: res.append(array1[pointer1]) pointer1 += 1 else: res.append(array2[pointer2]) pointer2 += 1 res += array1[pointer1: len(array1)] res += array2[pointer2: len(array2)] return res def merge_sort(array): ''' :param array: array of numbers :return: list, sorted array of numbers ''' if len(array) < 2: return array else: divider = len(array) // 2 lst1 = merge_sort(array[:divider]) lst2 = merge_sort(array[divider:]) return merge(lst1, lst2) def find_two_closest(array): ''' :param array: list of numbers :return: list, two numbers with difference less than in any other 2 numbers in array. ''' sorted_array = merge_sort(array) res = list() res.append(sorted_array[0]) res.append(sorted_array[1]) for i in range(1, len(sorted_array) - 1): if abs(res[0] - res[1]) > abs(sorted_array[i] - sorted_array[i + 1]): res[0] = sorted_array[i] res[1] = sorted_array[i + 1] return res if __name__ == '__main__': a = [3, 10, 20, 2, 50, 5, 90, 100] print(find_two_closest(a)) # Calculating complexity: # Sorting - O(nlog(n)) # Finding pair - O(n) # General: O(n + nlog(n)) = O(nlog(n))
# Task 1 # speed = int(input('Enter speed: ')) # distance = int(input('Enter distance: ')) # time = distance / speed # print('Time for reaching place: ' + str(time)) # name = input('Enter your name: ') # age = input('Enter your age: ') # surname = input('Enter your surname: ') # print(f'Hello, Your surname is {surname}, your name is {name} and your age is {age} years old') # Task2 # import random # list_ = random.sample(range(100), 10) # if 3 in list_: # print('Yes') # else: # print('No') # print(list_) # Task3 # product_amount = int(input('Enter amount of product: ')) # product_price = int(input('Enter price off the prooduct: ')) # total = product_amount * product_price # print(f'Total price:{total}') # Task4 d = input('Choose diameter of your pizza: (30,,40, 50):') count = input('How many pizzas do you want to order? :') price_per_one = 0 if d == '30': price_per_one = 500 elif d == '40': price_per_one = 600 elif d == '50': price_per_one = 700 else: print('There is no such size') total = int(count) * price_per_one print(f'Total price is {total}$')
# DayOFBirth = int(input('Enter day of your birth: ')) # MonthOfBirth = int(input('Enter month of your birth: ')) # YearOfBirth = int(input('Enter year of your birth:')) # print(DayOFBirth+MonthOfBirth+YearOfBirth) # payment=int(input('Paymentfor courses: ')) # discount= int(input('Discount for best students: ')) # print('Total payment: ', int(payment-discount*payment/100), '$') from math import pi r = int(input('Enter radius of round: ')) area = pi * r**2 dlina = 2 * pi * r print('Square of the round:', round(area, 2), '\n' 'Lenght of the round: ', round(dlina, 2))
import random class QueueSimulation: def __init__(self,a,b,c,d): self.process_rate = a self.min_req_rate = b self.max_req_rate = c self.queue = [] self.queue_capacity = d def step(self, req): result = [] lost_count = 0 while len(self.queue) > 0: previous_queue_process = self.queue.pop(0) result.append(previous_queue_process) while len(result) < self.process_rate: process = req.pop(0) result.append(process) if len(req) == 0: pass else: while len(self.queue) < self.queue_capacity: not_yet_processed = req.pop(0) self.queue.append(not_yet_processed) if len(req) == 0: pass else: lost_count = len(req) return result, lost_count def run(self, n): for i in range (n): a = 0 number_of_requests = random.randint(self.min_req_rate,self.max_req_rate) number_of_results = 0 length_of_queue = 0 max_length_of_queue = self.queue_capacity number_of_results += length_of_queue length_of_queue = 0 if number_of_requests <= self.process_rate - number_of_results: number_of_results += number_of_requests else: number_of_requests -= (self.process_rate - number_of_results) if number_of_requests > max_length_of_queue: length_of_queue = max_length_of_queue a += 1 else: length_of_queue = number_of_requests lost_frequency = a/n return lost_frequency
target = int(input("Enter target: ")) def reachTarget(target): # Handling negatives by symmetry target = abs(target) # Keep moving while sum is smaller of difference is odd sum = 0 step = 0 while (sum < target or (sum-target) % 2 != 0): step = step + 1 sum = sum + step return step print(reachTarget(target))
from queue import Queue q = Queue(3) assert(q.is_empty()) assert(hasattr(q, "items")) assert(hasattr(q, "insert")) assert(hasattr(q, "remove")) assert(hasattr(q, "is_empty")) result = q.insert(5) assert(result == True) assert(not q.is_empty()) assert(q.__str__() == "5") result = q.insert(7) assert(result == True) assert(not q.is_empty()) assert(q.__str__() == "7 5") result = q.insert(-1) assert(result == True) assert(not q.is_empty()) assert(q.__str__() == "-1 7 5") result = q.insert(20) assert(result == False) assert(not q.is_empty()) assert(q.__str__() == "-1 7 5") result = q.insert(33) assert(result == False) assert(not q.is_empty()) assert(q.__str__() == "-1 7 5") x = q.remove() assert(not q.is_empty()) assert(q.__str__() == "-1 7") assert(x == 5) x = q.remove() assert(not q.is_empty()) assert(q.__str__() == "-1") assert(x == 7) q.insert(11) assert(not q.is_empty()) assert(q.__str__() == "11 -1") x = q.remove() assert(not q.is_empty()) assert(q.__str__() == "11") assert(x == -1) x = q.remove() assert(q.is_empty()) assert(q.__str__() == "") assert(x == 11)
import numpy board = [] counter = 0 def win_check(player): # win horizontally player_win = 0 if board[0] == board[1] == board[2] == player or board[3] == board[4] == board[5] == player or board[6] == board[7] == board[8] == player: player_win += 1 # win vertically elif board[0] == board[3] == board[6] == player or board[1] == board[4] == board[7] == player or board[2] == board[5] == board[8] == player: player_win += 1 # win diagonally elif board[0] == board[4] == board[8] == player or board[2] == board[4] == board[6] == player: player_win += 1 return player_win def track(_level, _maxlevel): if _level == _maxlevel + 1: global counter # # counter += 1 # print(board, counter) num_x = 0 num_o = 0 for i in board: if i == "x": num_x += 1 elif i == "o": num_o +=1 x_win = win_check("x") o_win = win_check("o") # legal check # draw legal = False if x_win == o_win == 0 and num_x == 5 and num_o == 4: legal = True # x win elif x_win == 1 and o_win == 0 and num_x - num_o == 1: legal = True # o win elif x_win == 0 and o_win == 1 and num_o == num_x: legal = True # x has double move: elif x_win == 2 and o_win == 0 and num_x == 5 and num_o == 4: legal = True # print board if legal: counter += 1 print(numpy.reshape(board, (3, 3)), counter) return for j in ["-", "x", "o"]: # print(j, _level-1, visited) if j not in visited[_level-1]: board.append(j) visited[_level-1].append(j) track(_level+1, _maxlevel) visited[_level-1].pop() board.pop() visited = [] for i in range(9): visited.append([]) track(1, 9)
class Node: content = None Next = None def __init__(self): pass class LinkedList: def __init__(self): self.head = [] def push(self): pass def is_empty(self): if len(self.head) == 0: return True else: return False def __str__(self): s = "" if self.is_empty(): s = "<<E>>" else: for i in range(len(self.head)-1): s += str(self.head[i]) + "->" if not self.is_empty(): s += str(self.head[len(self.head)]) return s def add_first(self, d): pass def remove_first(self): pass def add_last(self): pass def remove_last(self): pass def find(self): pass
string = input("Enter a string: ") shift = int(input("Enter Caesar shift: ")) char = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" enc = '' dec = '' def encrypt(str, n): global enc for i in str: if i in char: check = ord(i) + shift if check >= 97 and check <= 122 or check >= 65 and check <= 90: new = check elif check > 122 or 90 < check <= 96: new = check - 26 new2 = chr(new) enc += new2 else: enc += i return enc def decrypt(str, n): global dec for i in str: if i in char: check = ord(i) - shift if check >= 97 and check <= 122 or check >= 65 and check <= 90: new = check elif check < 65 or 90 < check <= 96: new = check + 26 new2 = chr(new) dec += new2 else: dec += i return dec print(encrypt(string, shift)) print(decrypt(enc, shift))
age = int(input("How old are you? ")) if (age < 16) or (age > 65): print("Enjoy your free time") else: print("Have a good day at work") x = "false" if x: print("x is true") x = input("Please enter some text: ") if x: print("You entered '{}".format(x)) else: print("You did not entered anything") print(not False)
import Crypto.Random.random as rand import hashlib import string # Given a password and salt, compute their hash def hash_password(password, salt): cur = password + salt # Repeatedly hash the password, to make brute forcing more expensive for _ in range(10000): cur = hashlib.sha512(cur).hexdigest() # Done! return cur # Securely generate a token (random, unique string) # @param length The length of the token characters DEFAULT_TOKEN_LENGTH = 256 def secure_token(length = DEFAULT_TOKEN_LENGTH): return "".join([rand.choice(string.hexdigits) for _ in range(length)])
#!/usr/bin/python3.6 import numpy as np import sys import math import DecisionTree as dt def bootstrap(trees,depth,train,test,display = False): """Performs bootstrap aggregation with a decision tree learner for k-class classification""" #Build an array for indices/predictions for output indices = np.zeros((train.length,trees), dtype = int) prediction_labels = np.zeros((test.length,trees), dtype = str) prediction_probs = np.zeros((test.length,test.label_length), dtype = float) for i in range(0,trees): #Randomly sample data from train to use bs_sample = np.random.choice(range(0,train.length), size = train.length) indices.T[i] = bs_sample bs_features = train.features[bs_sample] bs_labels = train.labels[bs_sample] #Create and train boostrap decision tree tree = dt.DecisionTree() tree.fit(bs_features, bs_labels, train.metadata, max_depth = depth) #Using this tree, do prediction on test prediction_probs += tree.predict(test.features, prob = True) prediction_labels.T[i] = tree.predict(test.features, prob = False) #Now, vote for predicted class using prediction_probs matrix predictions = [] truth = [] correct = 0 for i in range(0,test.length): #Finds the class that received the most probability prediction_index = np.argmax(prediction_probs[i]) yhat = test.metadata[-1][1][prediction_index] y = test.labels[i] predictions.append(yhat) truth.append(y) #Increment number of correct predictions if yhat == y: correct += 1 #calculate accuracy accuracy = correct/test.length if display: #Print the tree training indices for i in range(0,train.length): print(','.join(map(str,indices[i]))) #Print the predictions print() for i in range(0,test.length): print(','.join(prediction_labels[i]), predictions[i], truth[i], sep = ',') #Print accuracy print() print(accuracy) #Return the overall predictions return predictions def adaboost(trees,depth,train,test,display = False): """Implements the adaboost algorithm for k-class classification using a decision tree learner""" #initialize weights weights = np.ones(train.length)/train.length train_truth = train.labels test_predictions_list = np.zeros((test.length, trees), dtype = str) num_classes = train.label_length alpha_list = [] weights_list = np.zeros((train.length, trees)) test_possible_labels = [test.metadata[-1][1],]*test.length cx = 0 #Create decision trees for i in range(0,trees): weights_list.T[i] = weights #Creates a list of weights for output #Create and train decision tree tree = dt.DecisionTree() tree.fit(train.features, train.labels, train.metadata, max_depth = depth, instance_weights = weights) #Using this tree, do prediction on train train_predictions = tree.predict(train.features, prob = False) incorrect = (train_predictions != train_truth).astype(float) #Calculate error error = np.dot(weights,incorrect) / sum(weights) #If error is large, break out of the loop if error >= 1 - 1/num_classes: trees = i - 1 break #Calculate alpha alpha = np.log((1-error)/error) + np.log(num_classes - 1) alpha_list.append(alpha) #Update weights weights = weights * np.exp(alpha*incorrect) weights = weights/sum(weights) #Now, to do prediction on test test_predictions = tree.predict(test.features, prob = False) test_predictions_list.T[i] = test_predictions #This is a bit of an ugly workaround x = np.tile(test_predictions,(test.label_length,1)).T kclass = (test_possible_labels == x).astype(float) #Creates a sum which we will use for overall classification cx += alpha * kclass #Classification is the class that maximizes cx classifications_index = np.argmax(cx, axis = 1).astype(int) #Build the classifications output array and calculate accuracy test_truth = test.labels classifications = np.take(test.metadata[-1][1], classifications_index) accuracy = sum((test_truth == classifications).astype(float)) / test.length if display: #Print the tree training weights for i in range(0,train.length): print(','.join(map("{:10.12f}".format, weights_list[i]))) #Print the alphas print() print(','.join(map("{:10.12f}".format,alpha_list[:]))) #Print the predictions print() for i in range(0,test.length): print(','.join(test_predictions_list[i]), classifications[i], test_truth[i], sep = ',') #Print accuracy print() print(accuracy) #return overall classifications return classifications def build_confusion_matrix(data, predictions, verbose = False): """Builds a confusion matrix from the test data and given predictions""" #Build a dictionary to handle str labels temp_dict = dict(enumerate(data.metadata[-1][1])) labels_dict = {y:x for x,y in temp_dict.items()} #Convert labels to index (to handle strings) truth = data.labels predictions_index = np.vectorize(labels_dict.get)(predictions) truth_index = np.vectorize(labels_dict.get)(truth) #Build the confusion matrix and populate cm = np.zeros((data.label_length,data.label_length), dtype = int) np.add.at(cm, (predictions_index, truth_index), 1) if verbose: #Print out stuff for grading for i in range(0,len(cm)): print(','.join(map(str, cm[i]))) return cm
#!/usr/bin/python # -*- coding: UTF-8 -*- for i in range(1,10): for j in range(11,20): print(i,j) if j == 15: break print i
#!/usr/bin/python # -*- coding: UTF-8 -*- # 随着随机次数的增加 # 平均值越来越趋向于5.5 # 也就是(1+10)/2 import random s1 = 0 s2 = 0 s3 = 0 s4 = 0 for i in range(1,10**1+1): p = random.choice(range(1,11)) # print('从1到9中取个随机值,第一次是:%d') % p s1 += p i1 = float(i) print('1到10之间,取10次随机值之和是:%d,平均值是:%f') % (s1,s1/i1) for j in range(1,10**3+1): p2 = random.choice(range(1,11)) s2 += p2 j1=float(j) print('1到10之间,取1000次随机值之和是:%d,平均值是:%f') % (s2,s2/j1) for k in range(1,10**5+1): p3 = random.choice(range(1,11)) s3 += p3 k1 = float(k) print('1到10之间,取10万次随机值之和是:%d,平均值是:%f') % (s3,s3/k1) # for g in range(1,10**7+1): # p4 = random.choice(range(1,11)) # s4 += p4 # g1 = float(g) # print('1到10之间,取1000万次随机值之和是:%d,平均值是:%f') % (s4,s4/g1) f = 100 * random.random() print("1-100的随机数是: %.2f") % round(f,2) print("1-100的随机数是: %2f") % round(f,2) # 比较下这两者的区别
from quaternion import Quaternion as Q import sys if __name__ == '__main__': q = Q(1,2,3,4) r = Q(0,-2,1,-4) print("\nTest quaternions") print("q = " + str(q)) print("r = " + str(r)) print("\nQuaternion operations and functions") print("q+r = " + str(q+r)) print("q+r = " + str(q+r)) print("q*r = " + str(q*r)) print("-q = " + str(-q)) print("+q = " + str(+q)) print("r/q = " + str(r/q)) print("|q| = " + str(abs(q))) print("conj(q) = " + str(Q.conj(q))) print("exp(q) = " + str(Q.exp(q))) print("log(q) = " + str(Q.log(q))) # print("pow(q,2) = " + str(Q.pow(q,2))) # Not working - returns zeros if sys.version_info[0]>=3: # These don't work in Python 2.7 print("\nQuaternion operations with scalars") print("2+q = " + str(2+q)) print("q-3 = " + str(2+q)) print("2*q = " + str(2*q)) print("q/2 = " + str(q/2))
# SplinesGenerator.py # Author: Tinli Yarrington # Date: 3/22/15 # Dates edited: 3/23/15, 3/24/15, 3/25/15, 3/26/15 # Purpose: user inputs number of vertices and values of sides, and program generates bases splines for those graphs # Notes: # - change program so it can take more than three vertices # - confirm that splines being generated are bases '''def turnToInt(sides): for side in range(0,len(sides)): sides[side] = int(sides[side]) def generateSplines(integerMod, vertices, sides): trivialSpline = [] splines = [] for side in range(0,vertices-1): trivialSpline.append(1) def main(): bar = "+" + ("-"*48) + "+" print(bar) print("|{0:^48}|".format("SPLINES GENERATOR")) print(bar) print() integerMod = eval(input("What is the moduli for this graph? ")) vertices = eval(input("How many vertices does your graph have? ")) sides = input("What are the values of the sides of your graph? (separate each side with a space) ") sides = sides.split(" ") turnToInt(sides) generateSplines(integerMod, vertices, sides) main()''' import itertools def main(): ''' splines = [] moduli = eval(input("What moduli are you using for your graph? ")) vertices = eval(input("How many vertices does your graph have? ")) sides = input("What are the values for the sides of your graph? (please separate each number with a space) ") sides = sides.split(" ") for side in range(0,len(sides)): sides[side] = int(sides[side]) for vertice in range(0,vertices): splines.append([]) for zero in range(0,vertice): splines[vertice].append(0) for one in range(0,vertices): splines[0].append(1) print(splines) for spline in splines: while len(spline) < vertices: for vertice in range(len(spline)-1,vertices-1): for num in itertools.count(1): if (num - spline[vertice-1])%sides[vertice-1] == 0 and num !=spline[vertice-1] and num%sides[vertice] == 0: spline.append(num) break ''' vertices = 3 splines = [] # moduli = eval(input("What moduli are you using for your graph? ")) # vertices = eval(input("How many vertices does your graph have? ")) sides = input("What are the values for the sides of your graph? (please separate each number with a space) ") sides = sides.split(" ") for side in range(0,len(sides)): sides[side] = int(sides[side]) for vertice in range(0,vertices): splines.append([]) for zero in range(0,vertice): splines[vertice].append(0) for one in range(0,vertices): splines[0].append(1) print(splines) for spline in splines: while len(spline) < 3: for vertice in range(len(spline),vertices): for num in itertools.count(1): if len(spline) == (vertices-1) and num%sides[vertice] == 0 and num%sides[vertice-1] == 0: spline.append(num) break elif (num - spline[vertice-1])%sides[vertice-1] == 0 and num != spline[vertice - 1]: print(spline,len(spline), num) spline.append(num) break print(splines) '''for num in itertools.count(1): if num%sides[0] == 0: splines[1].append(num) break for num in itertools.count(1): if (num-splines[1][1])%sides[1] == 0 and num%sides[2] == 0: splines[1].append(num) break for num in itertools.count(1): if (num-splines[2][1])%sides[1] == 0 and num%sides[2] == 0: splines[2].append(num) break print(splines[0], splines[1], splines[2]) for vertice in range(0,vertices): if splines[1][vertice] >= moduli: splines[1][vertice] = splines[1][vertice]%moduli for vertice in range(0,vertices): if splines[2][vertice] >= moduli: splines[2][vertice] = splines[2][vertice]%moduli print(splines[0], splines[1], splines[2])''' main()
# ************数据类型************ # 科学记数法 print(1.23e8) # 字符串:""或''本身只是一种表示,如果字符串中有',那就用""括起来。 print("I'm OK") # 既包含',又包含",用转义字符\ print('I\'m \"OK\"') # 用r''表示''里面的字符不允许转义 print(r'\\\t\\') # 用'''...'''格式表示多行内容 print('''line1 line2 line3''') # 布尔值 print(3 > 2) print(True and True) # 空值None # 变量: a = 123 print(a) a = '456' print(a) x = 10 x = x + 2 print(x) # 除法 1、/ 2、// print(10 / 3) print(10 // 3) # 整数的地板除,只取整数 # 取余 print(10 % 3)
# map和reduce函数: # map:接收两个参数,一个函数,一个Iterable,map将传入的函数作用于每一个元素,并返回新的Iterable def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # 高阶函数 print(r) print(list(r)) print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) # 变为字符串 from functools import reduce def add(x, y): return x + y print(reduce(add, [1, 3, 5, 7, 9])) # reduce把结果继续和序列的下一个元素做累积运算 def fn(x, y): return x * 10 + y print(reduce(fn, [1, 3, 5, 7, 9])) # str->int的函数: def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] print(list(map(char2num, '13579'))) # [1, 3, 5, 7, 9] print(reduce(fn, map(char2num, '13579'))) # 13579 # 整理: # def str2int(s): # def fn(x, y): # return x * 10 + y # # def char2num(s): # return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] # # return reduce(fn, map(char2num, s)) # print(str2int('123456')) # 用lambda函数化简: def str2int(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s)) # filter过滤:高阶函数 # 删掉偶数,只保留奇数: def is_odd(n): return n % 2 == 1 print(list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) # 求素数: def _odd_iter(): # 这是一个生成器:从3开始的奇数序列 n = 1 while True: n = n + 2 yield n # Python中的lambda关键字可以理解为:其功能类似于函数指针。 # lambda的官方翻译是匿名函数,这是相对与正常的函数来说的,举例说明: # 定义一个正常的函数,实现增1运算: # def plus1(x): # return x + 1 # 上面的语句实现了: # 1. # 定义了一个函数,函数名叫:plus1 # 2. # 此函数有一个参数 # 对应的匿名函数语句写作: # lambda x: x + 1 # 注意,这是一个表达式,所以他实际上是做不了任何事情的。。。 # 那么我们如果想调用函数来实现增1运算,分别用正常函数和匿名函数的实现举例如下: # 实名函数实现: # def plus1(x): # return x + 1 # a = 0 # a = plus1(a) # print(a) # 匿名函数实现: # func = lambda x: x + 1 # a = 0 # a = func(a) # print(a) # 结论,匿名函数的用法,既像C语言中的宏定义,又像C语言中的函数指针。 # 将匿名函数和实名函数结合起来使用就更加好玩了,比如: # def plus1(x): # return x + 1 # func = lambda x: plus1(x) # a = 0 # a = func(a) # print(a) # 你看,这不就是函数指针的用法了吗? # C语言有了函数指针就变得灵活无比,同样,将lambda用上之后,python也可以变得同样的灵活。 # 设置断点理解他 def _not_divisible(n): # 筛选函数 return lambda x: x % n > 0 # 如何理解yield关键字:https://www.jianshu.com/p/fb67382a0455 def primes(): yield 2 # 到这里返回一次,之后从这里开始 it = _odd_iter() # 初始化话序列 # print(it) # print(next(it)) # print('while:') # x = 0 while True: n = next(it) # 返回序列第一个数 yield n # print(n) # it1 = filter(_not_divisible(n), it) it = filter(_not_divisible(n), it) # 构造新序列 # num = 0 # for i in it1: # print(i) # num += 1 # if num == 10: # break # print("------------") # x += 1 # if x == 5: # break # # print(it) # # print(next(it)) # num = 0 # print(it==it1) # print('while:') # while num < 10: # print(next(it1),) # num = num + 1 for n in primes(): if n < 100: print(n) else: break
# 排序算法: # python内置的函数:高级函数 print(sorted([12, -5, -62, 124, 65, 30])) # 接收一个key来实现自定义排序:按绝对值排序 print(sorted([12, -5, -62, 124, 65, 30], key=abs)) # 对字符串排序是对其ascii值来排序 # 反向排序,只需制定reverse为True就好: print(sorted([12, -5, -62, 124, 65, 30], reverse=True))
# TODO: 正割法: import matplotlib.pyplot as plt import numpy as np def getValue(x): return x ** 2 - 1.5 * x def paintf(): # TODO: 绘制x轴y轴 x = np.arange(-1, 4, 0.05) y1 = [0 * a for a in x] y = np.arange(-1, 4, 0.05) x1 = [0 * a for a in y] plt.plot(x, y1, '-', color='black') plt.plot(x1, y, '-', color='black') # TODO: 绘制 y = x ** 2 - 1.5 * x 的图像 x = np.arange(0, 3, 0.05) y = [getValue(a) for a in x] # log2(x)图像 plt.plot(x, y, '-b', label="y = x ** 2 - 1.5 * x") # label plt.legend(loc="lower right") paintf() a = 1 b = 3 c = 0 while abs(getValue(b)) > 0.0001: plt.plot([a, b], [getValue(a), getValue(b)], '-r') c = b - ((getValue(b) * (a - b)) / (getValue(a) - getValue(b))) plt.plot([c, c], [0, getValue(c)], '-r') a = b b = c print(c) plt.show()
# 函数: # help(abs) # 调用帮助文档查看abs函数 print(abs(100)) print(abs(-10)) print(max(1, 2, 3, 4)) # max函数直接接受任意多个参数,并返回最大的那个 # 类型转换 print(int('123')) print(str(123)) print(bool(1)) print(bool('')) # 定义函数: def my_abs(x): if not isinstance(x, (float, int)): # 修改的my_abs()函数--异常处理,instance<->示例 raise TypeError('bad operand type') if x >= 0: return x else: return -x # 空函数: def nop(): pass # 返回多个值: import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y + step + math.sin(angle) return nx, ny x, y = move(100, 100, 60, math.pi / 6) print(x) print(y) print(x, y) r = move(100, 100, 60, math.pi / 6) print(r) # 返回值是一个tuple
""" ---------------------------------------------------------------- Caren Groenhuijzen 01-07-2020 Eindopdracht gemaakt voor de leerlijn Python van NOVI Hogeschool ---------------------------------------------------------------- """ import socket as s import pickle as p """This client can connect to the server. It can receive strings and pickles. It can only send strings back to the server. Four errors are caught, a message will let the client know what went wrong.""" HOST = s.gethostname() PORT = 7007 socket = s.socket(s.AF_INET, s.SOCK_STREAM) HEADERSIZE = 10 BUFFER = 1024 try: socket.connect((HOST, PORT)) while True: full_msg = b"" new_msg = True while True: msg = socket.recv(BUFFER) if new_msg: msg_len = int(msg[:HEADERSIZE]) new_msg = False full_msg += msg if len(full_msg) - HEADERSIZE*2 == msg_len: reply_string = "--> " if full_msg[HEADERSIZE:HEADERSIZE*2].decode("utf-8")[0] == 's': full_msg = full_msg.decode("utf-8") print(full_msg[HEADERSIZE * 2:]) if "enter" in full_msg.lower() and "username" in full_msg.lower(): reply_string = "Username: " elif "enter" in full_msg.lower() and "password" in full_msg.lower(): reply_string = "Password: " elif full_msg[HEADERSIZE:HEADERSIZE*2].decode("utf-8")[0] == 'p': received_object = p.loads(full_msg[HEADERSIZE*2:]) if type(received_object) == dict: for key in received_object: print(key) else: print(received_object) socket.send(bytes(f"{len('Object received'):<{HEADERSIZE}}" + "Object received", "utf-8")) break reply = input(reply_string) reply = f"{len(reply):<{HEADERSIZE}}" + reply socket.send(bytes(reply, "utf-8")) new_msg = True full_msg = b"" except ConnectionRefusedError: print("Server is not running. Try running the server first and then the client.") except ConnectionResetError: print("Connection with server lost. \n" "Client will now be disconnected.") except TimeoutError: print("Connection failed, server didn't respond. \n" "This could be caused by the server not having internet access.") except ConnectionAbortedError: print("The server closed the connection.")
class Tile(): """the class for tiles. self variables: mine: if its true it means the tile has a mine, if it has no mine its false visible: the tiles state, meaning if its revealed (1) or not (0) flagged: if the flagged nearby_mines: the amount of mines nearby functions: reveal: the function to swap the state of the tile to be revealed flag: the function to swap the state of the tile to be flagged place_mine: the function to swap the state of the tile to have a mine """ def __init__(self, has_mine=False, visible=False, flagged=False): self.visible = visible self.mine = has_mine self.flagged = flagged self.nearby_mines = 0 def reveal(self): self.visible = True def flag(self): self.flagged = True def deflag(self): self.flagged = False def place_mine(self): self.mine = True def nearby_mines_update(self, amount): self.nearby_mines = amount
'''Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods. Hints:''' class inputString(object): def _init_(cow): cow.bull="" def getString(cow): cow.bull=raw_input() def printString(cow): print cow.bull.upper() moggy=inputString() moggy.getString() moggy.printString()
#Program to perform BFS and Print a spanning tree for a source #!/usr/bin/python class Queue: def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def enqueue(self,item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def neighbors(G,l,src,count,col): count=0 i=0 l=[] j=0 for i in range(1,col+1): if G[src][i]==1: l.insert(j+1,i) j+=1 count+=1 S=[] def BFS(src,Stree): visited=[] for i in range(1,100): visited.insert(1,0) count=0 l=[] Stree[src]=-1 q=Queue() q.enqueue(src) while q.isEmpty==False: p=q.dequeue() neighbors(S,l,p,count,col) for i in range(1,count+1): if l[i]!=src: if visited[l[i]]==0: q.enqueue(l[i]) Stree[l[i]]=p visited[l[i]]=1 #Main G=[] rows=input() cols=input() src=input() for i in range(1,rows+1): P=[] for j in range(1,cols+1): P.insert(j,input()) G.append(P) for r in G: print r Stree=[] BFS(src,Stree) print Stree
io=input("") while(io): n=int(raw_input("enter the year: ")) if n%4==0: if n%400==0: print "its leap year" elif n%100==0: print "not leap year" else: print "its leap year" io=io-1
#Evaluating a postfix expression class stack: def __init__(self): self.items=[] self.t=-1 def push(self,item): self.t+=1 self.items.insert(self.t,item) def pop(self): self.t-=1 def size(self): return self.t def isempty(self): return self.items==[] def top(self): return self.items[self.t] st=stack() s=raw_input() for i in range(0,len(s)): if s[i]>='1' and s[i]<='9': st.push(int(s[i])) else: k=st.top() st.pop() j=st.top() st.pop() if s[i]=='*': c= j*k st.push(c) if s[i]=='+': c= j+k st.push(c) if s[i]=='-': c= j-k st.push(c) if s[i]=='/': c= j/k st.push(c) print st.top()
#merge sort ---- one of the comparison sort # recursion def mergesort(liz): if len(liz) > 1: mid=len(liz)//2 liz1=liz[:mid] liz2=liz[mid:] mergesort(liz1) mergesort(liz2) i=0 j=0 k=0 while i < len(liz1) and j < len(liz2): if liz1[i] >= liz2[j]: liz[k]=liz1[i] k=k+1 i=i+1 else: liz[k]=liz2[j] k=k+1 j=j+1 while i < len(liz1): liz[k]=liz1[i] k=k+1 i=i+1 while j < len(liz2): liz[k]=liz2[j] k=k+1 j=j+1 k=raw_input() ll=k.split(" ") l=[] for i in range(0,len(ll)): l.append(int(ll[i])) mergesort(l) print l
# 标准库(python 常用模块) # 输出格式 # reprlib 模块为大型的或深度嵌套的容器缩写显示提供了 :repr() 函数的一个定制版本 # pprint 模块,用于当输出超过一行的时候,pretty printer 添加断行和标识符,使得数据结构显示的更清晰 # textwrap 模块格式化文本段落以适应设定的屏宽 import pprint t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta','yellow'], 'blue']]] pprint.pprint(t, width=30) import textwrap doc = """The wrap() method is just like fill() except that it returns a list of strings instead of one big string with newlines to separate the wrapped lines.""" print(textwrap.fill(doc, width=40)) # 模版(string 提供的一个灵活多变的模板类 Template) # 格式使用 $ 为开头的 python 合法标识作为占位符,占位符外面的大括号使它可以和其它的字符不加空格混在一起 # 模块中的 safe_substitute() 方法在数据不完整时,不会改变占位符 from string import Template t = Template('Return the $item to ${owner}') d = dict(item = 'unladen swallow') print(t.safe_substitute(d)) # 多线程(详见 python 的 Queue 模块) # 日志 # 默认情况下捕获信息和调试信息并将输出发送到标准错误流 import logging logging.debug('Debugging information') logging.info('Info information') logging.warning('Warning information') logging.error('Error information') logging.critical('Critical error,shutting down') # 列表工具 # list 相当于堆栈 # deque 相当于队列 # bisect 用以存储链表 # heapq 保持链表的最小值总是在 index 为 0 的位置 from heapq import heapify, heappop, heappush data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] heapify(data) heappush(data, -5) [heappop(data) for i in range(3)] # 十进制浮点数算法 # decimal 是一个适用于高精度浮点数运算的模块 # fractions 模块是一个基于有理数的运算 from decimal import * print(Decimal('1.00') % Decimal('.10')) # 0.00 print(1.00 % 0.10) # 0.09999999999999995 getcontext().prec = 36 print(Decimal(1) / Decimal(7)) # 0.142857142857142857142857142857142857 from fractions import Fraction print(Fraction.from_float(0.1)) # 3602879701896397/36028797018963968 print((0.1).as_integer_ratio()) # (3602879701896397, 36028797018963968)
N = raw_input('N: ') if N=="1": print'A' elif N=="2": print'B' elif N=="3": print'C' elif N=="4": print'D' elif N=="5": print'E' else: print'eroor'
"""A recursive decent parser that returns a parse tree Takes rules as a list of tuples (name, rule) and a token list (a list of (token name, token value) pairs) and returns a parse tree of nodes (rule name, value1, value2, ...) where values may be (token, value) or a child node. Rule values are lists of strings (or a single space-separated string), where each string is either a rule name or a token name. For clarity, it is suggested (but not required) that rule names be in lowercase while token names be in uppercase. Rule names may be repeated to specify alternate forms. One rule must be specified as the start rule, which matches the entire token stream. """ class ParseError(Exception): pass def parse(rules, start_rule, tokens): options = [ tree for tree, tokens_left in _parse(rules, start_rule, list(tokens)) if not tokens_left ] if not options: raise ParseError("Unable to parse input") elif len(options) > 1: raise ParseError("Ambiguous match") tree, = options return tree def _parse(rules, rule, tokens): if not tokens: return token_name, token_value = tokens[0] if rule == token_name: yield tokens[0], tokens[1:] return for name, parts in rules: if name != rule: continue for values, tokens_left in _parse_rule(rules, parts, tokens): yield (rule,) + values, tokens_left def _parse_rule(rules, rule_parts, tokens): if not rule_parts: yield (), tokens return sub_rule = rule_parts[0] for subtree, part_tokens in _parse(rules, sub_rule, tokens): for values, tokens_left in _parse_rule(rules, rule_parts[1:], part_tokens): yield (subtree,) + values, tokens_left def pprint_tree(tree, indent=0): """Helper function that pretty-prints a parse tree, for debugging""" name, values = tree[0], tree[1:] if len(values) == 1 and isinstance(values[0], basestring): print "{:<{indent}s}{} {}".format("", name, values[0], indent=indent) else: print "{:<{indent}s}{}:".format("", name, indent=indent) for value in values: pprint_tree(value, indent=indent+1)
"""Implements an infinite set which contains all but a finite set of elements""" from partialorder import partial_ordering # partial_ordering decorator fills in __lt__ and __gt__ based on __le__ and __ge__ @partial_ordering class UniverseSet(object): """This class acts like a set in most ways. However, all operations are done against a virtual "Universe Set" that contains every value. The main point of this kind of set is to exclude things from it specifically, and possibly intersect it with a finite set (to yield a finite set) later. Internals note: The set of things NOT in the universe set are kept track of as 'coset'. """ def __init__(self, coset=()): """The optional arg coset sets the initial coset (set of excluded items) but is intended only for internal use. Better to use UniverseSet() - exclude_set.""" self.coset = set(coset) def __and__(self, other): if isinstance(other, UniverseSet): return UniverseSet(self.coset | other.coset) return other - self.coset __rand__ = __and__ def __contains__(self, value): return value not in self.coset def __eq__(self, other): # we could let partial_ordering fill this in, but checking cosets are equal is much more efficient # than "both are subsets of each other". if isinstance(other, UniverseSet): return self.coset == other.coset return False def __le__(self, other): return self.issubset(other) def __ge__(self, other): return self.issuperset(other) def __or__(self, other): if isinstance(other, UniverseSet): return UniverseSet(self.coset & other.coset) return UniverseSet(self.coset & other) __ror__ = __or__ def __repr__(self): return "<UniverseSet() - %s>" % repr(self.coset) __str__ = __repr__ def __sub__(self, other): if isinstance(other, UniverseSet): return other.coset - self.coset return UniverseSet(self.coset | other) def __rsub__(self, other): return other & self.coset def __xor__(self, other): if isinstance(other, UniverseSet): return self.coset ^ other.coset return UniverseSet(self.coset & other) __rxor__ = __xor__ def add(self, value): self.coset.discard(value) def copy(self): return UniverseSet(self.coset) def difference(self, *others): ret = self for other in others: ret -= other def intersection(self, *others): ret = self for other in others: ret &= other return ret def isdisjoint(self, other): return not self & other def issubset(self, other): if isinstance(other, UniverseSet): return other.coset.issubset(self.coset) return False def issuperset(self, other): if isinstance(other, UniverseSet): return self.coset.issubset(other.coset) return self.coset.isdisjoint(other) def pop(self): raise ValueError("Cannot pop arbitrary value from infinite set") def remove(self, value): if value not in self: raise KeyError(value) self.discard(value) def discard(self, value): self.coset.add(value) def symmetric_difference(self, other): return self ^ other def union(self, *others): ret = self for other in others: ret |= other return ret def update(self, *others): self.coset = self.union(*others).coset # NOTE: We don't implement the following set methods: # clear # intersection_update # difference_update # symmetric_difference_update # as they require (or may require) updating in-place from an infinite set to a finite one, which we can't do.
"""A tool for working with iterators as though they are lists Sometimes you have a lazy iterator, which you want to use in some function that expects a list or tuple (or other indexable iterable). One solution is to convert the iterator to a list, but then you lose laziness. This LazyList wrapper takes an iterable (with optional len) and only fetches items as needed. It supports indexing, slicing, len(), etc.""" from itertools import count INF = float('inf') class LazyList(object): """Wraps an iterable in a list-like wrapper which only fetches items as needed.""" def __init__(self, iterable, length=None): """iterable can be any iterable to wrap. Optional arg length allows operations involving the length of the iterable to be done without having to exhaust the iterable to return its length. Note this doesn't apply if the iterable has a defined len(). As a special case, length may be the string 'inf' or a float INF. This indicates the iterable cannot be exhausted, and will cause certain operations (eg. lazylist[-1]) to raise a ValueError. """ try: length = len(iterable) except TypeError: pass if length == 'inf': length = INF self.length = length self.iterator = iter(iterable) self.items = [] def __repr__(self): return "<{}({!r}) read {}/{}>".format(type(self).__name__, self.iterator, len(self.items), "?" if self.length is None else self.length) def __len__(self): if self.length == INF: raise ValueError("Can't take len() of infinite list") while self.length is None: self.fetch_next() # exhaust iterable return self.length def __iter__(self): try: for x in count(): yield self[x] except IndexError: return def __getitem__(self, index): if isinstance(index, slice): return self.__getslice__(index.start, index.stop, index.step) if not isinstance(index, (int, long)): raise IndexError("{} indices must be int, not {}".format( type(index).__name__, type(self).__name__)) if index < 0: if self.length == INF: raise ValueError("Infinite list does not support negative indices") index += len(self) while index >= len(self.items): if self.length is not None and index >= self.length: raise IndexError("{} index out of range".format(type(self).__name__)) self.fetch_next() # either len(self.items) will increase or self.length will be set not None return self.items[index] def __getslice__(self, start, stop, step=None): # We can't simply use slice.indicies() since we don't want to compute len unless we have to. if hasattr(start, '__index__'): start = start.__index__() if hasattr(stop, '__index__'): stop = stop.__index__() if hasattr(step, '__index__'): step = step.__index__() if any(value is not None and not isinstance(value, (int, long)) for value in (start, stop, step)): raise TypeError("slice indices must be integers or None or have an __index__ method") if step == 0: raise ValueError("slice step cannot be zero") elif step is None: step = 1 elif step < 0: return reversed(list(self.__getslice__(stop, start, -step))) if start is None: start = 0 elif start < 0: if self.length == INF: raise ValueError("Infinite list does not support negative indices") start += len(self) if stop is not None and stop < 0: if self.length == INF: stop = None else: stop += len(self) return LazyList(self[x] for x in (count(start, step) if stop is None else xrange(start, stop, step))) def fetch_next(self): """Get next element from iterator and save it in items. Raises AssertionError if StopIteration reached and length does not match. Otherwise, sets length on StopIteration. """ try: item = self.iterator.next() except StopIteration: if self.length is not None and self.length != len(self.items): raise AssertionError("Incorrect length provided: Expected {}, got {}".format( self.length, len(self.items))) self.length = len(self.items) else: self.items.append(item)
import os.path import pathlib from os import path def saveToFile(filePath, textToSave): # Check if current file path exists file = pathlib.Path(filePath) if file.exists(): print("File exists") else: print("File doesn't exist. Creating file") # Open the file and overwrite the current text file = open(filePath, "w") file.writelines(textToSave) file.close() # Check that current text in file is same as expected data if textToSave == open(filePath).read(): print("File and text are the same") return True else: print("File and text are different") return False def readFile(filePath): # Check if current file path exists file = pathlib.Path(filePath) if file.exists(): print("File exist") file = open(filePath, "r") print(file.read()) file.close() else: print("File doesn't exist") print("") #Location of file saveToFile("C:\\Users\\ryanh\\OneDrive\\Documents\\test2.txt", "asdfqewd") #readFile("C:\\Users\\ryanh\\OneDrive\\Documents\\testwe2.txt")
#!/usr/bin/python3 from CS312Graph import * import time import itertools # --------------------- objects ---------------------------- class Node: id = None dist = None vertex = None def __init__(self, id, dist, vertex): self.id = id self.dist = dist self.vertex = vertex def updateDist(self, dist): self.dist = dist class PriorityQueue: def makeQueue(self, vertices): print("make queue") def insert(self, dist, vertex): print("insert") def decreaseKey(self, key, value): print("decrease key") def deleteMin(self): print("delete min") def size(self): print("size") class HeapPriorityQueue(PriorityQueue): def makeQueue(self, vertices): x = None def insert(self, dist, vertex): x = None def decreaseKey(self, key, value): x = None def deleteMin(self): x = None def size(self): x = None # return the element with the smallest key and remove it from the set class ArrayPriorityQueue(PriorityQueue): nodes = [] def makeQueue(self, vertices): for v in vertices: # node = Node(float("inf"), v) node = Node(v.node_id, float("inf"), v) self.nodes.append(node) def insert(self, dist, vertex): node = self.Node(vertex.node_id, dist, vertex) self.nodes.append(node) self.nodes.sort(key=lambda x: x.dist, reverse=False) def decreaseKey(self, key, value): for node in self.nodes: if node.id == value: node.dist = key self.nodes.sort(key=lambda x: x.dist, reverse=False) def deleteMin(self): minNode = self.nodes.pop(0) return minNode def size(self): return len(self.nodes) def printQ(self): print("printing queue") for n in self.nodes: print(n.dist, n.id) print("\n") # -------------- network routing ------------------------- class NetworkRoutingSolver: def __init__( self): pass def initializeNetwork( self, network ): assert( type(network) == CS312Graph ) self.network = network def getShortestPath( self, destIndex ): self.dest = destIndex # TODO: RETURN THE SHORTEST PATH FOR destIndex # INSTEAD OF THE DUMMY SET OF EDGES BELOW # IT'S JUST AN EXAMPLE OF THE FORMAT YOU'LL # NEED TO USE path_edges = [] total_length = 0 node = self.network.nodes[self.source] edges_left = 3 while edges_left > 0: edge = node.neighbors[2] path_edges.append( (edge.src.loc, edge.dest.loc, '{:.0f}'.format(edge.length)) ) total_length += edge.length node = edge.dest edges_left -= 1 return {'cost':total_length, 'path':path_edges} def computeShortestPaths( self, srcIndex, use_heap=False ): self.source = srcIndex t1 = time.time() # TODO: RUN DIJKSTRA'S TO DETERMINE SHORTEST PATHS. # ALSO, STORE THE RESULTS FOR THE SUBSEQUENT # CALL TO getShortestPath(dest_index) self.Dijkstra(use_heap) t2 = time.time() return (t2-t1) def Dijkstra(self, use_heap): # prioity queue operations # Insert: add a new element to the set # Decrease-key: accommodate the decrease # in key value of a particular element # Delete-min: return the element with the # smallest key, and remove it from the set # dist = dict() prev = dict() graph = self.network vertices = self.network.nodes print(graph) print("/n") # graph = (V, E) # finding all distances from s (starting node) to u for v in vertices: dist[v.node_id] = float("inf") prev[v.node_id] = None dist[self.source] = 0 # if use_heap: # queue = self.HeapPriorityQueue().makeQueue(dist, vertices) # else: # queue = self.ArrayPriorityQueue().makeQueue(dist, vertices) queue = ArrayPriorityQueue() queue.makeQueue(vertices) queue.decreaseKey(0, self.source) queue.printQ() while queue.size() > 0: u = queue.deleteMin() for edge in u.vertex.neighbors: if (dist[edge.dest.node_id] > dist[edge.src.node_id] + edge.length): dist[edge.dest.node_id] = dist[edge.src.node_id] + edge.length prev[edge.dest.node_id] = edge.src queue.decreaseKey(dist[edge.dest.node_id], edge.dest.node_id) queue.printQ() print("dist") for a, b in dist.items(): print(a, b) # H = makequeue(V) (using dist-values as keys) <- build a priority queue out of the given elements with the given key values # while H is not emty: # u = deletemin(H) <- return the element with the smallest key and remove it from the set # for all edges (u,v) in E: # if (dist(v) > dist(u) + l(u,v): # dist(v) = dist(u) + l(u,v) # prev(v) = u # decreasekey(H,v) return 0 def arrayDijkstra(self): return 0
#!/usr/bin/python2.7 # -*- coding: latin-1 -*- import sys #purpose of this exercice is to validate if that an input is made of only numbers #Of course there is a lot of better way to do that, but at this step, the studdents don't have # enough background to do it better. #the number to be filled by the user number = 0 isInputOk = False #So far, we don't know other way to loop, so let's enter into the loop like that while not isInputOk: #As long as the input is not ok isInputOk = True #At start, let's assume that the input is correct number = raw_input("What is you number ?\n ") index = 0 tableSize = len(number) #As we just learnt during the training, a string is a table #Let's iterate over each letter of the numberTable, as long as input is correct while (index < tableSize) and (isInputOk == True): if not number[index] in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: print "You just typed a wrong character : " + number[index] isInputOk = False index += 1 print "Your number is :" + number
nome = input('Digite o seu nome: ') idade = int(input('Qual a sua idade: ')) idade_limite = 18 if idade >= idade_limite: print(f'{nome} pode solicitar empréstimo...') else: print(f'{nome} não pode solicitar o empréstimo...')
num1 = 0 num2 = 0 if not num1 != num2: print('Retorno 1') else: print('Retorno 2')
# -*- coding: utf-8 -*- def compositeWallSeries(resistanceList): """This function takes as input a list of resistances, each of which is a dictionary. It computes the series of the resistances token as input. """ R_series=0 resistancesResults = {} for resistance in resistanceList: A = resistance["area"] L = resistance["length"] k = resistance["k"] R= round(L/(k*A),2) R_series=R_series+R nameOfResistance = resistance["name"] resistancesResults[nameOfResistance] = round(R,2) R_tot=R_series resistancesResults["R_total"] = round(R_tot,2) return resistancesResults resistancesResults= round(R_series,2) return resistancesResults def compositeWallParallel(resistanceList): """This function takes as input a list of resistances, each of which is a dictionary. It computes the parallel of the resistances token as input. """ resistancesResults = {} R_tot_inv=0 for resistance in resistanceList: A = resistance["area"] L = resistance["length"] k = resistance["k"] R= round(L/(k*A),3) R_inv= 1/(R) R_tot_inv += R_inv nameOfResistance = resistance["name"] resistancesResults[nameOfResistance] = round(R,2) R_tot = 1/R_tot_inv resistancesResults["R_total"] = round(R_tot,2) return resistancesResults def compositeWall(resistanceListSeries,resistanceListParallel): """This function takes as input two lists of resistances, each of which is a dictionary. It computes the series of the 1st list, the parallel of 2nd and sum it to return the total resistance given by the series of the two resistances computed. res={"name":"str","type":"'cond' or 'conv'","length":m,"area":m^2,"k":W/(m*deg°C)} resistance given is deg°C/W """ composite={} rSeries=compositeWallSeries(resistanceListSeries) rParallel=compositeWallParallel(resistanceListParallel) rSeriesTot=rSeries["R_total"] rParallelTot=rParallel["R_total"] rTot=rSeriesTot+rParallelTot composite["series"]=rSeries composite["parallel"]=rParallel composite["rWall"]=rTot return composite def wallConvection(resistanceConv): resistanceResult={} h=resistanceConv["hConv"] A=resistanceConv["area"] name=resistanceConv["name"] R=round(1/float(h)/float(A),2); resistanceResult[name]=round(R,4) resistanceResult["Rconv"]=round(R,4) return resistanceResult def wallResistance(listSeries,listParallel,convInt,convExt): wall=compositeWall(listSeries,listParallel) rWall=wall["rWall"] conv1=wallConvection(convInt) rConv1=conv1["Rconv"] conv2=wallConvection(convExt) rConv2=conv2["Rconv"] rTot=rWall+rConv1+rConv2 tot={} tot["wall"]=wall tot["convInt"]=conv1 tot["convExt"]=conv2 tot["rTot"]=rTot return tot Ri={"name":"Ri","type":"conv","area":1.25,"hConv":10} R1={"name":"R1","type":"cond","length":0.03,"area":1.25,"k":0.026} R2={"name":"R2","type":"cond","length":0.02,"area":1.25,"k":0.22} R3={"name":"R3","type":"cond","length":0.16,"area":0.075,"k":0.22} R4={"name":"R4","type":"cond","length":0.16,"area":1.1,"k":0.72} R5={"name":"R5","type":"cond","length":0.16,"area":0.075,"k":0.22} R6={"name":"R6","type":"cond","length":0.02,"area":1.25,"k":0.22} Ro={"name":"Ro","type":"conv","area":1.25,"hConv":25} series=[R1,R2,R6] parallel=[R3,R4,R5] a=wallResistance(series,parallel,Ri,Ro)
########################################################################################################################################## # Basically to understand the Class, Inheritance # # @lessons learned: # Python does NOT support method overloading... aka CompileTime Polymorphism... # https://www.geeksforgeeks.org/python-method-overloading/ # # @date Sun, 12Jan2020 @ 01:15 AM IST # @version 1.0 # @author VMP Consulting # ########################################################################################################################################## class Shapes(): myGreetings = "Hi, Welcome To Coindsyz!!!" def describeSelf(self): print("\nHi, This is the class Shapes, and I would be the PARENT class for my subclasses, " + "viz., Triangle, ReversedTriangle, Square, Rectangle, Forward and Backward slashes...") #Note: A Private method in python gets defined by preceding doubleunderscore to the method name...for instance, __myMethod(self) def __describeSelfPrivate(self, pGreetings): print ("\n\nHi, I'm an overloaded method (note: OVERLOADING (of methods) always happens WITHIN THE SAME CLASS) and " + "the greeting message I've received is : " + pGreetings + " and I happen to have a PRIVATE access, which means" + "I'm not accessible beyond this boundaries of this class, either by it's child classes or other classes outside of this one...") def callAllMethodsOfTheClass(self): describeSelf() __describeSelfPrivate(myGreetings) # The overloaded version of the method describeSelf() are commented out, since, we understood now that, Python does not support method overloading... # def describeSelf(self, pGreetings, pName): # print ("\nHi, I'm one more version of overloaded method but, the difference here is, my access is PROTECTED, which means, I'm available to " + # "all of the child classes, which are getting inherited from me, the parent class, called Shapes...\n" + # "do note that, just because I'm having one more extra parameter from my sibling method, this overloading becomes possible..." + # "Otherwise, If I happen to have a same set of parameters as my sibiling method, you would get an compilation error..." + # "so, do note that, only when the signature of the method happen to be different, the OVERLOADING becomes a possibility..." + # "methods, with same signature, can never be called/make overloading possible...") class Triangle(Shapes): def describeSelf(self): print("\nHi, This is the Triangle class, which is the CHILD class of my PARENT class called SHAPES..." + "and by RETAINING THE SAME METHOD SIGNATURE as that of my PARENT class, I would be OVERRIDING the implementation of this " + "method, which has my own (child) version of the implementation, which is different from the implementation of my PARENT class... ") class Square (Shapes): def printYourShape(): print ("\nHi, I'm A Square!!!") myGreetings = "Hi, Welcome To Coindsyz!!!" myName = "M. Nachimuthu" print ("OOPS Training Version Three"); myShapes = Shapes() myShapes.describeSelf() myShapes.callAllMethodsOfTheClass() myTriangle = Triangle(); myTriangle.describeSelf() mySquare = Square(); mySquare.describeSelf(); #input();
# Monta a matriz com todos os valores inicialmente iguais a zero def montar_matriz(linhas, colunas): matriz = [] for i in range(linhas): linha = [] for j in range(colunas): linha.append(0) matriz.append(linha) return matriz # Monta o distanciamento def montar_distanciamento(matriz, linhas, colunas): for i in range(linhas): for j in range(colunas): # Verifica se esta na primeira linha if i == 0: # Verifica se esta na primeira coluna if j == 0: matriz[i][j] = 1 else: # Verifica se tem pessoa ao lado if matriz[i][j-1] == 1: matriz[i][j] = 0 else: matriz[i][j] = 1 else: # Verifica se esta na primeira coluna if j == 0: # Verifica o primeiro lugar da linha anterior if matriz[i-1][j] == 1: matriz[i][j] = 0 else: matriz[i][j] = 1 else: # Verifica se tem pessoa ao lado if matriz[i][j-1] == 1: matriz[i][j] = 0 else: matriz[i][j] = 1 # Imprime a matriz como solicitado def imprimir_matriz(matriz, linhas, colunas): for i in range(linhas): for j in range(colunas): if(j == colunas - 1): print('%d' %matriz[i][j]) else: print('%d ' %matriz[i][j], end = '') # Verifica a quantidade de vagas def verifica_quantidade_vagas(matriz, linhas, colunas, quantidade_inscritos): quantidade_de_vagas = 0 for i in range(linhas): for j in range(colunas): if matriz[i][j] == 1: quantidade_de_vagas = quantidade_de_vagas + 1 if quantidade_de_vagas == quantidade_inscritos: return 'Todos já estão em seus lugares e a palestra ja pode começar!' elif quantidade_de_vagas > quantidade_inscritos: return 'Ainda temos {} vagas para assistir a nossa palestra'.format(quantidade_de_vagas - quantidade_inscritos) else: return 'A equipe NEPRaE está disponibilizando {} cadeiras para que todos assistam a palestra'.format(quantidade_inscritos - quantidade_de_vagas) # Programa principal def main(): # Leitura dos dados linha_lida = input() quantidade_inscritos = int(input()) valores = linha_lida.split(' ') linhas = int(valores[0]) colunas = int(valores[1]) # Monta a matriz matriz = montar_matriz(linhas, colunas) # Aplica o distanciamento montar_distanciamento(matriz, linhas, colunas) # Imprime a matriz imprimir_matriz(matriz, linhas, colunas) # Imprime a informacao sobre as vagas print(verifica_quantidade_vagas(matriz, linhas, colunas, quantidade_inscritos)) main()
#!/usr/bin/python # -*- coding=utf8 -*- """ # Author: wanghan # Created Time : 2017年03月27日 17:43:27 # File Name: 默认参数.py # Description: """ def power(x,n=2): s = 1 while n > 0: s = s*x n = n - 1 return s print(power(2))
#!/usr/bin/python """Implements k-fold cross-validiation and Ditterch's 5x2 cross-validiation method. """ import random def _buildFolds(inputData, k=10): """Return a list of folds. Each fold is a list of examples. The inputData must be list-like, meaning that it's type can be the built-in list or a TrainingSet, which inherits from list. The return value is a list of k folds, where the union of all the k folds is the whole inputData. >>> from TrainingSet import TrainingSet >>> training = TrainingSet('Datasets/votes-train0.csv') >>> folds = _buildFolds(training) >>> len(folds) 10 >>> [ len(fold) for fold in folds ] [35, 35, 35, 35, 35, 35, 35, 34, 34, 34] >>> sum([ len(fold) for fold in folds ]) 347 >>> sum([ len(fold) for fold in folds ]) == len(training) True """ # make a copy of the data set so that we don't shuffle original data data = inputData[:] random.shuffle(data) # Initialize the folds to empty lists folds = [] for i in range(k): folds.append([]) # Loop over data and build up the folds for i in range(len(data)): index = i % k folds[index].append(data[i]) return folds def kFold(inputData, k=10): """This is the traditional k-fold cross-validiation method. It is implemented as a generator, so loop through it like so: >>> for training, validation in kFold(range(10)): ... print len(training), len(validation) ... 9 1 9 1 9 1 9 1 9 1 9 1 9 1 9 1 9 1 9 1 >>> from TrainingSet import TrainingSet >>> training = TrainingSet('Datasets/votes-train0.csv') >>> for t,v in kFold(training, k=5): ... t.extend(v); print t.sort() == training.sort() ... True True True True True """ uniqueFolds = _buildFolds(inputData, k) for i in range(k): training = [] validation = [] for j in range(k): if i != j: training.extend(uniqueFolds[j]) else: validation.extend(uniqueFolds[j]) yield training, validation def ditterch5x2(inputData): """Create Ditterch's 5x2 cross validation set. Performs 2-fold cross-valdiation 5 times. Of the 2 folds, each one is used as the training set once, while the other is used as the validation set. 10 training/validation pairs are yielded through a generator. >>> from TrainingSet import TrainingSet >>> training = TrainingSet('Datasets/votes-train0.csv') >>> len(training) 347 >>> for t,v in ditterch5x2(training): ... print len(t), len(v) ... 174 173 173 174 174 173 173 174 174 173 173 174 174 173 173 174 174 173 173 174 >>> for t,v in ditterch5x2(training): ... t.extend(v); print t.sort() == training.sort() ... True True True True True True True True True True """ for i in range(5): fold1, fold2 = _buildFolds(inputData, k=2) yield fold1, fold2 yield fold2, fold1 # Some more tests __test__ = { "simple-buildFolds" : """ >>> folds = _buildFolds(range(32)) >>> len(folds) 10 >>> [ len(fold) for fold in folds ] [4, 4, 3, 3, 3, 3, 3, 3, 3, 3] >>> sum([ 19 in fold for fold in folds ]) 1 >>> sum([ sum(fold) for fold in folds ]) == sum(range(32)) True """, "simple-kFold" : """ >>> for t,v in kFold(range(102), 20): ... print len(t), len(v) ... 96 6 96 6 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 97 5 >>> from TrainingSet import TrainingSet >>> training = TrainingSet('Datasets/titanic.csv') >>> for t,v in kFold(training, k=30): ... print len(t), len(v) ... 2127 74 2127 74 2127 74 2127 74 2127 74 2127 74 2127 74 2127 74 2127 74 2127 74 2127 74 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 2128 73 >>> for t,v in kFold(training, k=30): ... print len(t) + len(v) == len(training) ... True True True True True True True True True True True True True True True True True True True True True True True True True True True True True True """, } def _test(): """Run the tests in the documentation strings.""" import doctest return doctest.testmod(verbose=True) if __name__ == "__main__": try: __IP # Are we running IPython? except NameError: _test() # If not, run the tests
################################################################################################## ########################### Variable Practice ######################################### ################################################################################################## ########################### Strings ######################################### #1) Create a variable named greeting and assign it a string with the value of Hello, remember to use quotes around the string greeting = "hello," #2) Use the print function to display the greeting variable to the screen print(greeting) #3) Create another variable called name and assign it the value of your name #4) Use the print funciton to display both the greeting and the name, use the + operator to concatenate the two strings #5) Notice that in the output above the two strings are stuck together without a space in between, fix it by # concatenating a space in between the two variables #6) Try using the multiplication operator on your greeting variable, see what happens when you print greeting * 3 ########################### Integers ######################################### #7) Create a variable named x and assign it the value 7 #8) Use the print function to display the value of x to the screen #9) Create a another variable named y and assign it the value 3 #10) Create a variable named result and assign it the value of x / y #11) Use the print funciton to display the value of result #14) Re-assign the value of result to x % y (% is the modulus operator) #15) Use the print funciton to display the value of result
# 找出数组中的第一个重复数字,限制,n个数的数组,所有数字都在0~n内 # 思路:用一个指针i从前往后遍历,设指向的数字为m,直到找到第一个m与i不同的位置 # 将m交换到其下标位置处,若m与其下标位置数已经相同,则停止输出,否则循环 class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): # 思路:遍历整个数组,下标i,值m,若i==m,判断下一个元素, # 否则将m放到与下标相同的位置上 i = 0 length = len(numbers) while (i < length): m = numbers[i] if m == i: i = i + 1 else: # 交换时判断是否相等,如果相等则重复了 temp = numbers[m] if temp == m: # 找到一个重复的函数就停止函数 duplication[0] = m return True numbers[m] = m numbers[i] = temp i = i + 1 return False
# 根据前序和中序遍历重构二叉树 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here # 思路:前序遍历的首个元素是根节点,在中序遍历中找到该节点,确定左右子树节点个数 # 这时又分别得到左右子树的前中遍历字符串,递归处理 # 如果遍历序列为空,则是空树,返回None pre = ''.join(pre) tin = ''.join(tin) if (pre == '') & (tin == ''): return None # 对任意子树,根为前序遍历首个元素 x = pre[0] node = TreeNode(x) # 元素不重复,直接根据指定元素拆分得到左右子树中序遍历序列 inorders = tin.split(x) # 根据左右子树个数截取前序遍历序列 left_count = len(inorders[0]) # [:]如果截取失败自动返回空字符串'',不用判断左右子树是否为空 left_pre = pre[1:1 + left_count] right_pre = pre[1 + left_count:] # 递归处理左右子树 node.left = self.reConstructBinaryTree(left_pre, inorders[0]) node.right = self.reConstructBinaryTree(right_pre, inorders[1]) return node # n1 = TreeNode(1) # n2 = TreeNode(2) # n3 = TreeNode(3) # n1.right = n2 # n2.left = n3 def trace_tree(root): if root == None: return trace_tree(root.left) print(root.val) trace_tree(root.right) solution = Solution() root = solution.reConstructBinaryTree('123', '132') print(root)
# 求fib第n项 # 思路:生成一个39项的数字,从前往后遍历生成 # -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here l = [0 for i in range(n + 1)] l[0] = 0 if n > 0: l[1] = 1 i = 2 while i <= n: l[i] = l[i - 1] + l[i - 2] i = i + 1 return l[n] s = Solution() print(s.Fibonacci(0))
class AddEvenNum: def evenNumber(self): allEvenNumber=[] for x in range(10,20): # print(x) if x%2==0: allEvenNumber.append(x) # print(x) return allEvenNumber # if __name__=="__main__": # evenNumber()
class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print 'Sorry, minimum balance must be maintained.' else: BankAccount.withdraw(self, amount) class A: def f(self): return self.g() def g(self): return 'A' class B(A): def g(self): return 'B' a = A() b = B() print a.f(), b.f() print a.g(), b.g()
class BankAccount: def __init__(self): self.balance = 0 def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance ''' >>> a = BankAccount() >>> b = BankAccount() >>> a.deposit(100) 100 >>> b.deposit(50) 50 >>> b.withdraw(10) 40 >>> a.withdraw(10) 90 '''
#main.py from fraction import Fraction def H(n): h = Fraction(0, 1) for k in range(1, n + 1): h += Fraction(1, k) return h def T(n): t = Fraction(0, 1) k = 0 while(k <= n): t += Fraction(1, 2) ** k k += 1 return t def Z(n): z = Fraction(0, 1) for k in range(0, n + 1): z += Fraction(1, 2) ** k return Fraction(2, 1) - z def R(n, b): r = Fraction(0, 1) for k in range(1, n + 1): r += Fraction(1, k) ** b return r #Main Code if __name__ == "__main__" : print('Welcome to Fun with Fractions!') valid = False while not valid: try: userInput = int(input("Enter Number of iterations (integer>0):\n")) if userInput > 0: valid = True except ValueError: valid = False print( 'H(' +str(userInput) + ')=' + str(H(userInput))) print( 'H(' +str(userInput) + ')~=' + str(H(userInput).approximate())) print( 'T(' +str(userInput) + ')=' + str(T(userInput))) print( 'T(' +str(userInput) + ')~=' + str(T(userInput).approximate())) print( 'Z(' +str(userInput) + ')=' + str(Z(userInput))) print( 'Z(' +str(userInput) + ')~=' + str(Z(userInput).approximate())) for i in range(userInput, userInput + 1): print( 'R(' + str(userInput) + ',' + str(i) +')=' + str(R(userInput, i))) print( 'R(' + str(userInput) + ',' + str(i) +')~=' + str(R(userInput, i).approximate()))
#!/usr/bin/python3 """ function that append a strig to a file """ def append_write(filename="", text=""): """ appending to a file """ with open(filename, mode='a', encoding="UTF8") as myfile: return myfile.write(text)
#!/usr/bin/python3 """ function that write a str to a file """ def write_file(filename="", text=""): """ writing to a file """ with open(filename, mode='w', encoding="UTF8") as myfile: return myfile.write(text)
################################################################################ # # blank_gen.py # A barebones D&D Monster Generator using statblock5e # Only the monster name is filled in, all other monster information must be # inserted into the code manually. # # Usage: python blank_gen.py [monster name] # If there is a space ine the monster name, for example: chain devil # Use a period instead of space. That is: chain.devil # # This generator is developed by Shunman Tse (RiasKlein) # https://github.com/riasklein # Statblock5e code is by Val Markovic (Valloric) # https://github.com/Valloric # # Version 1.3 # ################################################################################ import sys # print_usage_instructions # Function prints the usage instructions def print_usage_instructions (): print ("Correct Usage:\tpython blank_gen.py [monster name]") if len(sys.argv) < 2: print ("Usage Error:\tThe program needs a monster name.") print_usage_instructions() sys.exit() # According to the usage instructions, the monster name is the second argument monster_name = sys.argv[1] # Get the monster name from arguments # Convert periods to spaces monster_name = monster_name.replace ('.', ' ') # Capitalize the first letter of every word in monster name list = [word[0].upper() + word[1:] for word in monster_name.split()] monster_name = " ".join(list) # Now we must create a HTML file with that monster's name filew = open (monster_name.lower() + ".html", 'w') ################################################################################ # Writing the formatting code into the HTML file ################################################################################ filew.write( """<!DOCTYPE html> <html><head><link href="https://fonts.googleapis.com/css?family=Libre+Baskerville:700" rel="stylesheet" type="text/css"/><link href="http://fonts.googleapis.com/css?family=Noto+Sans:400,700,400italic,700italic" rel="stylesheet" type="text/css"/><meta charset="utf-8"/> <title>""") filew.write(monster_name) filew.write( """</title><style> body { margin: 0; } stat-block { margin-left: 20px; margin-top: 20px; } </style></head><body><template id="tapered-rule"> <style> svg { fill: #922610; stroke: #922610; margin-top: 0.6em; margin-bottom: 0.35em; } </style> <svg height="5" width="400"> <polyline points="0,0 400,2.5 0,5"></polyline> </svg> </template><script> (function(window, document) { var elemName = 'tapered-rule'; var thatDoc = document; var thisDoc = (thatDoc.currentScript || thatDoc._currentScript).ownerDocument; var proto = Object.create(HTMLElement.prototype, { createdCallback: { value: function() { var template = thisDoc.getElementById(elemName); var clone = thatDoc.importNode(template.content, true); this.createShadowRoot().appendChild(clone); } } }); thatDoc.registerElement(elemName, {prototype: proto}); })(window, document); </script><template id="top-stats"> <style> ::content * { color: #7A200D; } </style> <tapered-rule></tapered-rule> <content></content> <tapered-rule></tapered-rule> </template><script> (function(window, document) { var elemName = 'top-stats'; var thatDoc = document; var thisDoc = (thatDoc.currentScript || thatDoc._currentScript).ownerDocument; var proto = Object.create(HTMLElement.prototype, { createdCallback: { value: function() { var template = thisDoc.getElementById(elemName); var clone = thatDoc.importNode(template.content, true); this.createShadowRoot().appendChild(clone); } } }); thatDoc.registerElement(elemName, {prototype: proto}); })(window, document); </script><template id="creature-heading"> <style> ::content > h1 { font-family: 'Libre Baskerville', 'Lora', 'Calisto MT', 'Bookman Old Style', Bookman, 'Goudy Old Style', Garamond, 'Hoefler Text', 'Bitstream Charter', Georgia, serif; color: #7A200D; font-weight: 700; margin: 0px; font-size: 23px; letter-spacing: 1px; font-variant: small-caps; } ::content > h2 { font-weight: normal; font-style: italic; font-size: 12px; margin: 0; } </style> <content select="h1"></content> <content select="h2"></content> </template><script> (function(window, document) { var elemName = 'creature-heading'; var thatDoc = document; var thisDoc = (thatDoc.currentScript || thatDoc._currentScript).ownerDocument; var proto = Object.create(HTMLElement.prototype, { createdCallback: { value: function() { var template = thisDoc.getElementById(elemName); var clone = thatDoc.importNode(template.content, true); this.createShadowRoot().appendChild(clone); } } }); thatDoc.registerElement(elemName, {prototype: proto}); })(window, document); </script><template id="abilities-block"> <style> table { width: 100%; border: 0px; border-collapse: collapse; } th, td { width: 50px; text-align: center; } </style> <tapered-rule></tapered-rule> <table> <tbody><tr> <th>STR</th> <th>DEX</th> <th>CON</th> <th>INT</th> <th>WIS</th> <th>CHA</th> </tr> <tr> <td id="str"></td> <td id="dex"></td> <td id="con"></td> <td id="int"></td> <td id="wis"></td> <td id="cha"></td> </tr> </tbody></table> <tapered-rule></tapered-rule> </template><script> (function(window, document) { function abilityModifier(abilityScore) { var score = parseInt(abilityScore, 10); return Math.floor((score - 10) / 2); } function formattedModifier(abilityModifier) { if (abilityModifier >= 0) { return '+' + abilityModifier; } // This is an en dash, NOT a "normal" dash. The minus sign needs to be more visible. return unescape('%u2013') + Math.abs(abilityModifier); } function abilityText(abilityScore) { return [String(abilityScore), ' (', formattedModifier(abilityModifier(abilityScore)), ')'].join(''); } var elemName = 'abilities-block'; var thatDoc = document; var thisDoc = (thatDoc.currentScript || thatDoc._currentScript).ownerDocument; var proto = Object.create(HTMLElement.prototype, { createdCallback: { value: function() { var template = thisDoc.getElementById(elemName); var clone = thatDoc.importNode(template.content, true); var root = this.createShadowRoot().appendChild(clone); } }, attachedCallback: { value: function() { var root = this.shadowRoot; for (var i = 0; i < this.attributes.length; i++) { var attribute = this.attributes[i]; var abilityShortName = attribute.name.split('-')[1]; root.getElementById(abilityShortName).textContent = abilityText(attribute.value); } } } }); thatDoc.registerElement(elemName, {prototype: proto}); })(window, document); </script><template id="property-block"> <style> :host { margin-top: 0.3em; margin-bottom: 0.9em; line-height: 1.5; display: block; } ::content > h4 { margin: 0; display: inline; font-weight: bold; font-style: italic; } ::content > p:first-of-type { display: inline; text-indent: 0; } ::content > p { text-indent: 1em; margin: 0; } </style> <content></content> </template><script> (function(window, document) { var elemName = 'property-block'; var thatDoc = document; var thisDoc = (thatDoc.currentScript || thatDoc._currentScript).ownerDocument; var proto = Object.create(HTMLElement.prototype, { createdCallback: { value: function() { var template = thisDoc.getElementById(elemName); var clone = thatDoc.importNode(template.content, true); this.createShadowRoot().appendChild(clone); } } }); thatDoc.registerElement(elemName, {prototype: proto}); })(window, document); </script><template id="property-line"> <style> :host { line-height: 1.4; display: block; text-indent: -1em; padding-left: 1em; } ::content > h4 { margin: 0; display: inline; font-weight: bold; } ::content > p:first-of-type { display: inline; text-indent: 0; } ::content > p { text-indent: 1em; margin: 0; } </style> <content></content> </template><script> (function(window, document) { var elemName = 'property-line'; var thatDoc = document; var thisDoc = (thatDoc.currentScript || thatDoc._currentScript).ownerDocument; var proto = Object.create(HTMLElement.prototype, { createdCallback: { value: function() { var template = thisDoc.getElementById(elemName); var clone = thatDoc.importNode(template.content, true); this.createShadowRoot().appendChild(clone); } } }); thatDoc.registerElement(elemName, {prototype: proto}); })(window, document); </script><template id="stat-block"> <style> .bar { height: 5px; background: #E69A28; border: 1px solid #000; position: relative; z-index: 1; } :host { display: inline-block; } #content-wrap { font-family: 'Noto Sans', 'Myriad Pro', Calibri, Helvetica, Arial, sans-serif; font-size: 13.5px; background: #FDF1DC; padding: 0.6em; padding-bottom: 0.5em; border: 1px #DDD solid; box-shadow: 0 0 1.5em #867453; /* We don't want the box-shadow in front of the bar divs. */ position: relative; z-index: 0; /* Leaving room for the two bars to protrude outwards */ margin-left: 2px; margin-right: 2px; /* This is possibly overriden by next CSS rule. */ width: 400px; -webkit-columns: 400px; -moz-columns: 400px; columns: 400px; -webkit-column-gap: 40px; -moz-column-gap: 40px; column-gap: 40px; /* When height is constrained, we want sequential filling of columns. */ -webkit-column-fill: auto; -moz-column-fill: auto; column-fill: auto; } :host([data-two-column]) #content-wrap { /* One column is 400px and the gap between them is 40px. */ width: 840px; } ::content > h3 { border-bottom: 1px solid #7A200D; color: #7A200D; font-size: 21px; font-variant: small-caps; font-weight: normal; letter-spacing: 1px; margin: 0; margin-bottom: 0.3em; break-inside: avoid-column; break-after: avoid-column; } /* For user-level p elems. */ ::content > p { margin-top: 0.3em; margin-bottom: 0.9em; line-height: 1.5; } /* Last child shouldn't have bottom margin, too much white space. */ ::content > *:last-child { margin-bottom: 0; } </style> <div class="bar"></div> <div id="content-wrap"> <content></content> </div> <div class="bar"></div> </template><script> (function(window, document) { var elemName = 'stat-block'; var thatDoc = document; var thisDoc = (thatDoc.currentScript || thatDoc._currentScript).ownerDocument; var proto = Object.create(HTMLElement.prototype, { createdCallback: { value: function() { var template = thisDoc.getElementById(elemName); // If the attr() CSS3 function were properly implemented, we wouldn't // need this hack... if (this.hasAttribute('data-content-height')) { var wrap = template.content.getElementById('content-wrap'); wrap.style.height = this.getAttribute('data-content-height') + 'px'; } var clone = thatDoc.importNode(template.content, true); this.createShadowRoot().appendChild(clone); } } }); thatDoc.registerElement(elemName, {prototype: proto}); })(window, document); </script> """ ) ################################################################################ # Writing the monster stats into the file ################################################################################ filew.write(""" <stat-block> <creature-heading> <h1>""") filew.write(monster_name) filew.write("""</h1> <h2> </h2> </creature-heading> <top-stats> <property-line> <h4>Armor Class</h4> <p> </p> </property-line> <property-line> <h4>Hit Points</h4> <p> </p> </property-line> <property-line> <h4>Speed</h4> <p> </p> </property-line> <abilities-block data-str="1" data-dex="1" data-con="1" data-int="1" data-wis="1" data-cha="1" ></abilities-block> <property-line> <h4>Saving Throws</h4> <p> </p> </property-line> <property-line> <h4>Skills</h4> <p> </p> </property-line> <property-line> <h4>Damage Resistances</h4> <p> </p> </property-line> <property-line> <h4>Damage Immunities</h4> <p> </p> </property-line> <property-line> <h4>Damage Vulnerabilities</h4> <p> </p> </property-line> <property-line> <h4>Condition Immunities</h4> <p> </p> </property-line> <property-line> <h4>Senses</h4> <p> </p> </property-line> <property-line> <h4>Languages</h4> <p> </p> </property-line> <property-line> <h4>Challenge</h4> <p> </p> </property-line> </top-stats> <property-block> <h4> </h4> <p> </p> </property-block> <property-block> <h4> </h4> <p> </p> </property-block> <h3>Actions</h3> <property-block> <h4> </h4> <p> </p> </property-block> <property-block> <h4> </h4> <p><i>Melee Weapon Attack:</i> <i>Hit:</i> </p> </property-block> <property-block> <h4> </h4> <p><i>Ranged Weapon Attack:</i> <i>Hit:</i> </p> </property-block> </stat-block></body></html> """) filew.close() # Closing the opened file
# Homework: Your job is to make a custom calculator. # Your calculator should accept at least three values. # For example height, width, length # It should print a prompt that makes it clear what # is being calculated. # For example: # Enter height, width, and length to calculate the area of a cube # Height: 3 # Width: 4 # Length: 2 # After accepting input the calculator should perform # an accurate calculation and display the results in # a clear and well formatted message. # For example: A cube with a height of 3, width of 4, and length of 2 has an area of 24 # You can accept string input that becomes part of the descirption. # For example: Input units: inches # Be sure to convert your numeric values to numbers before performing math operations! import math print("Welcome to the pythagorean theorem calculator (a^2 + b^2 = c^2)") typeVar = input("Enter which variable you would like to solve for. You can either enter \"a\", \"b\", or \"c\": ") #check if typeVar is either a, b, or c while typeVar != "a" and typeVar != "b" and typeVar != "c": print("") print("Please enter either \"a\", \"b\", or \"c\"") typeVar = input("Enter which variable you would like to solve for. You can either enter \"a\", \"b\", or \"c\": ") a = None b = None c = None def isNum(num): try: int(num) return True except: return False def getA(): #value for b b = input("Please enter a value for b: ") while isNum(b) != True: print("") print("Please enter a numeric value") b = input("Please enter a value for b: ") #value for c print("") c = input("Please enter a value for c: ") while isNum(c) != True: print("") print("Please enter a numeric value") c = input("Please enter a value for c: ") #convert b and c to ints b = int(b) c = int(c) a = math.sqrt((math.pow(c, 2) - math.pow(b, 2))) # print((math.pow(2, 2))) print(f"A triangle, given leg \"b\" as {b} and a hypotenuse of {c} will result in leg \"a\" being {a}") def getB(): #value for a a = input("Please enter a value for a: ") while isNum(a) != True: print("") print("Please enter a numeric value") a = input("Please enter a value for a: ") #value for c print("") c = input("Please enter a value for c: ") while isNum(c) != True: print("") print("Please enter a numeric value") c = input("Please enter a value for c: ") #convert a and c to ints a = int(a) c = int(c) b = math.sqrt((math.pow(c, 2) - math.pow(a, 2))) print(f"A triangle, given leg \"a\" as {a} and a hypotenuse of {c} will result in leg \"b\" being {b}") def getC(): #value for a a = input("Please enter a value for a: ") while isNum(a) != True: print("") print("Please enter a numeric value") a = input("Please enter a value for a: ") #value for b print("") b = input("Please enter a value for b: ") while isNum(b) != True: print("") print("Please enter a numeric value") b = input("Please enter a value for b: ") a = int(a) b = int(b) c = math.sqrt(math.pow(a, 2) + math.pow(b, 2)) print(f"A triangle, given leg \"a\" as {a} and leg \"b\" as {b} will result in the hypotenuse being being {c}") optionsA = { "a": getA, "b": getB, "c": getC } optionsA[typeVar]()
#!/usr/bin/env python3 from csv_parser import CsvParser from decimal import Decimal class SalesReport: """ This class holds the data returned by your generate_sales_report() method. # Your SalesReport must also contain: # * The total sales associated with each product over the quarter. # * The average weekly sales associated with each product. # * Products should be indexed by product name in the report. """ def __init__(self, ): # NUMBER_OF_WEEKS_IN_QUARTER = 12 # weekly_sums = [0] * NUMBER_OF_WEEKS_IN_QUARTER # use dictionary to allow for possibility of missing weeks # key is week self.total_sales_per_week = {} # key is product self.total_sales_per_product = {} self.average_sales_per_product = {} def total_sales_per_week_report(self): """ :return: a string e.g. Week Total Sales 0 1261.67 1 1373.37 2 6.00 11 1182.06 """ text = 'Week Total Sales\n' for key, value in self.total_sales_per_week.items(): # https://docs.python.org/3/library/string.html#formatstrings text += str(f'{key: >4} {value: >11}\n') return text def total_sales_per_product_report(self): """ :return: The total sales associated with each product over the quarter a string e.g. Product1 Product2 Product3 Total Sales 1695.83 628.75 1498.52 """ products = ' ' for key in self.total_sales_per_product.keys(): products += str(f'{key: >10}') header = products sum_line = 'Total Sales ' for value in self.total_sales_per_product.values(): # https://docs.python.org/3/library/string.html#formatstrings sum_line += str(f'{value: >10}') return header + '\n' + sum_line + '\n' def total_sales_per_product_report_narrow_format(self): """ :return: The total sales associated with each product over the quarter, in narrow format a string e.g. Product Total Sales Product1 1695.83 Product2 628.75 Product3 1498.52 """ text = 'Product Total Sales\n' for key, value in self.total_sales_per_product.items(): # https://docs.python.org/3/library/string.html#formatstrings text += str(f'{key: >4} {value: >13}\n') return text def average_weekly_sales_report(self): """ :return: The average weekly sales associated with each product. a string e.g. Product1 Product2 Product3 Average Sales 423.96 157.19 374.63 """ products = ' ' for key in self.average_sales_per_product.keys(): products += str(f'{key: >10}') header = products sum_line = 'Average Sales' for value in self.average_sales_per_product.values(): # https://docs.python.org/3/library/string.html#formatstrings sum_line += str(f'{value: >10.2f}') return header + '\n' + sum_line + '\n' def week_with_highest_sales(self): """ assume sales may be negative (e.g. customers returned items), 0, or positive :return: first week with maximum value """ # max_value = max(self.total_sales_per_week.values()) # week_with_max_value = None # # for key, value in self.total_sales_per_week.items(): # if value == max_value: # week_with_max_value = key # break # key function used for the comparison returns the item[1], the item value item_with_max_value = max(self.total_sales_per_week.items(), key=lambda item: item[1]) # return item_with_max_value[0], the key return item_with_max_value[0] def week_with_highest_sales_report(self): """ :return: the week with the highest sales. """ return str(f'Week with highest sales: {self.week_with_highest_sales()}\n') def generate_sales_report(parser): """ Tally up the sales results from the quarter. This method consumes a CSV file describing the quarterly sales report, and returns aggregate statistics about the input data. The sales report input follows a CSV format with columns like the following: Week Product1 Product2 Product3 ... 0 568.15 180.12 513.40 1 581.34 312.01 480.02 ... 11 545.34 134.62 502.10 For each week, we display the sales generated from each of N products represented in the second through N+1th columns of the CSV. The 1st column indicates the week number. Each quarter consists of 12 weeks. This method generates a sales report with the following aggregate data: * The total value associated with each week. * Identify the week with the highest sales. @param parser a CsvParser initialized with the input CSV data. @return a SalesReport containing the figures of merit described above. Product1 Product2 Product3 ... total 568.15 180.12 513.40 """ sales_report = SalesReport() number_of_records = update_sales(parser, sales_report) # generate average sales per product. Assumes sales_report.total_sales_per_product is up to date. sales_report.average_sales_per_product =\ {product_name: sales_report.total_sales_per_product[product_name] / number_of_records for product_name in parser.product_names} return sales_report def update_sales(parser, sales_report): """ iterates parser and updates sales_report :param parser: an iterable that supplies a sequence, every element is a list e.g. first element ['0', '568.15', '180.12', '513.40'...] :param sales_report: object to update :return: number of records processed, caller may use this to calculate an average """ cumulative_sales_per_product = [0] * parser.number_of_products number_of_records = 0 for csv_line_as_array in parser: week_number_string = csv_line_as_array[0] # tail of csv_line_as_array converted to Decimal # currency, use Decimal not float # e.g. [568.15, 180.12, 513.40...] sales_per_week_per_product = [Decimal(x) for x in csv_line_as_array[1:]] # update total sales per week sales_report.total_sales_per_week[week_number_string] = sum(sales_per_week_per_product) # accumulate sales per product # prefer method enumerate(x) over range(len(x)) for product_index, product_name in enumerate(parser.product_names): cumulative_sales_per_product[product_index] += sales_per_week_per_product[product_index] number_of_records += 1 sales_report.total_sales_per_product = dict(zip(parser.product_names, cumulative_sales_per_product)) return number_of_records if __name__ == '__main__': # print("Test") # sales_text contains entire csv file filename = './data/sales.csv' with open(filename) as f: sales_text = f.read() # print(sales_text) parser = CsvParser(sales_text) sales_report = generate_sales_report(parser) print(sales_report.total_sales_per_week_report()) print(sales_report.week_with_highest_sales_report()) print(sales_report.total_sales_per_product_report()) # print(sales_report.total_sales_per_product_report_narrow_format()) print(sales_report.average_weekly_sales_report())
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- import asyncio,threading,time @asyncio.coroutine def hello(): print("Hello world!") # 异步调用asyncio.sleep(1): x = asyncio.sleep(1) print('r=' + type(x)) r = yield from asyncio.sleep(1) print("Hello again!") @asyncio.coroutine def hello2(): print('Hello world! (%s)' % threading.currentThread()) yield from asyncio.sleep(5) print('Hello again! (%s)' % threading.currentThread()) # 获取EventLoop: loop = asyncio.get_event_loop() # 执行coroutine h = hello() loop.run_until_complete(h) print("main") # loop.close() print("#"*100) loop1 = asyncio.get_event_loop() # actually, this loop is loop above tasks = (hello2(), hello2()) loop1.run_until_complete(asyncio.wait(tasks)) loop1.close() print("main2")
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- def square_gen(val): i = 0 val_from_send = None print("\nsquare_gen begin") while True: # 使用yield语句生成值,使用out_val接收send()方法发送的参数值 print("before yield val_from_send =", val_from_send,',i =',i) val_from_send = (yield val_from_send ** 2) if val_from_send is not None else (yield i ** 2) # 如果程序使用send()方法获取下一个值,out_val会获取send()方法的参数 i += 1 print("after yield val_from_send =", val_from_send, ',i =', i) sg = square_gen(5) print("============================") # 第一次调用send()方法获取值,只能传入None作为参数 print("sg.send first,",end=' ') print(sg.send(None)) # 0 print("next first,",end=' ') print(next(sg)) # 1 print("next second,,",end=' ') print(next(sg)) # 4 print("next third,,",end=' ') print(next(sg)) # 9 print('--------------') # 调用send()方法获取生成器的下一个值,参数9会被发送给生成器 print("sg.send second,",end=' ') print(sg.send(900)) # 810000 # 再次调用next()函数获取生成器的下一个值 print("next fourth,",end=' ') print(next(sg)) # 25 print("sg.send third,",end=' ') print(sg.send(100)) # 10000 # sg.close() # print(next(sg))
''' 1. The list of non-negative integers that are [5,10,7,14,25,36] . Print the square of each number. eg for [1,2,3,4] the output would be 1 4 9 16 ''' def squaringNumbers(listofnumbers): for i in range(0,len(listofnumbers)): print(listofnumbers[i]**2) squaringNumbers([5,10,7,14,25,36])
''' 3. Write a function called raindrops that takes a number. - If the number is divisible by 3, it should return “Pling”. - If it is divisible by 5, it should return “Plang”. - If it is divisible by both 3 and 5, it should return “PlingPlang”. - If it is divisible by by 7, it should return "Plong" - If it is divisible by both 7 and 5, it should return “PlongPlang”. - If it is divisible by both 7 and 3, it should return “PlongPling”. - If it is divisible by both 7, 5 and 3, it should return “PlongPlangPling”. - Otherwise, it should return the same number. ''' dict1={3: "Pling", 5: "Plang", 7: "Plong"} def rd(userin): str1="" for key,value in dict1.items(): if userin%key==0: str1+=value return str1 def rainDrops(userin): if userin%3==0 and userin%5==0 and userin%7==0: return "PlongPlangPling" elif userin%3==0 and userin%7==0: return "PlongPling" elif userin%5==0 and userin%7==0: return "PlongPlang" elif userin%3==0 and userin%5==0: return "PlingPlang" elif userin%3==0: return "Pling" elif userin%5==0: return "Plang" elif userin%7==0: return "Plong" else: return userin answer=rd(int(input("Enter a number: "))) print(answer)
def sum(lista): suma = 0 for i in lista: suma += i return suma def multip(lista): multiplicacion = 1 for i in lista: multiplicacion *= i return multiplicacion n=int(input("cantidad numeros:")) lista=[] for i in range(0,n): lista.append(int(input("ingrese numero "+str(i+1)+" de la lista: "))) print "La Suma de los elementos es: " + str(sum(lista)) print "La Multiplicación de los elementos es: " + str(multip(lista))
frase=int(input("Ingrese cantidad de palabras: ")) palabras=[] for i in range(0,frase): palabras.append(raw_input("Palabra "+str(i+1)+": ")) def mas_larga(lista): mayor=len(lista[0]) maslarga=lista[0] for palabra in lista: if mayor <= len(palabra): mayor=len(palabra) maslarga = palabra else: maslarga=maslarga return maslarga print "la palabra mas larga es: "+mas_larga(palabras)
from abc import ABCMeta, abstractmethod class figure(): """parent class""" __metaclass__ = ABCMeta @abstractmethod def reckon(self): """return square"""
# name=input('我的名字:') # age=input('我的年龄:') # sex=input('我的性别:') # print('我的名字是:'+name, '\n我的年龄是:'+age,'\n我的性别是:'+sex) # mmm=''' # ----------------info of %s------------------ # name : %s # age : %s # job : %s # hobbie : %s # --------------------end----------------------- # ''' % ('曾阿牛', '曾阿牛 ', 100, '明教教主', '大保健') # print(mmm) # name=input('请输入你的姓名:') # age=input('请输入你的年龄:') # job=input('请输入你的工作:') # hobbie=input('请输入你的爱好') # msg=''' # ----------------------info of %s----------------- # name : %s # age : %s # job : %s # hobbie : %s # ------------------------end---------------------- # ''' % (name, name,age,job,hobbie) # print(msg) # dic={ # 'name':'曾阿牛', # 'age':23, # 'job':'明教教主', # 'hobbie':'大保健' # } # msg=''' # ----------------------info of %(name)s----------------- # name : %(name)s # age : %(age)s # job : %(job)s # hobbie : %(hobbie)s # ------------------------end---------------------- # ''' % dic # print(msg) # msg='我叫%s,今年%s,学习进度%s' % ('管',0,'%2') # print(msg) # msg='我叫%s,今年%s,学习进度2%%' % ('管',0,) # print(msg) # count=0 # while count<=5: # count=count+1 # print(count) # count=0 # while count<=5: # count=count+1 # print(count) # else: # print('执行完毕') # count=0 # while count<=5: # count=count+1 # print(count) # if count==4:break # else: # print('执行完毕') # print(1>2) # print(int(True),int(False)) # print(bool(0),bool(8),bool(7)) # print(4 or 1) # print(4 and 1) # print(-4 or 1) # print(2**16)
#!/usr/bin/env python3 ''' loopy test ''' #channel = int(input("What channel do you REALLY want?: ")) FAVS = [26, 52, 4, 498, 102] for channel in FAVS: if channel < 11: print("For Channel ", channel, " You need the basic package") elif channel < 41: print("For Channel ", channel, " You need the standard package") elif channel < 101: print("For Channel ", channel, " You need the premium package") elif channel < 201: print("For Channel ", channel, " You need the HD package") else: print("For Channel ", channel, " You need the Expensive package")
import math def ehPrimo(n): result = True size = int(math.sqrt(n)) for i in range(2,size): #print('{} dividido por {}'.format(n,i)) if n % i == 0: result = False break return result if __name__ == "__main__": n=991564654552145 #n=23 print(ehPrimo(n))
#program works!!! cards_chosen = ['king','4','3','8','3'] hit = 0 while True: print ('Here are your cards: ') def print_list(x):#dont really know how this works but it works just to make it print nicer print('\n'.join(x)) print_list(cards_chosen[0:2+hit]) values = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'jack':10,'queen':10,'king':10} #at this point im excluding the ace too hard to work with cards_chosen_values = [] for go_though_cards_chosen in cards_chosen: total_player_values = values[go_though_cards_chosen] cards_chosen_values.append(total_player_values) sum_of_player = (sum(cards_chosen_values[0:2+hit]))#just for test purposes if sum_of_player == 21: win_lose = 'win'#then print the outcome of the win_lose print ('21!!!')#just for testing break elif sum_of_player > 21: win_lose = 'lose'#then prin teh outcome of the win_lose later print ('Busted')#just for test purposes break else: hit_stand = input('Will you hit or stand? ') hit_stand = hit_stand.lower() if hit_stand == 'hit': hit = hit + 1 print (hit) else: print ('player stood stand') break#break probalbaly will need a while at the beggining
#going to finish the dealer's hand #figure out how to print the list/cards not backwards #need to add this to the final combined part cards_chosen = ['king','4','2','7','3'] dealer_hit = 0 win_lose = 'lose' cards_chosen_values = [] sum_of_player = 20 values = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'jack':10,'queen':10,'king':10} #at this point im excluding the ace too hard to work with for go_though_cards_chosen in cards_chosen: total_player_values = values[go_though_cards_chosen] cards_chosen_values.append(total_player_values) #this part should be printed before the player hits or stands print ('The dealer has a face up card: %s, and one faced down' % cards_chosen[len(cards_chosen)-1])#pick the last term in the list while win_lose != 'win': def print_list(x):#dont really know how this works but it works just to make it print nicer print('\n'.join(x)) print_list(cards_chosen[len(cards_chosen)-2-dealer_hit:len(cards_chosen)]) sum_of_dealers_cards = (sum(cards_chosen_values[len(cards_chosen_values)-2-dealer_hit:len(cards_chosen_values)]))#takes the valuse from the end of the list print ('For a total of: %s' % sum_of_dealers_cards)#testing purposes if sum_of_player >= sum_of_dealers_cards: print ('Dealer must hit') dealer_hit = dealer_hit + 1 elif sum_of_dealers_cards > 21: print('Dealer bust') win_lose = 'win' break else: print ('Dealer wins') win_lose = 'lose' break
#be able to give a user a initial amout of chips, ask for wager, print ('Hey there player, I\'ve started you off with 500$. Try and get as high as you can.) money = 500 bet = input('What\'s your wager? ') if bet <= money: #run blackjack game else: print ('I\'m sorry but I can\'t accept that value as a bet.) #at the end of the game if game_outcome == win: print ('Congrats you beat the dealer.') money += money + (bet * 2) print ('you currently have $%s' % money) else: print ('The dealer won') money -= money + (bet * 2)
from tkinter import * class Box: def __init__(self, size): self.size = size def in_horizontal_contact(self, x): return x <= 0 or x >= self.size def in_vertical_contact(self, y): return y <= 0 or y >= self.size def in_square_contact_x(self, x, y, gap): return gap*(-1) <= ((self.size // 2)-x) <= gap and abs((self.size // 2)-y) == gap def in_square_contact_y(self, x, y, gap): return gap*(-1) <= ((self.size // 2)-y) <= gap and abs((self.size // 2)-x) == gap class MovingBall: def __init__(self, x, y, xv, yv, color, size, box): self.x = x self.y = y self.xv = xv self.yv = yv self.color = color self.size = size self.box = box def move(self, time_unit, gap): self.x = self.x + self.xv * time_unit self.y = self.y + self.yv * time_unit if self.box.in_horizontal_contact(self.x): self.xv = - self.xv elif self.box.in_vertical_contact(self.y): self.yv = - self.yv elif self.box.in_square_contact_x(self.x, self.y, gap) : self.yv *= -1 elif self.box.in_square_contact_y(self.x, self.y, gap): self.xv *= -1 class AnimationWriter: def __init__(self, root, ball, ball2, box): self.size = box.size self.canvas = Canvas(root, width=self.size, height=self.size) self.canvas.grid() self.ball = ball self.ball2 = ball2 def animate(self): gap = self.ball.size e = self.size // 2 self.canvas.delete(ALL) self.ball.move(1, gap) x = self.ball.x y = self.ball.y s = self.ball.size * 2 c = self.ball.color e = self.size // 2 self.canvas.create_oval(x, y, x+s , y+s, outline=c, fill=c) self.ball2.move(1, gap) x2 = self.ball2.x y2 = self.ball2.y s2 = self.ball2.size * 2 c2 = self.ball2.color self.canvas.create_oval(x2, y2, x2+s2 , y2+s2, outline=c2, fill=c2) if (x-x2)**2 + (y-y2)**2 < (gap*2)**2: self.ball.xv *= -1 self.ball.yv *= -1 self.ball2.xv *= -1 self.ball2.yv *= -1 self.canvas.create_rectangle(e+gap, e+gap, e-gap, e-gap, outline="blue", fill="blue") self.canvas.after(10, self.animate) class BounceController: def __init__(self): box_size = 400 ball_size = 10 ball_color_red = 'red' ball_color_green = 'green' x_velocity, y_velocity = 5, 2 self.root = Tk() self.root.title("Bouncing Ball") self.root.geometry(str(box_size+10)+"x"+str(box_size+10)) self.box = Box(box_size) self.ball = MovingBall(box_size//5, box_size//5, x_velocity, y_velocity, ball_color_red, ball_size, self.box) self.ball2 = MovingBall(box_size//3, box_size//3, x_velocity, y_velocity, ball_color_green, ball_size, self.box) def play(self): AnimationWriter(self.root, self.ball, self.ball2, self.box).animate() self.root.mainloop() A= BounceController() A.play()
"""Defines Data Models for Spellcheck Module.""" from spellcheckapp import db class SpellChecks(db.Model): """ SpellChecks Database Model. Defines SpellChecks fields. """ id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), db.ForeignKey('users.username'), unique=False, nullable=False) submitted_text = db.Column(db.String(501), unique=False, nullable=False) misspelled_words = db.Column(db.String(501), unique=False, nullable=True) def __repr__(self): """Defines string representation of a SpellChecks tuple.""" return '<User %r Spell_check_id %r>' % (self.username, self.id)
# write a program to convert a users input from kgs to lbs and vice-versa kgs = int(input("Enter weight in kgs: ")) pounds = kgs/0.90 print("The weight in pounds is", round(kgs, 1)) pounds = int(input("Enter weight in Pounds: ")) kgs = pounds/0.90 print("The weight in kgs is", round(kgs, 1)) # find the total price def price(numbers): total = 0 print(sum((8, 2, 3, 0, 7)))