text
stringlengths
37
1.41M
str_1 = "lucidProgramming" str_2 = "LucidProgramming" str_3 = "lucidprogramming" def iterativeFindUpper(testStr): for c in testStr: if c == c.upper(): return c return None # print(iterativeFindUpper(str_1)) # print(iterativeFindUpper(str_2)) # print(iterativeFindUpper(str_3)) def recursiveFindUpper(singleStr, testStr): # print(singleStr) if len(testStr) == 0: return None if singleStr != "" and singleStr == singleStr.upper(): return singleStr return recursiveFindUpper(testStr[0:1], testStr[1:]) print(recursiveFindUpper("", str_1)) # print(recursiveFindUpper(str_2)) # print(recursiveFindUpper(str_3))
""" Solver class to solve the Queen board using some algorithm """ from lib.problem.board import Board class Solver: """ Solving the Queen board by using algorithms defined Attributes ---------- __board : Board initial board __stepsClimbed : int number of steps taken in the solution __currentHeuristics : int initial heuristic of the board __newHeuristics : int heuristic generated from the neighbour __verbose : bool True to print the neighbours chosen """ def __init__(self, n=4, verbose=False): self.__board = Board(n=n) self.__stepsClimbed = 0 self.__currentHeuristics = 0 self.__newHeuristics = 0 self.__verbose = verbose self.__restarts = 0 def getStepsClimbed(self): """ Returns the no of steps taken Returns ------- int steps taken """ return self.__stepsClimbed def getHeuristics(self): """ Returns heuristics of initial and final states Returns ------- tuple both heuristics """ return self.__currentHeuristics, self.__newHeuristics def getRestarts(self): """ Returns 0 if only SHC is ran else some values of restarts Returns ------- int number of restarts for Iterative HC """ return self.__restarts def runHillClimbing(self): """ Run the hill climbing on the board Returns ------- list final board state """ currentState = self.__board.generateBoard() print("Starting Board :: ") self.__board.printBoard(currentState) while True: self.__currentHeuristics = self.__board.calculateHeuristic(currentState) neighbours = self.__board.getNeighbours(currentState) if not neighbours: break if self.__verbose: print(f"Neighbour Board :: [with heuristics {self.__board.calculateHeuristic(currentState)}]") self.__board.printBoard(currentState) # min heuristic in selected neighbour = min(neighbours, key=lambda state: self.__board.calculateHeuristic(state)) if self.__board.calculateHeuristic(neighbour) >= self.__board.calculateHeuristic(currentState): break # updating the current state currentState = neighbour self.__stepsClimbed += 1 self.__newHeuristics = self.__board.calculateHeuristic(currentState) print("Final Board :: ") self.__board.printBoard(currentState) return currentState def runRandomRestartHillClimbing(self, iterations=100): """ Restarting the board if it gets stuck on the Local M, Default no of restarts determined by iterations Parameters ---------- iterations : int number of iterations Returns ------- list final board state """ currentState = self.__board.generateBoard() print("Starting Board :: ") self.__board.printBoard(currentState) for i in range(iterations): while True: self.__currentHeuristics = self.__board.calculateHeuristic(currentState) neighbours = self.__board.getNeighbours(currentState) if not neighbours: break if self.__verbose: print(f"Neighbour Board :: [with heuristics {self.__board.calculateHeuristic(currentState)}]") self.__board.printBoard(currentState) # min heuristic in selected neighbour = min(neighbours, key=lambda state: self.__board.calculateHeuristic(state)) if self.__board.calculateHeuristic(neighbour) >= self.__board.calculateHeuristic(currentState): break # updating the current state currentState = neighbour self.__stepsClimbed += 1 self.__newHeuristics = self.__board.calculateHeuristic(currentState) # if not the final answer if self.__newHeuristics > 0.0: currentState = self.__board.generateBoard() self.__restarts += 1 else: print("Final Board :: ") self.__board.printBoard(currentState) return currentState # well this is the final anyway print("Final Board :: ") self.__board.printBoard(currentState) return currentState
import os import cv2 import numpy as np def read_gt_file(path): """Read an optical flow map from disk Optical flow maps are stored in disk as 3-channel uint16 PNG images, following the method described in the KITTI optical flow dataset 2012 (http://www.cvlibs.net/datasets/kitti/eval_stereo_flow.php?benchmark=flow). Returns: numpy array with shape [height, width, 3]. The first and second channels denote the corresponding optical flow 2D vector (u, v). The third channel is a mask denoting if an optical flow 2D vector exists for that pixel. Vector components u and v values range [-512..512]. NOTE: this function is copied from video/optical_flow.py. We do not move it here to keep backwards-compatibility with week 1. """ data = cv2.imread(path, -1).astype('float32') result = np.empty(data.shape, dtype='float32') result[:,:,0] = (data[:,:,2] - 2**15) / 64 result[:,:,1] = (data[:,:,1] - 2**15) / 64 result[:,:,2] = data[:,:,0] return result def read_sequence(number, annotated=True): """Read a train sequence from the KITTI dataset The sequence belongs to the `image_0` folder, which is a subdirectory of the `training` folder. For the ground truth, we use the `flow_noc` directory, as stated in the exercises for Week 1 (pre-slides page 33). Args: number: (int) it identifies the sequence to read. For example, for number=3, the sequence is composed by the files 000003_10.png and 000003_11.png. annotated: (bool) when True, the function returns the ground truth for that sequence. Returns: A numpy array with shape [2, h, w] with the 2 images (grayscale) of the sequence. Additionally, when annotated=True, a second numpy array with shape [h, w, 3] is returned with the optical flow ground truth annotation. """ # Kitti directories we use kitti_dir = os.path.join(os.path.dirname(__file__), '..', 'datasets', 'data_stereo_flow') train_dir = os.path.join(kitti_dir, 'training', 'image_0') gt_dir = os.path.join(kitti_dir, 'training', 'flow_noc') # Paths to images to load im0_path = os.path.join(train_dir, f'{number:06d}_10.png') im1_path = os.path.join(train_dir, f'{number:06d}_11.png') gt_path = os.path.join(gt_dir, f'{number:06d}_10.png') # Read and convert images im0 = cv2.imread(im0_path, -1) im1 = cv2.imread(im1_path, -1) seq = np.array([im0, im1]) seq = seq[..., np.newaxis] # add extra axis to have same shape as cdnet: # [n, h, w, 1] if annotated: gt = read_gt_file(gt_path) result = (seq, gt) else: result = seq return result
# When a class has its own functions, those functions are called methods. # method _description_ using print statements, prints out the name and age of the animal it’s called on. class Animal(object): """Makes cute animals.""" is_alive = True def __init__(self, name, age): self.name = name self.age = age def description(self): print self.name print self.age # self must be an argument to the description method. Otherwise, printing self.name and self.age won’t work, # since Python won’t know which self (that is, which object) you’re talking about hippo = Animal("hippy", 2) hippo.description()
""" The main method for the program used to edit an excel file of wind turbine information Author: Patrick Danielson """ # Imports import pandas as pd import time_generation as tg import dataframe_manipulation as em # Method in progress to create new excel file with conditions given # Input: Excel file # Output: Creates file on desktop def fileReader(inputFile, outputFile, dstActive): df = pd.read_excel(inputFile) # Create time column em.appendTimeFlag(df) # Generate missing times, by finding times = tg.makeTimes(df['time'].tolist(), dstActive) # Add missing times to excel file em.addNewTimes(df, times) # Create and update VTWS Flags for missing values em.appendVTWSFlag(df) em.updateVTWSFlag(df) # Export file df.to_excel(outputFile, index=False) # Main function, to ensure correct running enviroment. # Please replace inputFile, outputFile, and dstActive to the desired variables. # Set inputFile to input excel file, outputFile to desired output location, # and dstActive to whether DST is recognized in the given area (On by default) if __name__ == '__main__': inputFile = '/Users/patrick/Desktop/test 2021-05-06 start.xlsx' outputFile = '/Users/patrick/Desktop/check results.xlsx' dstActive = True fileReader(inputFile, outputFile, dstActive)
# # @lc app=leetcode.cn id=188 lang=python3 # # [188] 买卖股票的最佳时机 IV # # https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/description/ # # algorithms # Hard (28.25%) # Likes: 143 # Dislikes: 0 # Total Accepted: 9.2K # Total Submissions: 32.4K # Testcase Example: '2\n[2,4,1]' # # 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 # # 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。 # # 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 # # 示例 1: # # 输入: [2,4,1], k = 2 # 输出: 2 # 解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。 # # # 示例 2: # # 输入: [3,2,6,5,0,3], k = 2 # 输出: 7 # 解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 # 。 # 随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。 # # # # @lc code=start class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: def help(prices): if not prices: return 0 dp=[[0]*2 for _ in range(len(prices))]#定义dp table #需要找到一些basic case dp[0][0]=0 dp[0][1]=-prices[0] for i in range(1,len(prices)):#转移方程 dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i]) dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i]) return dp[len(prices)-1][0] if not prices: return 0 #dp table K=k n=len(prices) if k>n/2: return help(prices) dp=[[[0]*2 for _ in range(K+1)] for _ in range(n)] #base case #状态转移方程 for i in range(n): for k in range(K,0,-1): if i==0: dp[i][k][0] = 0 dp[i][k][1] = -prices[i]#这个初始化条件很重要啊 continue dp[i][k][0]=max(dp[i-1][k][0],dp[i-1][k][1]+prices[i]) dp[i][k][1]=max(dp[i-1][k][1],dp[i-1][k-1][0]-prices[i]) return dp[n-1][K][0]#注意代码规范 # @lc code=end
# # @lc app=leetcode.cn id=109 lang=python3 # # [109] 有序链表转换二叉搜索树 # # https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/description/ # # algorithms # Medium (69.56%) # Likes: 130 # Dislikes: 0 # Total Accepted: 16K # Total Submissions: 23K # Testcase Example: '[-10,-3,0,5,9]' # # 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 # # 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 # # 示例: # # 给定的有序链表: [-10, -3, 0, 5, 9], # # 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: # # ⁠ 0 # ⁠ / \ # ⁠ -3 9 # ⁠ / / # ⁠-10 5 # # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedListToBST(self, head: ListNode) -> TreeNode: #先要遍历链表得到列表 res=[] while head != None: res.append(head.val) head=head.next def buildTree(nums,begin,end): if begin >end: return None mid=(begin+end)//2 root=TreeNode(nums[mid]) root.left=buildTree(nums,begin,mid-1)#列表z中间左边的都在左子树 root.right=buildTree(nums,mid+1,end)#列表右边的都在右子树 return root if len(res)==0: return None return buildTree(res,0,len(res)-1) # @lc code=end
# # @lc app=leetcode.cn id=814 lang=python3 # # [814] 二叉树剪枝 # # https://leetcode-cn.com/problems/binary-tree-pruning/description/ # # algorithms # Medium (71.50%) # Likes: 65 # Dislikes: 0 # Total Accepted: 5.1K # Total Submissions: 7.1K # Testcase Example: '[1,null,0,0,1]' # # 给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。 # # 返回移除了所有不包含 1 的子树的原二叉树。 # # ( 节点 X 的子树为 X 本身,以及所有 X 的后代。) # # # 示例1: # 输入: [1,null,0,0,1] # 输出: [1,null,0,null,1] # ⁠ # 解释: # 只有红色节点满足条件“所有不包含 1 的子树”。 # 右图为返回的答案。 # # # # # # 示例2: # 输入: [1,0,1,0,0,0,1] # 输出: [1,null,1,null,1] # # # # # # # 示例3: # 输入: [1,1,0,1,1,0,1,0] # 输出: [1,1,0,1,1,null,1] # # # # # # 说明: # # # 给定的二叉树最多有 100 个节点。 # 每个节点的值只会为 0 或 1 。 # # # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ###从底向上后续遍历,如果当前元素为0且左右子树为null,则删除节点 class Solution: def pruneTree(self, root: TreeNode) -> TreeNode: if root is None: return None root.left=self.pruneTree(root.left) root.right=self.pruneTree(root.right) if root.val==0 and root.left is None and root.right is None: return None return root # @lc code=end
import os def find_files(suffix, path): """ Finds all files beneath path with file name suffix. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ ls = os.listdir(path) files = [] for item in ls: item_path = os.path.join(path, item) if os.path.isdir(item_path): files += find_files(suffix, item_path) if os.path.isfile(item_path) and item.endswith(suffix): files.append(item_path) return files test_path = '/home/b/Documents/Udacity/Python/P1/testdir' suffix = 'c' # traverses subsub directory actual = find_files( suffix, os.path.join(test_path, 'subdir3') ) expect = ['/home/b/Documents/Udacity/Python/P1/testdir/subdir3/subsubdir1/b.c'] assert(actual == expect) # finds all four recursive matches actual = len( find_files(suffix, test_path) ) expect = 4 assert(actual == expect) # finds another four recursive matches actual = len( find_files('h', test_path) ) expect = 4 assert(actual == expect) for file_path in find_files('c', test_path): print(file_path)
import os import Crypto.PublicKey.RSA import Crypto.Hash.SHA256 ''' Helpful routines for signing and verifying message signatures ''' def digest(message): digester = Crypto.Hash.SHA256.new() digester.update(message) return digester.digest() def genKeyPair(): return Crypto.PublicKey.RSA.generate(1024, os.urandom) def getPrivateKey(keyPair): return keyPair def getPublicKey(keyPair): return keyPair.publickey() def signMessage(key, message): ''' Sign a message with a private key key must be an RSA.PublicKey object holding the private key ''' # Compute hash of message h = digest(message) # Get the signature return key.sign(h, '') def verifySignature(pubKey, message, signature): ''' Returns True iff the signature is verified for the given message and public key. pubKey is a bytes object containing the PEM encoded public key. signature is a bytes object with the signature. ''' # Compute the hash of the message h = digest(message) return pubKey.verify(h, signature)
''' Replace this file with your implementation from Assignment 1 ''' from UTXO import UTXO import CryptoUtil from Transaction import Transaction class TxHandler(object): ''' Collect transactions into a mutually valid set that can be used to mine a new block. ''' def __init__(self, pool): ''' Create the new handler. This should make a copy of the UTXOPool passed as a parameter. ''' # TODO - implement this pass def getUTXOPool(self): ''' Return the current value of this TxHandler's UTXOPool as modified by calls to handleTxs. ''' # TODO - implement this pass def isValidTx(self, tx): ''' Return True if: (1) all outputs claimed by tx are in the current UTXO pool, (2) the signatures on each input of tx are valid, (3) no UTXO is claimed multiple times by tx, (4) all of txs output values are non-negative, and (5) the sum of txs input values is greater than or equal to the sum of its output values; and False otherwise. ''' # TODO - implement this pass def handleTxs(self, possibleTxs): ''' Return a maximal subset of mutually valid transactions from possibleTxs. "Maximal" means that no other transaction can be added to the list and still have all the transactions mutually valid. Note that there may be more than one correct subset because of the possibility of transactions trying to double spend some output. possibleTxs must be a list of Transaction objects. ''' # TODO - implement this pass
# -*- coding: utf-8 -*- """ Created on Tue Jul 19 14:35:47 2016 @author: yifanli """ import turtle def main(): #filename = input("Please enter drawing filename: ") filename = "drawingSingle.txt" t = turtle.Turtle() screen = t.getscreen() file = open(filename,"r") for line in file: """ first, purify each line of records of the drawing file used """ text = line.strip() """ second, make all records of each line an array of strings """ commandList = text.split(",") """ third, select the first string argument as the command""" command = commandList[0] """Examine the command and execute it""" if command == "goto": x=float(commandList[1]) y=float(commandList[2]) width=float(commandList[3]) color=commandList[4].strip() t.width(width) t.pencolor(color) t.goto(x,y) elif command == "circle": radius = float(commandList[1]) width = float(commandList[2]) color = commandList[3].strip() t.width(width) t.pencolor(color) t.circle(radius) elif command == "beginfill": color = commandList[1].strip() t.fillcolor(color) t.begin_fill() elif command == "endfill": t.end_fill() elif command == "penup": t.penup() elif command == "pendown": t.pendown() else : print "Unknown command found in file",command file.close() """Hide the turtle that we used to draw""" t.ht() """This causes the program to hold the turtle graphics window open until the mouse is clicked.""" screen.exitonclick() print("Program execution completed.") """if _name_ == "_main_" :""" main()
def make_shirt(size = 'large', shirt_msg = 'I love python'): """prints a msg about the shirt size and what it says""" print(f"The shirt size is {size} and the message on the shirt says {shirt_msg.title()}.") make_shirt('small','live life to the fullest') make_shirt(shirt_msg='the sun will rise again', size='medium') make_shirt() make_shirt('medium') make_shirt('small','I love c')
# traking down the speed of a alien that can move at different speeds alien_o = {'x_position': 0, 'y_position' : 25, 'speed': 'medium'} print(f"original position: {alien_o['x_position']}") if alien_o['speed'] == 'slow': x_increment = 1 elif alien_o['speed'] == 'medium': x_increment = 2 else : x_increment = 3 alien_o['x_position'] = alien_o['x_position'] + x_increment print(f"new position: {alien_o['x_position']}")
num = input('Please enter the number of times you want to display hello world: ') for i in range(int(num)): print('Hello World!') for x in range(0,11,2): print(x)
# This program tells the user if the number # they enter is a multiple of ten print("Enter a number and I'll tell you if its a multiple of ten or not") num = input() num = int(num) if num % 10 == 0: print(f"The number {num} is a multiple of 10.") else: print(f"The number {num} is not a multiple of 10.")
prompt = "Enter the toppings your would like on your pizza: " active = True while active: message = input(prompt) if message == 'quit': active = False else: print(f"adding {message} to pizza.")
file_name = 'guest_book.txt' while True: name = input("Please enter your name here: ") if name == 'quit': break else: with open(file_name, 'a') as file_object: file_object.write(f"{name}\n") print(f"Hello {name}, you've been added to the guest book.")
name = 'Bob' age = 3000 # note this is on big block of code of the if and else if statement if name == 'Alice': print('Hi Alice') elif age < 12: print('You are not Alice, kiddo') elif age > 2000: print('Unlike you, Alice is not an undead, immortal vampire.') elif age > 100: print('You are not Alice, granny.') print('Hello agian')
pet_0 = { 'animal' : 'dog', 'breed' : 'husky', 'name' : 'rex', 'owner' : 'miguel', 'age' : 6 } pet_1 = { 'animal' : 'bird', 'breed' : 'parakeet', 'name' : 'lola', 'owner' : 'sarah', 'age' : 4 } pet_2 = { 'animal' : 'lizard', 'breed' : 'skink', 'name' : 'larry', 'owner' : 'robert', 'age' : 3 } pets = [pet_0,pet_1,pet_2] for pet in pets: animal = pet['animal'] breed = pet['breed'] name = pet['name'] owner = pet['owner'] age = pet['age'] print(f"my name is {name} and i am a {breed} which is a type of {animal}." f" I am {age} years old and my owners name is {owner}.")
''' ## Summary: **Name:** Functionalize Maching Learning Procedure **Author:** Siyang Jing **Organization:** UNC-CH **License:** WTFPL **Reference:** 1. TensorFlow's keras tutorial 1. The author's other codes 1. Relevant numerous papers **Description:** This file prepares a function ML _Input_: * Parameters: * train_data * train_labels * test_data * test_labels * model: default is none, will build a 2 layer FNN with 20 neurons * EPOCHS: default is 1000, seems a good number * Other model fitting parameters * Flags: * MLPLOTTING: if enabled, will plot figures as described below * MLDEBUG: if enabled, will print ... for each 100 epochs _Output_: 1. model: a tensorflow keras model 1. mean absolute error 1. accuracy score _Saved Files_: For now, doesn't save anything. _Plots_: 1. Loss versus epochs 1. Accuracy versus epochs 1. Print test loss, mae, and acc **Requirements:** 1. Relevant Python modules 1. AuxFuncs, which defines the following: 1. Observation operator 1. Stupid inverse function 1. Lorenz96 as model 1. DataGenerator, which generates data based on the models in AuxFuncs ## TODO list: 1. Write a function to parse model fitting parameters 1. Arbitrary statistics type 1. Save the model _optional_ 1. Figure out what acc score means for regression model ''' import tensorflow as tf from tensorflow import keras import numpy as np from EnKF_func import * from AuxFuncs import * import matplotlib.pyplot as plt def ML(train_data,train_labels, test_data,test_labels, model=None, MLDEBUG=True, MLPLOTTING=False, EPOCHS=1000): # Default Model if model is None: def build_model(): model = keras.Sequential([ keras.layers.Dense(20, activation=tf.nn.relu, input_shape=(train_data.shape[1],)), keras.layers.Dense(20, activation=tf.nn.relu), keras.layers.Dense(20) ]) #optimizer = tf.train.RMSPropOptimizer(0.001) model.compile(loss='mse', optimizer='adam', metrics=['mae','acc']) return model model = build_model() # Display training progress by printing a single dot for each completed epoch. class PrintDot(keras.callbacks.Callback): def on_epoch_end(self,epoch,logs): if epoch % 100 == 0: print('') print('.', end='') # Store training stats history = model.fit(train_data, train_labels, epochs=EPOCHS, validation_split=0.2, verbose=0, callbacks=[PrintDot()] if MLDEBUG else None) [loss, mae, acc] = model.evaluate(test_data, test_labels, verbose=0) if MLPLOTTING: def plot_history(history): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Abs Error') plt.plot(history.epoch, np.array(history.history['mean_absolute_error']), label='Train Loss') plt.plot(history.epoch, np.array(history.history['val_mean_absolute_error']), label = 'Val loss') plt.legend() plt.ylim([0,5]) plot_history(history) def plot_acc_history(history): plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Rel Error') plt.plot(history.epoch, np.array(history.history['acc']), label='Train Loss') plt.plot(history.epoch, np.array(history.history['val_acc']), label = 'Val loss') plt.legend() plt.ylim([0,5]) plot_acc_history(history) print("") print("Testing set Mean Abs Error: {:4.2f}".format(mae)) print("Testing set Accuracy: {:4.2f}".format(acc)) return (model,mae,acc)
import random KREWES = { 'orpheus': ['Emily','Kevin','Vishwaa','Eric','Jay'], 'rex': ['William','Joseph','Calvin','Ethan','Moody'], 'endymion': ['Grace','Nahi','Derek','Jun Tao','Connor'] } def rando(tn): print(random.choice(KREWES[tn])) tn = input("Enter team name: ") if tn in KREWES: rando(tn) else: print("Team not there")
print("******************************************************************") print("PROGRAM STUDI : ILMU KOMPUTER ") print("MATA KULIAH : STRUKTUR DATA ") print("KELAS : 15.2A.31 ") print("TIM KELOMPOK 3 ") print(" 1. DIMAS RAMADHAN AGUSTINA (15200384)") print(" 2. AGUS WAHYUDI (15200095)") print(" 3. LAKSMONO ADZANI (15200170)") print(" 4. GHIFARUL AZHAR (15200234)") print("******************************************************************") # By Coddingan Agus Wahyudi # Array List Matriks # Jumlah Kolom kolom= int(input("Masukkan Jumlah Kolom : ")) # Jumlah Baris baris= int(input("Masukkan Jumlah Baris : ")) # Array Matriks 1 x=[] # Array Matriks 2 y=[] # Array Matriks Total # List * baris dan kolom agar jumlah baris dan kolom di sesuaikan dengan jumlah yang diinput z=[0]* baris for i in range (kolom): z[i] = [0]* kolom print("") # Input ke dalam Matriks X # Perulangan Bersarang For # Perulangan Berdasarkan Kolom for i in range (kolom): line=[] print("Baris Ke - "+str(i)) # Perulangan Berdasarkan Baris for i in range (baris): line.append(int(input("Masukkan Bilangan : "))) x.append(line) # Output Matriks X for line in x : print(line) print("") # Input ke dalam Matriks Y # Perulangan Bersarang For # Perulangan Berdasarkan Kolom for i in range (kolom): lines=[] print("Baris Ke - "+str(i)) # Perulangan Berdasarkan Baris for i in range (baris): lines.append(int(input("Masukkan Bilangan : "))) y.append(lines) # Output Matriks Y for line in y : print(lines) print("") # Penjumlahan # Perulangan Kolom Dengan Jumlah Kolom Yang Di Matriks X for kolomz in range (len(x)): # Perulangan Baris Dengan Jumlah Baris Yang Di Matriks X for linez in range (len(x[0])): # Memasukkan Hasil Penjumalahan Matriks X dan Y ke Z z[kolomz][linez] = x[kolomz][linez] + y[kolomz][linez] # Output nya...... print("=============================================================================") print("TOTAL") for i in z : print(i)
#!/usr/bin/python3 def uppercase(str): for word in str: if ord(word) >= 97 and ord(word) <= 122: word = chr(ord(word) - 32) print("{}".format(word), end="") print("")
#!/usr/bin/python3 """ Docstring """ def read_lines(filename="", nb_lines=0): """[summary] Args: filename (str, optional): [description]. Defaults to "". """ with open(filename) as file: line = 0 for i in file: line += 1 if nb_lines <= 0 or nb_lines >= line: file.seek(0) for i in file: print(i, end="") else: file.seek(0) for i in range(nb_lines): n = file.readline() print(n, end="")
import random def playPlusOrMinus(): random.seed() value = random.randint(1, 100) count = 0 found = False while not found: print ("Try a number : ") guess = int(input()) count += 1 if guess > value: print("Too big !") elif guess < value: print("Too small !") else: found = True print("Congrats ! You have found the right number in {} tentatives !".format(count)) print("Do you want to play ? 1/0") answer = int(input()) if answer > 0: playPlusOrMinus()
import time def job_1(): print("Job_1 Started") start = time.time() k = 0 for i in range(10000): for j in range(10000): k = i + j end = time.time() total = end - start print("Job_1 Completed in",total) def job_2(): print("Job_2 Started") start = time.time() k = 0 for i in range(10000): for j in range(10000): k = i + j end = time.time() total = end - start print("Job_2 Completed in", total) def job_3(): print("Job_3 Started") start = time.time() k = 0 for i in range(10000): for j in range(10000): k = i + j end = time.time() total = end - start print("Job_3 Completed in", total) start = time.time() job_1() job_2() job_3() end = time.time() total = end - start print("Total time taken is",total)
""" This file contains functions for transforming tensorflow tensors that represents images. These are used in order to get better-looking results when performing feature-visualizations. """ import tensorflow as tf import math # TODO: fill in the rest of the functions def random_param(param_list): random_index = tf.random_uniform((), 0, len(param_list), dtype='int32') param = tf.constant(param_list)[random_index] param = tf.identity(param, name='random') return param def pad(tensor, pad): padding = tf.constant([[pad, pad], [pad, pad], [0, 0]]) return tf.pad(tensor, padding, constant_values=0.459) def jitter(tensor, jitter_x, jitter_y): pass # the following function is really just a random crop ..this implementation assumes that there is # sufficient padding at the start, so a random crop sorta has the same effect on helping the visualization def random_jitter(tensor, pixels): dimensions = tf.shape(tensor) height, width = dimensions[0], dimensions[1] new_dimensions = [height - pixels, width - pixels, 3] tensor = tf.random_crop(tensor, new_dimensions) return tensor def rotate(tensor, angle): pass def random_rotate(tensor, param_list): angle = random_param(param_list) angle = tf.cast(angle, dtype='float32') radian = angle * tf.constant(math.pi, dtype='float32') / 180 tensor = tf.contrib.image.rotate(tensor, radian) return tensor def scale(tensor, factor): pass def random_scale(tensor, param_list): factor = random_param(param_list) dimensions = tf.shape(tensor) height, width = tf.cast(dimensions[0], dtype='float32'), tf.cast(dimensions[1], dtype='float32') scale_height, scale_width = tf.cast(height * factor, dtype='int32'), tf.cast(width * factor, dtype='int32') tensor = tf.expand_dims(tensor, 0) tensor = tf.image.resize_bilinear(tensor, [scale_height, scale_width]) tensor = tf.squeeze(tensor, 0) return tensor
class Data: def __init__(self, data): tmp = data.split("|") self.name = tmp[0] self.age = tmp[1] self.grade = tmp[2] def print_age(self): print(self.age) def print_grade(self): print("%s님 당신의 점수는 %s입니다." % (self.name, self.grade)) data = Data("홍길동|42|A") data.print_age() data.print_grade()
f1 = open("test.txt", 'w') f1.write("Life is too shor!") f1.close() f2 = open("test.txt", 'r') print(f2.read()) f2.close() # close를 명시적으로 할 필요가 없는 with구문 with open("test.txt", 'w') as f1: f1.write("Life is too short!") with open("test.txt", 'r') as f2: print(f2.read()) # 'a' 모드 user_input = input("저장할 내용을 입력하세요:") f = open('abc.txt', 'a') # 내용을 추가하기 위해서 'a'를 사용 f.write(user_input) f.write("\n") # 입력된 내용을 줄단위로 구분하기 위해 줄바꿈 문자 삽입 f.close() # 역순 저장 f = open('abc.txt', 'r') lines = f.readlines() # 모든 라인을 읽음 f.close() print(lines) rlines = reversed(lines) # 읽은 라인을 역순으로 정렬 f = open('abc.txt', 'w') for line in rlines: line = line.strip() # 포함되어 있는 줄바꿈 문자 제거 f.write(line) f.write('\n') # 줄바꿈 문자 삽입
input1 = input("첫번째 숫자를 입력하세요:") input2 = input("두번째 숫자를 입력하세요:") total = int(input1) + int(input2) print("두 수의 합은 %s 입니다" % total)
def mul(*args): result = 1 for n in args: result *= n print(result) mul(1,2,3,4,5)
import math a = float(input("Enter the value of a")) if(a>0): b= float(input("Enter the value of b")) c=float(input("Enter the value of c")) Uroot = (b*b)-(4*a*c) x1= (-b+math.sqrt(Uroot))/(2*a) x2 = (-b-math.sqrt(Uroot))/(2*a) print("The value of x1 and x2 is:") print(x1,x2); else: print("The Value of a should be Greater then 0 to be Quadradic Equation")
String1= "{l} {f} {g}".format(g="Geeks",f="For",l="Life") print("\nPrint String in order of Keyword: ") print(String1)
p =float(input("Enter the principal amount")) t = float(input("Enter the Time")) r = float(input("Enter the rate")) print("The simple interest is ",(p*t*r)/100)
def largest(arr,num): max=arr[0] for i in range(0,num): if(arr[i]>max): max=arr[i] return max arr=[] num=int(input("Enter the Array Size")) print("Enter the Array") for i in range(0,num): item=int(input()) arr.append(item) ans = largest(arr,num) print(arr) print("Largest num is ",ans)
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ digits = 0 xCopy = int(str(x)[:]) #Used to form reversed integer power = len(str(abs(x))) - 1 for i in range(len(str(x))): #Runs on all digits of x digits += (abs(xCopy) % 10) * (10 ** power) #Multiplies smallest digit by largest power power -= 1 xCopy = abs(xCopy) // 10 if x < 0: digits = -int(digits) #Adjusts sign of digits depending on sign of x if abs(digits) >= (2**31) - 1: #If reversed number is out of range, make digits 0 digits = 0 return digits
# -*- coding: utf-8 -*- ''' Common utility methods for key concept extraction. ''' from nltk.corpus import stopwords as nltk_stopwords import unicodedata def ascii_approximation(s): """ Returns an ascii "approximation" to the given unicode string. @param s: The string to be approximated. """ if not isinstance(s, unicode): s = str(s).decode('utf-8', 'replace') return unicodedata.normalize('NFKD', s).encode('ASCII', 'replace') def wash_string(text): text = text.replace(")", "") text = text.replace("(", "") return text.strip() def default_stopwords(): ''' Returns a default set of stopwords. ''' stopwords = nltk_stopwords.words('english') stopwords.extend(['%', "''", "'m", '--', '``', '|', '/', '-', '.', '?', '!', ',', ';', ':', '(', ')', '"', "'", '`', '’', "'s"]) return set(stopwords) DEFAULT_STOPWORDS = default_stopwords() MONTHS = set([ 'january', 'jan.', 'jan', 'february', 'feb.', 'feb', 'march', 'mar.', 'mar', 'april', 'apr.', 'apr', 'may', 'june', 'jun.', 'jun', 'july', 'jul.', 'jul', 'august', 'aug.', 'aug', 'september', 'sep.', 'sept.', 'sep', 'sept', 'october', 'oct.', 'oct', 'december', 'dec.', 'dec', ]) def post_process(phrases): """ Returns a version of the given collection of phrases with stop words removed from the beginning and end of phrases and omitting phrases that are too long. @param phrases: The phrases to process. """ filtered_phrases = set([]) for phrase in phrases: phrase, length = trim(phrase) if length > 4 or length == 0 or phrase.lower() in MONTHS: continue filtered_phrases.add(phrase) return filtered_phrases def sub_leaves(tree, node): ''' Extracts and returns leaf nodes in the given tree below the given node. ''' return [t.leaves() for t in tree.subtrees(lambda s: s.node == node)] import nltk.data SENTENCE_DETECTOR = nltk.data.load('tokenizers/punkt/english.pickle') def tag_document(document): tokenized_sentences = [] tagged_sentences = [] for sentence in SENTENCE_DETECTOR.tokenize(document.strip()): #tokens = [ascii_approximation(s) for s in nltk.word_tokenize(sentence)] tokens = [wash_string(token) for token in nltk.word_tokenize(sentence) if wash_string(token)] tags = nltk.pos_tag(tokens) tokenized_sentences.append(tokens) tagged_sentences.append(tags) return tokenized_sentences, tagged_sentences def trim(phrase): ''' Returns a version of the given phrase with stop words removed from the beginning and end of the phrase. @param phrase: The phrase to trim. ''' words = phrase.split() while words and words[0] in DEFAULT_STOPWORDS: words.pop(0) while words and words[-1] in DEFAULT_STOPWORDS: words.pop(-1) return " ".join(words), len(words)
class MyTime(object): def __init__(self, time): self._time = time self._hours = int(self._time.split(':')[0]) self._minutes = int(self._time.split(':')[1]) self._seconds = int(self._time.split(':')[2]) def get_hours(self): return self._hours def get_minutes(self): return self._minutes def get_seconds(self): return self._seconds def advance(self, hours, minutes, seconds): self._hours += hours if self._hours + hours < 25 else hours - 24 self._minutes += minutes if self._minutes + minutes < 61 else hours - 60 self._seconds += seconds if self._seconds + seconds < 61 else hours - 60 def is_less_than(self, time): owntime = (self.get_hours() * 3600) + (self.get_minutes() * 60) + self.get_seconds() othertime = (time.get_hours() * 3600) + (time.get_minutes() * 60) + time.get_seconds() return owntime < othertime def to_string(self): return '{hh}:{mm}:{ss}'.format(hh=self._hours, mm=self._minutes, ss=self._seconds)
#!/usr/bin/env python # coding: utf-8 # <div class="licence"> # <span>Licence CC BY-NC-ND</span> # <span>François Rechenmann &amp; Thierry Parmentelat</span> # <span><img src="media/inria-25-alpha.png" /></span> # </div> # # `next_start_codon` and `next_stop_codon` # Let us now remember the algorithm that searches for coding regions, that we have seen in the previous sequence, and in which we have been using two utility functions to locate **Start** and **Stop** codons. Here is the code that we used at that time, and that uses the concepts that we just saw in the notebooks on searching patterns in strings in python. # ### The `%` operator for computing moduli # In the following code, we will use the '%' operator that computes the modulo - i.e. the rest in integer division - between two numbers. For example: # In[ ]: # 25 = 2 * 10 + 5 print("the rest of 25 divided by 10 is", 25 % 10) # ### The `continue` statement # Our code this time uses the `continue` statement, that allows to exit the current loop (here a `for` loop) and to **move to the next iteration**. # In[ ]: # an example with a `continue` statement # the main loop scans numbers 0, 1, 2, 3 and 4 for i in range(5): # but we decide to ignore multiples of 3 # and so in this case we just go to the next item in the loop if i % 3 == 0: continue print("dealing with", i) # ### `next_start_codon` : searching a triple on one phase # We can now write the code for `next_start_codon`: # In[ ]: # reminder : the value for the START codon start_codon = "ATG" # In[ ]: # the function used when looking for coding regions def next_start_codon(dna, start): """ locates the next START codon from index start and on the same phase as start returns None when there is no further match """ # starting at index start index = start # while we can find a START codon while True: # looking for a START from that position index = dna.find(start_codon, index) # nothing left if index == -1: return None # if we are not on the same phase as start, we ignore that place if (index - start) % 3 != 0: # in this case we need to move forward a little, # otherwise we will stay here forever index += 3 # and we proceed with the search continue # here there is a match on the right phase, we can return this return index # Let us convince ourselves that the function behaves as expected, with a small test that should cover most cases: # In[ ]: dna = "ATGCGATGTATGCGTGCAGCTGCTAGCTCGTAATGTCGTCATGGATCATCGATCATGG" for phase in 0, 1, 2: print("PHASE", phase) next = phase while next is not None: next = next_start_codon(dna, next) if next is not None: print("found at index", next, dna[next:next+3]) next += 3 # ##### `next_stop_codon` : searching any of 3 triples on a phase # Following a very similar appraoch, we can also now write `next_stop_codon`: # In[ ]: # the regular expressions module import re # reminder : the possible values for the STOP codon # we use a logical OR `|` to search for either 'TAA' or 'TAG' or 'TGA' re_stop = re.compile("TAA|TAG|TGA") # In[ ]: def next_stop_codon(dna, start): """ locates next STOP codon, starting at index start and on the same phase as start returns None when no further match can be found """ # we start at index start index = start # as long as necessary while True: # search a STOP from current index match = re_stop.search(dna, index) # nothing left to find if match is None: return None # if not on the same phase as start, discard this match index = match.start() if (index - start) % 3 != 0: # like above, we need to move forward a bit index += 3 continue # we have a match on the right phase return index # And here again, we can run a quick sweep for testing this function: # In[ ]: print(dna) for phase in 0, 1, 2: print("PHASE", phase) next = phase while next is not None: next = next_stop_codon(dna, next) if next is not None: print("found at index", next, dna[next:next+3]) next += 3
import math i=0 num=0 ''' while i < 10 : i+=1 print("MisionTIC") while i<10: i+=1 print(i) ''' '''Realiza un programa que muestre los numeros impares que hay del 1 al 20 y final muestre la suma de todos ellos'''
"""This file defines the model for a user""" from datetime import datetime from werkzeug.security import check_password_hash from mongoengine import fields, Document, DoesNotExist class User(Document): """Defines a user model for the database Attributes: email: The unique email used to register the user hashed_password: The string representation of the user's hashed password date_registered: The date the user registered for an account email_verified: A flag to track whether the user has verified their email """ email = fields.EmailField(unique=True, required=True) hashed_password = fields.StringField(required=True) date_registered = fields.DateField(default=datetime.now().strftime("%Y-%m-%d")) email_verified = fields.BooleanField(default=False) def check_user_provided_password(self, user_provided_password) -> bool: """Checks the validity of the user provided password Parameters: user_provided_password: password entered by the user Returns: Boolean value associated with validity of user provided password """ return check_password_hash(self.hashed_password, user_provided_password)
"""Code for solving a case of one-dimensional heat conduction in a rod with internal heat generation using 1D quadratic elements""" from __future__ import division import numpy as np from pylab import* """Inputs""" d = float(raw_input("Enter the diameter of the cross-sectional area of the rod(mm): ")) L = float(raw_input("Enter the length of the rod(mm): ")) k = float(raw_input("Enter the thermal conductivity of the material(W/mK): ")) n = int(raw_input("Enter the number of quadratic elements: ")) Q = float(raw_input("Enter the amount of heat generation(W/m3): ")) q = float(raw_input("Enter the heat flux(W/m2): ")) Temp = float(raw_input("Enter the temperature of the rod end(celsius): ")) """Factors""" fac = (k * ((pi/4)*((d/1000)**2)))/(3*((L/1000)/n)) gen = ((pi/4)*((d/1000)**2)*((L/1000)/n)*Q) """Matrices Declaration""" G = np.zeros([(2*n+1), (2*n+1)]) mat = np.zeros([(2*n+1), (2*n+1)]) trim = np.zeros([(2*n), (2*n)]) fq = np.zeros([(2*n+1), (1)]) FQ = np.zeros([(2*n+1), (1)]) FG = np.zeros([(2*n), (1)]) trimFQ = np.zeros([(2*n), (1)]) TPlot = [] Local = [] """Form the element conductance matrix""" matrix = np.matrix([[(7*fac), (-8*fac), fac], [(-8*fac), (16*fac), (-8*fac)], [(fac), (-8*fac), (7*fac)]]) """Form the heat generation vector""" H = np.matrix([[(gen/6)], [(2*gen)/3], [gen/6]]) """Direct Stiffness Method""" """Formation of global heat generation vector""" l = 0 m = 0 p = 0 for k in range(0, 2*n-1): if(k%2 == 0): for i in range(k, k+3): fq[i,0] = H[p,0] p = p + 1 for j in range(k, k+3): mat[i,j] = matrix[l,m] m = m + 1 l = l + 1 m = 0 G = G + mat mat = np.zeros([(2*n+1), (2*n+1)]) FQ = FQ + fq fq = np.zeros([(2*n+1), (1)]) l = 0 p = 0 """Solve using elimination approach""" for i in range(0, 2*n): trimFQ[i,0] = FQ[i,0] if(i == 0): FG[i,0] = ((pi/4)*((d/1000)**2))*q elif(i == (2*n-1) or i == (2*n-2)): FG[i,0] = -1 * G[i,2*n] * Temp else: FG[i,0] = 0 for j in range(0, 2*n): trim[i,j] = G[i,j] trim = np.matrix(trim) T = (trim.I) * (trimFQ + FG) finalT = np.vstack((T,Temp)) print "Nodal temperatures are: \n", finalT """Plot using the interpolation functions""" val = 0 dist = 0 carry = 0 for k in range(0, 2*n-1): if (k%2 == 0): for p in range(0, 11, 1): s = p/10 val = (2*finalT[k,0]*(s-0.5)*(s-1)) + (-4*finalT[(k+1),0]*s*(s-1)) + (2*finalT[(k+2),0]*s*(s-0.5)) TPlot.append(val) dist = (carry*(L/n)) + (s*(L/n)) Local.append(dist) carry = carry + 1 plot(Local, TPlot) xlabel("Rod length(mm)") ylabel("Temperature(celsius)") grid() show()
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.37 工具: python == 3.7.3 介绍: 熟悉pandas基本功能,参考《利用Python进行数据分析》5.2 """ import pandas as pd from pandas import Series, DataFrame import numpy as np """ 重建索引 """ print('Example 1:') obj = pd.Series([4.5, 7.3, -5.3, 3.6], index=['d', 'b', 'a', 'c']) print(obj) #d 4.5 #b 7.3 #a -5.3 #c 3.6 #dtype: float64 # reindex方法将按照新的索引排序,如果索引的值不存在,将填入缺失值 print('Example 2:') obj2 = obj.reindex(['a', 'b', 'c','d','e']) print(obj2) #a -5.3 #b 7.3 #c 3.6 #d 4.5 #e NaN #dtype: float64 # 可以使用ffill等方法在重建索引时进行差值 # ffill将值进行前向填充 print('Example 3:') obj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0, 2, 4]) print(obj3) #0 blue #2 purple #4 yellow #dtype: object print(obj3.reindex(range(6), method='ffill')) #0 blue #1 blue #2 purple #3 purple #4 yellow #5 yellow #dtype: object print('Example 4:') print('Example 5:') print('Example 6:') print('Example 7:') print('Example 8:') print('Example 9:') print('Example 10:') print('Example 11:') print('Example 12:') print('Example 13:') print('Example 14:') print('Example 15:') print('Example 16:') print('Example 17:') print('Example 18:') print('Example 19:') print('Example 20:') print('Example 21:') print('Example 22:') print('Example 23:') print('Example 24:') print('Example 25:') print('Example 26:') print('Example 27:') print('Example :')
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 介绍: 介绍Python集合,参考《利用Python进行数据分析》3.1.5 """ """ 集合 """ # 集合使用set()函数,其无序且元素唯一 print('Example 41:') print(set([2, 2, 2, 1, 3, 3])) # {1, 2, 3} # 集合并集 print('Example 42:') a = {1, 2, 3, 4, 5} b = {3, 4, 5, 6, 7, 8} print(a.union(b)) # {1, 2, 3, 4, 5, 6, 7, 8} print(a | b) # {1, 2, 3, 4, 5, 6, 7, 8} # 集合交集 print('Example 43:') print(a.intersection(b)) # {3, 4, 5} print(a & b) # {3, 4, 5} # 集合元素不可变,如果想要包含列表型元素,需要转换为元组 print('Example 44:') my_data = [1, 2, 3, 4] my_set = {tuple(my_data)} print(my_set) # {(1, 2, 3, 4)} # 判断一个集合是否为另一个集合的子集或者超集 print('Example 45:') a_set = {1, 2, 3, 4, 5} print({1, 2, 3}.issubset(a_set)) # True print(a_set.issuperset({1, 2, 3})) # True # 判断集合是否相等 print('Example 46:') print({1, 2, 3} == {3, 2, 1}) # True
import time # 插入排序 def insertion_sort(data): move_count = 0 # 统计移动次数 circle_count = 0 # 统计循环次数 for test n = len(data) for i in range(1, n): for j in range(i, 0, -1): circle_count += 1 # for test if data[j] < data[j-1]: data[j], data[j-1] = data[j-1], data[j] move_count += 1 # for test else: break print(data) print('move_count:', move_count) print('circle_count:', circle_count) a = [3, 4, 7, 6, 45, 23, 69, 9, 55, 21, 11, 8] start = time.clock() insertion_sort(a) end = time.clock() print(end-start) """ 原理:从索引位1开始遍历列表,每一个数字,都和前面的所有数字按从后到前的顺序进行比较,小于则交换位置,大于则不变,重复,直到 完成排序 """
class Solution: def isPalindrome(self, s): """ 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我们将空字符串定义为有效的回文串 示例 1: 输入: "A man, a plan, a canal: Panama", 输出: true :type s: str :rtype: bool """ import re pat = re.compile(r'[\W_]') res = pat.sub('', s) res = res.lower() # print(res) if res == res[::-1]: return True else: return False if __name__ == "__main__": # a = 'kagjkj agjalga rT45RSJFKSJF6algj4567akg__ggkj_' a = "A man, a plan, a canal: Panama" res = Solution() print(res.isPalindrome(a))
# def tower_builder(n_floors): # # 方法一 # # list_res = [] # # for i in range(1, 2*n_floors, 2): # # #temp = (i+1)//2 # # list_res.append((n_floors-(i+1)//2)*" " + i * "*"+ (n_floors-(i+1)//2)*" ") # # return list_res # # 方法二 # #return [(n_floors-(i+1)//2)*" " + i * "*"+ (n_floors-(i+1)//2)*" " for i in range(1, 2*n_floors, 2)] # # 方法三 # return [("*"*(2*i-1)).center(2*n_floors -1) for i in range(1, n_floors+1)] # # print(tower_builder(3)) def test(): print('test',5+5) test()
# # def quick_sort(arrys, left, right): # if left >= right: # return arrys # # key = arrys[left] # # 将左边第一位定位基准数,以此数将序列分为两部分 # low = left # high = right # while left != right: # # 从最右边开始查(一定要从最右边开始查),查找比基准值小的数 # while left < right and arrys[right]>=key: # right -= 1 # arrys[left] = arrys[right] # # 从最左边开始查,查找比基准值大的数 # while left < right and arrys[left] <= key: # left += 1 # arrys[right] = arrys[left] # # arrys[right] = key # # # 分别对两部分数据再调用quick_sort函数 # quick_sort(arrys, low, left-1) # quick_sort(arrys, left+1, high) # # return arrys # # # if __name__ =="__main__": # # lis = [1, 2, 5, 3, 8, 29, 3] # n = len(lis) # quick_sort(lis, 0, n-1) # # print(quick_sort(lis, 0, n-1)) def shell_sort(alist): n = len(alist) # 初始步长 gap = int(n / 2) while gap > 0: # 按步长进行插入排序 for i in range(gap, n): j = i # 插入排序 while j>=gap and alist[j-gap] > alist[j]: alist[j-gap], alist[j] = alist[j], alist[j-gap] j -= gap # 得到新的步长 gap = int(gap / 2) alist = [54,26,93,17,77,31,44,55,20] shell_sort(alist) print(alist)
class MinStack: def __init__(self): """ initialize your data structure here. """ self.head = -1 self.data = [] def push(self, x): """ :type x: int :rtype: void """ # if self.head == -1: self.data.append(x) self.head += 1 def pop(self): """ :rtype: void """ elem = self.data.pop() self.head -= 1 return elem def top(self): """ :rtype: int """ if self.head == -1: return None else: return self.data[self.head] def getMin(self): """ :rtype: int """ if self.head == -1: return None else: index = self.head min_elem = self.data[self.head] while index >= 0: min_elem = min(min_elem, self.data[index]) index -= 1 return min_elem # Your MinStack object will be instantiated and called as such: obj = MinStack() minStack = MinStack() minStack.push(-2) minStack.push(0) minStack.push(-3) # minStack.getMin() print(minStack.getMin()) print(minStack.pop()) print(minStack.top()) print(minStack.getMin()) # minStack.getMin()
def longestchildlist(arr): arr2 = arr[::-1] res = [] for i in range(1, len(arr)): b = [] for v in arr2[i-1:]: if len(b): if v < b[0]: b.insert(0, v) else: b.insert(0, v) if len(b) > len(res): res = b return res if __name__ == "__main__": a = [1,7,3,5,9,6,8,4,2,9,7,5] print(longestchildlist(a))
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums.count(target): nums.append(target) nums.sort() return nums.index(target) if __name__ == "__main__": lis = [1, 3, 5, 6] num = 2 res = Solution() res.searchInsert(lis, num) """ 35. 搜索插入位置 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 示例 2: 输入: [1,3,5,6], 2 输出: 1 """
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if needle is not '': if needle in haystack: return haystack.index(needle) else: return -1 else: return 0 if __name__ == "__main__": haystack = "hello" needle = "ll" res = Solution() print(res.strStr(haystack, needle)) """ 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 示例 1: 输入: haystack = "hello", needle = "ll" 输出: 2 示例 2: 输入: haystack = "aaaaa", needle = "bba" 输出: -1 说明: 当 needle 是空字符串时,我们应当返回什么值呢? 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。 """
class Solution: def lengthOfLastWord(self, s): """ 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 . 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 :type s: str :rtype: int """ res = s.strip().split(' ') if any(res): return len(res[-1]) else: return 0 if __name__ == '__main__': s = 'ajgakj kajga gkajg lakjgk ' temp = Solution() print(temp.lengthOfLastWord(s))
#comment added for git push practice dashboard = ['-'for i in range(9)] game_is_running = True current_player = 'X' winner = None def play_game(): global game_is_running global winner show_board() while game_is_running: handle_turn(current_player) check_if_gameover() flip_player() if winner == 'X' or winner == 'O': print(winner + "'s won") elif winner == None : print("Tie") def show_board(): print("\n") print(dashboard[0] +'|' + dashboard[1]+'|'+dashboard[2]+"\t 1|2|3") print(dashboard[3] +'|' + dashboard[4]+'|'+dashboard[5]+"\t 4|5|6") print(dashboard[6] +'|' + dashboard[7]+'|'+dashboard[8]+"\t 7|8|9") print("\n") def handle_turn(player): print(player + "'s turn") position = int(input("Enter no. between 1 to 9:\n")) valid = False while not valid: while position not in range(1,10): print("invalid input;\nplese select number between 0 to 9") position = int(input("Enter no. between 1 to 9:")) position -=1 if dashboard[position] == "-": valid = True else: print("you cant go there,select different input") dashboard[position] = player show_board() def check_if_gameover(): check_for_winner() check_for_tie() def check_for_winner(): global winner row_winner = row_matched() col_winner = col_matched() dia_winner = dia_matched() if row_winner: winner = row_winner elif col_winner: winner = col_winner elif dia_winner: winner = dia_winner else: winner = None def row_matched(): global game_is_running row_1 =dashboard[0]==dashboard[1]==dashboard[2]!= '-' row_2 =dashboard[3]==dashboard[4]==dashboard[5]!= '-' row_3 =dashboard[6]==dashboard[7]==dashboard[8]!= '-' if row_1 or row_2 or row_3 : game_is_running = False if row_1: return dashboard[0] elif row_2: return dashboard[3] elif row_3: return dashboard[6] else: return None def col_matched(): global game_is_running col_1 =dashboard[0]==dashboard[3]==dashboard[6]!= '-' col_2 =dashboard[1]==dashboard[4]==dashboard[7]!= '-' col_3 =dashboard[2]==dashboard[5]==dashboard[8]!= '-' if col_1 or col_2 or col_3 : game_is_running = False if col_1: return dashboard[0] elif col_2: return dashboard[1] elif col_3: return dashboard[2] else: return None def dia_matched(): global game_is_running dia_1 =dashboard[0]==dashboard[4]==dashboard[8]!= '-' dia_2 =dashboard[2]==dashboard[4]==dashboard[6]!= '-' if dia_1 or dia_2 : game_is_running = False if dia_1: return dashboard[0] elif dia_2: return dashboard[2] else: return None def check_for_tie(): global game_is_running if '-' not in dashboard: game_is_running = False # return True # # else: # return False def flip_player(): global current_player if current_player == 'X': current_player = 'O' elif current_player == 'O': current_player = 'X' play_game()
# Selection sort is proces of sorting an array. # In Selection sort, we take the smallest value in the array and swap it with the first element in the unsorted part. def selectionSort(list): for i in range(len(list)-1): minvalue = i for j in range(i+1,len(list)): if(list[minvalue] > list[j]): minvalue = j temp = list[i] list[i] = list[minvalue] list[minvalue] = temp return list list = [50,20,80,10,60] sorted = selectionSort(list) print(sorted)
import os import random # Defining the suits and ranks of a given card suits = ["Spades", "Hearts", "Diamonds", "Clubs"] ranks = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"] player_hands = [] player_bids = [] player_chips = [] def create_deck(): # Create a full deck with 52 cards deck = [] for suit in suits: for rank in ranks: deck.append((suit, rank)) return deck def deal(hand, deck): # Place one card from the deck to a hand hand.append(deck.pop()) def calc_score(hand): # Calculate the score of a given hand total = 0 at_least_one_ace = False for card in hand: if card[1] == "Jack" or card[1] == "Queen" or card[1] == "King": total += 10 elif card[1] == "Ace": total += 1 at_least_one_ace = True else: total += card[1] if at_least_one_ace is True and total <= 11: total += 10 return total def card_details(card): # Return information about a specific card return str(card[1]) + " of " + card[0] def hand_details(player_hand): # Return card information and score of a given hand hand_str = "You have " for card in player_hand: hand_str += card_details(card) + ", " hand_str += "for a total of " + str(calc_score(player_hand)) return hand_str def dealer_details(dealer_hand): # Return information about the dealer. Starts differently from player. hand_str = "The dealer has " for card in dealer_hand: hand_str += card_details(card) + ", " hand_str += "for a total of " + str(calc_score(dealer_hand)) return hand_str def player_is_bust(player_hand): # To find out if a player busted! if calc_score(player_hand) > 21: return True else: return False def blackjack(hand): # To find out if a player got blackjack! if calc_score(hand) == 21: return True else: return False def clear(): # Commands for clearing the terminal when necessary if os.name == 'nt': os.system('CLS') if os.name == 'posix': os.system('clear') def reveal_results(dealer_hand, player_hands, player_chips, player_bids): # Redistribute chips based on everyone's cards and amount bid # Evaluating results for every single player for i in range(len(player_hands)): if player_is_bust(player_hands[i]): print("Player " + str(i + 1) + " busted, losing " + str(player_bids[i]) + " chips.") player_chips[i] -= player_bids[i] elif blackjack(player_hands[i]) is True and blackjack(dealer_hand) is False: print("Player " + str(i + 1) + " got blackjack, winning " + str(player_bids[i] * 2) + " chips.") player_chips[i] += player_bids[i] * 2 elif not player_is_bust(dealer_hand) and calc_score(player_hands[i]) > calc_score(dealer_hand): print("Player " + str(i + 1) + " wins, winning " + str(player_bids[i]) + " chips!") player_chips[i] += player_bids[i] elif player_is_bust(dealer_hand): print("The dealer busted. Player " + str(i + 1) + " wins " + str(player_bids[i]) + " chips!") player_chips[i] += player_bids[i] elif calc_score(player_hands[i]) < calc_score(dealer_hand): print("Player " + str(i + 1) + " lost, losing " + str(player_bids[i]) + " chips!") player_chips[i] -= player_bids[i] elif calc_score(player_hands[i]) == calc_score(dealer_hand): print("Player " + str(i + 1) + " had a draw! No chips were lost!") def display_players_stats(num_players): # Print out information about each player when a round ends or someone quits for i in range(num_players): print("Player " + str(i + 1) + " has " + str(player_chips[i]) + " chips.") def restart_game(): # Clearing the player cards and bids to prepare for the next game del player_hands[:] del player_bids[:] def player_bankrupts(players): # Determining if any player has 0 chips remaining for chip_remaining in players: if chip_remaining == 0: return True return False def game(): clear() enter_game = False while enter_game is False: # Catching invalid input for number of players try: num_players = int(input("Welcome to BlackJack!\nHow many players are playing? (Up to 3)")) if num_players > 3 or num_players < 1: print("That is an invalid number of players. Try again!") else: enter_game = True except ValueError: print("Please type an integer between 0 and 3") print("The game is starting! Each player gets 500 chips to start out with!") for i in range(num_players): player_chips.append(500) while not player_bankrupts(player_chips): global_deck = create_deck() random.shuffle(global_deck) dealer_hand = [] deal(dealer_hand, global_deck) deal(dealer_hand, global_deck) print("The dealer is showing a " + card_details(dealer_hand[0])) for i in range(num_players): print("Player " + str(i + 1) + ": it's your turn!") player_hand = [] valid_bid = False while valid_bid is False: # Catching invalid input for amount to bid try: bid = int(input("How much would you like to bid? You have " + str(player_chips[i]) + " chips.")) if bid < 0 or bid > player_chips[i]: print("That is an invalid amount to bid. Try again!") else: valid_bid = True player_bids.append(bid) except ValueError as e: print("Please type a valid integer for bidding!") deal(player_hand, global_deck) deal(player_hand, global_deck) print(hand_details(player_hand)) while player_is_bust(player_hand) is False: choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower() clear() if choice == "h": deal(player_hand, global_deck) print(hand_details(player_hand)) if player_is_bust(player_hand) is True: print("Player " + str(i + 1) + " busted!") player_hands.append(player_hand) break elif choice == "s": print("Player " + str(i + 1) + ", your total is: " + str(calc_score(player_hand))) player_hands.append(player_hand) break elif choice == "q": print("Ending game...") display_players_stats(num_players) exit() else: print("Invalid choice. Try again.") # Dealer's Turn while calc_score(dealer_hand) < 17: deal(dealer_hand, global_deck) print(dealer_details(dealer_hand)) if player_is_bust(dealer_hand): print("The dealer busted!") reveal_results(dealer_hand, player_hands, player_chips, player_bids) display_players_stats(num_players) restart_game() if player_bankrupts(player_chips) is False: print("\nNew round coming up!\n") print("Someone lost all of their chips! Therefore, the dealer wins! Thanks for playing!") if __name__ == "__main__": game()
class user(object): def __init__(self,name,email,password): self.name = name self.email = email self.password = password self.friends_list = [] self.posts = [] def add_friend(self,email1,friends_list): self.email1 = email1 self.friends_list.append(self.email1) print (self.name +" had added "+self.email1 +" as a friend") def remove_friend(self,email1,friends_list): self.email1 = email1 self.friends_list.remove(self.email1) print (self.name+" had removed "+ self.email1 +" from your friends_list ") def Post (self,text): post1 = post ("blhhh", [],[]) self.posts.append(text) print (self.name+"has posted: "+text) def get_userInfo (self): print ("Name: " + self.name) print ("Email: " + self.email) print ("Password: " + self.password) print ("Friends: " , self.friends_list) print ("Posts: " , self.posts) class post (user): def __init__(self, share , likes, email): self.email = email self.comments = [] self.likes = likes def add_Like (self, likes): self.likes = self.likes + 1 print ("likes: " + str(self.likes)) user1 = user("Loai","[email protected]", "myhiddenpassword123") user2 = user("dod","[email protected]", "myhiddenpassword") user3 = user ("zi" , "[email protected]" , "bibi") user1.add_friend ("dod", user1.friends_list) user1.Post ("blahhhhhhh") user2.get_userInfo() user1.add_friend("zi" , user1.friends_list) user1.remove_friend("zi", user1.friends_list)
import numpy as np import matplotlib.pyplot as plt import ml.linear_regression as lire from ml.gradient_descent import gradient_descent data = np.loadtxt("ml_course_material/machine-learning-ex1/ex1/ex1data1.txt", delimiter=",") (m, feature_length_with_result) = data.shape x = data[:, 0].reshape((m, feature_length_with_result - 1)) y = data[:, 1].reshape((m, 1)) x_m = np.hstack((np.ones((m, 1)), x)) (theta, costs) = gradient_descent(x_m, y, lire.linear_regression_cost, lire.linear_regression_cost_derivative) plt.subplot(211) plt.plot(x, y, "xr", x, x_m @ theta) plt.subplot(212) plt.plot(costs) plt.show()
import numpy as np import ml.utils as utils def feed_forward(X, Thetas): """ Feeds the inputs X through neural network represented by Theta matrices. :param X: inputs: m x n (m examples, n features) :param Thetas: Theta matrix for each layer :return: matrix of shape m x #neurons_in_output_layer """ (m, n) = X.shape A = X.T for Theta in Thetas: A = np.vstack((np.ones((1, m)), A)) Z = Theta @ A A = utils.sigmoid(Z) return A.T def neural_network_cost(X, Y, Thetas, regularization_lambda=0): (m, n) = X.shape H_X = feed_forward(X, Thetas) total_cost = 0 for i in range(m): y = Y[i].T h_x = H_X[i].T cost_i = -y * np.log(h_x) - (1 - y) * np.log(1 - h_x) total_cost += cost_i.sum() regularization = 0 if (regularization_lambda): regularization_sum = 0 for Theta in Thetas: Theta_without_bias = Theta[:, 1:] regularization_sum += (Theta_without_bias ** 2).sum((0, 1)) regularization = regularization_sum return total_cost / m + regularization_lambda / (2 * m) * regularization def neural_network_cost_unrolled(X, Y, theta, shapes, regularization_lambda=0): Thetas = utils.roll(theta, shapes) return neural_network_cost(X, Y, Thetas, regularization_lambda) def sigmoid_gradient(z): sigmoid_z = utils.sigmoid(z) return sigmoid_z * (1 - sigmoid_z) def neural_network_cost_gradient(X, Y, Thetas, regularization_lambda=0): (m, n) = X.shape cost = 0 Deltas = [np.zeros(Theta.shape) for Theta in Thetas] for (idx, x) in enumerate(X): list_a = [x.reshape((len(x), 1))] list_z = [] for Theta in Thetas: list_a[-1] = np.vstack((np.array([1]), list_a[-1])) list_z.append(Theta @ list_a[-1]) list_a.append(utils.sigmoid(list_z[-1])) y = Y[idx].reshape((Y.shape[1], 1)) h_x = list_a.pop() cost += (-y * np.log(h_x) - (1 - y) * np.log(1 - h_x)).sum() list_z.pop() delta_last_layer = h_x - y for layer_idx in reversed(range(len(Thetas))): Deltas[layer_idx] += delta_last_layer @ list_a.pop().T if layer_idx > 0: delta_last_layer = (Thetas[layer_idx].T @ delta_last_layer)[1:, :] * sigmoid_gradient(list_z.pop()) Deltas = [Delta / m for Delta in Deltas] cost /= m if regularization_lambda: regularization_sum = 0 for Theta in Thetas: Theta_without_bias = Theta[:, 1:] regularization_sum += (Theta_without_bias ** 2).sum((0, 1)) cost += regularization_lambda / (2 * m) * regularization_sum for idx in range(len(Thetas)): Theta_without_bias = Thetas[idx][:, 1:] Deltas[idx][:, 1:] += Theta_without_bias * (regularization_lambda / m) return cost, Deltas def neural_network_cost_gradient_unrolled(theta, X, Y, shapes, regularization_lambda=0): Thetas = utils.roll(theta, shapes) (cost, Deltas) = neural_network_cost_gradient(X, Y, Thetas, regularization_lambda) return cost, utils.flatten_and_stack(Deltas)[0].reshape((-1)) def initialize_random_theta(shape, epsilon_init=0.12): rng = np.random.default_rng() return rng.random((shape[0], shape[1] + 1)) * 2 * epsilon_init - epsilon_init
"""Calculate the equation inside the list in order of operation. The first and last item will always be a number. Numbers are separated by a + or * symbol. All items are in individual strings. Examples: >>> calculate(["6", "+", "8", "*", "12", "+", "47"]) 149 >>> calculate(["1", "+", "1", "+", "1"]) 3 >>> calculate(["1", "+", "1", "*", "1", "+", "20"]) 22 """ def calculate(lst): """Mathematically calculates items inside list in order of operation.""" new_lst = [] if "*" in lst: for index in range(len(lst) - 1): if lst[index] == "*": product = int(lst[(index - 1)]) * int(lst[(index + 1)]) new_lst.append(product) lst.pop(index - 1) new_lst.pop(index - 1) else: new_lst.append(lst[index]) # print new_lst else: for index in range(len(lst)): new_lst.append(lst[index]) # print new_lst another_lst = [] for item in new_lst: if item != "+": another_lst.append(int(item)) result = 0 for n in another_lst: result += n return result # BRAINSTORMING IDEAS # if I could use sum() # return sum(another_lst) # for item in new_lst: # if item % 2 != # answer = 0 # for index in range(len(new_lst) - 1): # if index % 2 != 0: # result = new_lst[index] + new_lst[index + 2] # answer += result # print answer if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TEST PASSED. AWESOMESAUCE!\n"
def print_node_at_depth(root, depth): def wut_depth(root, depth, current_d): # base case if current_d == depth: print node else: current_d += 1 wut_depth(root.left, depth, current_d) wut_depth(root.right, depth, current_d)
def calc_change(n): penny = 1 nickle = 5 dime = 10 quarter = 25 coins = { quarter: 0, dime: 0, nickle: 0, penny: 0 } while n > 0: if n >= quarter: n -= 25 coins[quarter] += 1 elif n >= dime: n -= 10 coins[dime] += 1 elif n >= nickle: n -= 5 coins[nickle] += 1 else: n -= penny coins[penny] += 1 print coins calc_change(55)
""" Write a function that reverses a string. Use as much memory as you want. """ def reverse_str(string): lst = list(string) current = len(lst) - 1 new_lst = [] while current > -1: new_lst.append(lst[current]) current -= 1 #print new_lst return "".join(new_lst) print reverse_str("cat") print reverse_str("my cat") print reverse_str(" ") print reverse_str("") print reverse_str("123")
''' The classical introductory exercise. Just say "Hello, World!". "Hello, World!" is the traditional first program for beginning programming in a new language or environment. The objectives are simple: Write a function that returns the string "Hello, World!". Run the test suite and make sure that it succeeds. Submit your solution and check it at the website. If everything goes well, you will be ready to fetch your first real exercise. ''' def hello(): return("Hello, World!")
# Written by Eric Martin for COMP9021 # # Prompts the user for an arity (a natural number) n and a word. # Call symbol a word consisting of nothing but alphabetic characters # and underscores. # Checks that the word is valid, in that it satisfies the following # inductive definition: # - a symbol, with spaces allowed at both ends, is a valid word; # - a word of the form s(w_1,...,w_n) with s denoting a symbol and # w_1, ..., w_n denoting valid words, with spaces allowed at both ends # and around parentheses and commas, is a valid word. import sys import re import fileinput class Error(Exception): def __init__(self,msg): Error.msg=msg def token(in_str): token_list=list() tmp_list=re.findall(r"[_a-zA-Z]+|\(|\)|,| ",in_str) #print(tmp_list) tmp_len=0 for token in tmp_list: if re.fullmatch(r"[_a-zA-Z]+",token): token_list.append([token,0]) tmp_len+=len(token) elif re.fullmatch(r"\(|\)",token): token_list.append([token,1]) tmp_len+=1 elif token==',': token_list.append([token,2]) tmp_len+=1 elif token==' ': token_list.append([token,3]) tmp_len+=1 if tmp_len!=len(in_str): raise Error("Length Error") return token_list def is_word_brackets(tl,rg,n,depth): if len(tl)<4: raise Error("not brackets word") while tl[rg[0]][0]==' ': rg[0]+=1 while tl[rg[1]][0]==' ': rg[1]-=1 #tmp="" #for i in range(rg[0],rg[1]+1): # tmp+=tl[i][0] #tmp="is_brackets_word : "+tmp #print(tmp) tmp=rg[0] try: while tl[tmp][0]!='(': tmp+=1 tmp-=1 except: raise Error("out of range") if not is_word_symbol(tl,[rg[0],tmp],depth+1): raise Error("Format Error - not a symbol") rg[0]=tmp+1 if tl[rg[0]][0]!='(' or tl[rg[1]][0]!=')': raise Error("Format Error - brackets") rg[0]+=1 rg[1]-=1 tmp_cnt=0 brackets_list=list() tmp_stack=list() flag=True for i in range(rg[0],rg[1]+1): if tl[i][0]=='(': tmp_stack.append(1) elif tl[i][0]==')': if len(tmp_stack)>=1: tmp_stack.pop() else: raise Error("Brackets Error") elif tl[i][0]==',': if len(tmp_stack)==0: brackets_list.append(i) if len(brackets_list)!=n-1: raise Error("Less Error") brackets_list.append(rg[1]+1) #print(brackets_list) for i in range(n): try: is_word(tl,[rg[0],brackets_list[i]-1],n,depth+1) rg[0]=brackets_list[i]+1 except Exception as error: #print(error.msg) return False return True def is_word_symbol(tl,rg,depth): while tl[rg[0]][0]==' ': rg[0]+=1 while tl[rg[1]][0]==' ': rg[1]-=1 #tmp="" #for i in range(rg[0],rg[1]+1): # tmp+=tl[i][0] #tmp="is_symbol_word : "+tmp #print(tmp) if tl[rg[0]][1]==0: return True return False def is_word(tl,rg,n,depth): while tl[rg[0]][0]==' ': rg[0]+=1 while tl[rg[1]][0]==' ': rg[1]-=1 #tmp="" #for i in range(rg[0],rg[1]+1): # tmp+=tl[i][0] #tmp="is_word : "+tmp #print(tmp) if depth==0 and n>1: return is_word_brackets(tl,rg,n,depth+1) for i in range(rg[0],rg[1]+1): if tl[i][1]==1: return is_word_brackets(tl,rg,n,depth+1) return is_word_symbol(tl,rg,depth+1) def is_valid(word, arity): try: token_list=token(word) return is_word(token_list,[0,len(token_list)-1],arity,0) except Exception as error: #print(error.msg) return False return False # REPLACE THE RETURN STATEMENT ABOVE WITH YOUR CODE try: arity = int(input('Input an arity : ')) if arity < 0: raise ValueError except ValueError: print('Incorrect arity, giving up...') sys.exit() word = input('Input a word: ') if is_valid(word, arity): print('The word is valid.') else: print('The word is invalid.')
# 1/1 count_web_words # 1/1 read_url # 1/1 string_to_words # 1.5/2 count_words # Bug as noted! You could remove the empty words here # 2/2 print_descending # 2/2 comments and style # # GRADE: 7.5/8 # Nice work! import urllib.request as web def get_input(): input_url = input("What url do you want to use?") return input_url def read_url(url): """ Reads a webpage. Parameters: url: the url of the webpage Returns: the text of the webpage as a string """ webpage = web.urlopen(url) text = webpage.read() text = text.decode("utf-8") webpage.close() return text def string_to_words(big_string): #BUG: extra spaces make empty list items """ Turns a string into a list, omitting everything but letters and spaces Parameters: big_string: a string Returns: a list with each item an individual word """ assert isinstance(big_string, str) big_string = big_string.lower() simple_string = "" for i in range(0, len(big_string)): if ord("a") <= ord(big_string[i]) <= ord("z") or ord(big_string[i]) == ord(" "): simple_string += big_string[i] elif big_string[i] == "\n": simple_string += " " word_list = simple_string.split(" ") return word_list def count_words(list_words): """ Turns a list of words into a dictionary with words as keys and word counts as values Parameters: list_words: a list of words with one word per item Returns: a dictionary with words and word counts """ assert isinstance(list_words, list) word_counts = {} for word in list_words: if word in word_counts: word_counts[word] = word_counts[word] + 1 else: word_counts[word] = 1 return word_counts def count_web_words(url): """ Takes a webpage and returns a dictionary of the individual words and word counts Parameters: url: the url of the webpage Return Value: a dictionary with words as keys and wordcounts as values """ assert isinstance(url, str) text = read_url(url) word_list = string_to_words(text) word_counts = count_words(word_list) return word_counts def print_descending(word_dict): """ Prints a dictionary of individual words and their counts in descending order of wordcounts Parameters: word_dict: a dictionary of words and wordcounts Pre-conditions: the dictionary's keys should be individual words and the values should be wordcounts Post-conditions: will print each item on its own line with paired keys and items Return Value: None, called for its side effects """ assert isinstance (word_dict, dict) values = list(word_dict.values()) max_value = max(values) num = max_value while num > 0: for key in word_dict: if word_dict[key] == num: print(key, ":", word_dict[key]) num -= 1 def main(): url = get_input() dictionary = count_web_words(url) print_descending(dictionary) #if __name__ == "__main__": # main() if __name__=='__main__': print_descending(count_web_words('http://cs.whitman.edu/%7Eexleyas/course_resources/test2.txt'))
""" anagrams.py What anagrams can be found among 1000 common words in US English? To find out, debug the definition of the find_anagrams function below. In addition to fixing the code, add two comments as follows: # BUG: Show where you found the bug and explain how you found it. # FIX: Briefly explain in English how you fixed the bug. Author: johnsoam ; Andrew Johnson Main topics: Using dictionaries to solve problems; dictionaries with lists as values; debugging """ def sort_letters(word): """ Returns a string containing the letters of the given word, in alphabetical order. """ chars = list(word) chars.sort() return ''.join(chars) def find_anagrams(words): """ Given a list of words, produces a list of lists. Each sublist contains words that are anagrams of each other. """ grouped_words = {} #print(words) # Build a dictionary mapping sorted letters to lists of similar words. for w in words: wsorted = sort_letters(w) if wsorted in grouped_words: grouped_words[wsorted].append(w) #BUG: was appending to non-extent lists, #found by comparing it to mode(data) function #on pg. 378 of text book else: #CORRECTION: if wsorted is not present grouped_words[wsorted] = [] #it must be created as a list first grouped_words[wsorted].append(w) #and then appended # Return a list containing only the groups larger than 1. result = [] for group in grouped_words.values(): if len(group) > 1: result.append(group) return result def retrieve_page(url): """ Retrieve the contents of a web page. The contents is converted to a string before returning it. """ import urllib.request my_socket = urllib.request.urlopen(url) dta = str(my_socket.read()) my_socket.close() return dta def main(): # Get list of 1000 common US English words url = "http://splasho.com/upgoer5/phpspellcheck/dictionaries/1000.dicin" words = retrieve_page(url).strip().split('\\n') # Find and print anagrams anagrams = find_anagrams(words) print("%d anagram groups found" % len(anagrams)) for group in anagrams: print(group) if __name__ == '__main__': main()
import math def distance (x1, y1, x2, y2): """ this fuction finds the distance between two points Parameters: """ distance = math.sqrt(((x2 - x1)**2) + ((y2 - y1)**2)) return distance print(distance(0, 0, 4, 0)) def tri_perimeter(x1, y1, x2, y2, x3, y3): side1 = distance (x1, y1, x2, y2) side2 = distance (x2, y2, x3, y3) side3 = distance (x1, y1, x3, y3) perim = side1 + side2 + side3 return perim print (tri_perimeter(2, 1, 5, 5, 5, 1))
import random def weather (): chance = random.random() if chance < 0.66: print("SNOW") elif chance < 0.99: print ("SUNNY DAY") else: print("RAINS CATS AND DOGS!") def loaded(): chance = random.random() if chance < 0.25: roll = 1 elif chance < 0.50: roll = 6 elif chance < 0.625: roll = 2 elif chance < 0.75: roll = 3 elif chance < 0.875: roll = 4 else: roll = 5 return roll def roll(): chance = random.random() if chance < 1/6: roll = 1 elif chance < 2/6: roll = 6 elif chance < 3/6: roll = 2 elif chance < 4/6: roll = 3 elif chance < 5/6: roll = 4 else: roll = 5 return roll def diceHistogram (trials): two = 0 three = 0 four = 0 five = 0 six = 0 seven = 0 eight = 0 nine = 0 ten = 0 eleven = 0 twelve = 0 for i in range (trials): diceValue = roll() + roll() if diceValue == 2: two = two + 1 if diceValue == 3: three += 1 if diceValue == 4: four += 1 if diceValue == 5: five += 1 if diceValue == 6: six += 1 if diceValue == 7: seven += 1 if diceValue == 8: eight += 1 if diceValue == 9: nine += 1 if diceValue == 10: ten += 1 if diceValue == 11: eleven += 1 if diceValue == 12: twelve += 1 print ("Two's: " + "*"*two) print ("Three's: " + "*"*three) print ("Four's: " + "*"*four) print ("Five's: " + "*"*five) print ("Six's: " + "*"*six) print ("Seven's: " + "*"*seven) print ("Eight's: " + "*"*eight) print ("Nine's: " + "*"*nine) print ("Ten's: " + "*"*ten) print ("Eleven's: " + "*"*eleven) print ("Twelve's: " + "*"*twelve) diceHistogram (300)
VOWELS = "aeiuo" def piglatin(word): return word[1:] + word[0] + "ay" def main(): print(piglatin("python")) print(piglatin("Janet")) print(piglatin("string")) if __name__ == "__main__": main()
import re def get_matching_words(regex): words = ["aimlessness", "assassin", "baby", "beekeeper", "belladonna", "cannonball", "crybaby", "denver", "embraceable", "facetious", "flashbulb", "gaslight", "hobgoblin", "iconoclast", "issue", "kebab", "kilo", "laundered", "mattress", "millennia", "natural", "obsessive", "paranoia", "queen", "rabble", "reabsorb", "sacrilegious", "schoolroom", "tabby", "tabloid", "unbearable", "union", "videotape","bttu0bo"] matches = [] for word in words: if re.search(regex,word): matches.append(word) return matches #1 All words that contain a "v" # print get_matching_words(r'v.') #2 All words that contain a double-"s" # print get_matching_words(r'ss+') #3 All words that end with an "e" #print get_matching_words(r'e$') #4 All words that contain an "b", any character, then another "b" #print get_matching_words(r'b.b') #5 All words that contain a "b", at least one character, then another "b" #print get_matching_words(r'b.+b') #6 All words that contain an "b", any number of characters (including zero), then another "b" #print get_matching_words(r'b\w+b') #7 All words that include all five vowels in order #print get_matching_words(r'a.*e.*i.*o.*u') #8 All words that only use the letters in "regular expression" (each letter can appear any number of times) #print get_matching_words(r'r+e+g+u+l+a+r+e+x+p+r+e+s+s+i+o+n') #9 All words that contain a double letter #print get_matching_words(r'.+')
def layered(x): (arr, multiplier) = x newarr = [] for index in arr: insert = [] one = index * multiplier while one>0: insert.append(1) one = one - 1 newarr.append(insert) print newarr return newarr x = layered(([2,4,5],3))
''' Assignment: Names Part I: Given the following list: ''' students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] ''' Copy Create a program that outputs: Michael Jordan John Rosales Mark Guillen KB Tonel ''' for student in students: print student['first_name'], student['last_name'] ''' Part II: Now, given the following dictionary: ''' users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } ''' Create a program that prints the following format (including number of characters in each combined name): users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } Copy Create a program that prints the following format (including number of characters in each combined name): Students 1 - MICHAEL JORDAN - 13 2 - JOHN ROSALES - 11 3 - MARK GUILLEN - 11 4 - KB TONEL - 7 Instructors 1 - MICHAEL CHOI - 11 2 - MARTIN PURYEAR - 13 ''' print '\n' for key,data in users.iteritems(): print key i = 1 for d in data: print '{} - {} {} - {}'.format(i, d['first_name'].upper(), d['last_name'].upper(), len(d['first_name']+d['last_name']))
# #Multiples - Part I for odd in range(1,1000,2): print odd # #Multiples - Part II for multiple in range(5,1000001,5): print multiple #Sum List sum = 0 arr = [1,2,5,10,255,3] for i in arr: sum+=i print sum #Average List sum = 0 arr = [1,2,5,10,255,3] for i in arr: sum+=i print sum/len(arr)
import matplotlib.pyplot as plt import numpy as np x = [1,2,3,4,5,6,7] y_product1 = [100,200,230,120,500,210,400] y_product2 = [212,323,124,213,102,222,320] plt.plot(x,y_product1) plt.plot(x,y_product2) plt.xlabel("days of week") plt.ylabel("sales of the day") plt.legend(["y_product1","y_product2"]) plt.title("salesof product1 and product2 graph") plt.show()
blocks = [ [ 'bamba is awesome', 'this is it', 'programming is awesome' ], [ "i'm a beast", ] ] for i, block in enumerate(blocks): for j, phrase in enumerate(block): if 'awesome' in phrase: block[j] = phrase.replace('awesome', 'unbelievable') #block[j] = 'a' print(blocks)
"""Reversed. OBS: não confunda com a função reverse() que estudamos nas listas reverse() é uma função das listas somente A relação é parecida com sort() e sorted() Sua função é inverter o iterável A função reversed() retorna um iterável chamado List Reverse Iterator Pode usar em list, tuple, set, dicionário, range, etc """ lista = [1, 2, 3, 4, 5] # Lista: print(list(reversed(lista))) res = tuple(reversed(lista)) print(res) # Podemos iterar sobre o reversed: for letra in reversed('Geremias Corrêa'): print(letra, end='') print() # Podemos fazer o mesmo sem uso do for: print(''.join(list(reversed('Geremias Corrêa')))) # Com o join transformamos a lista de string em uma string novamente. # Mais simples ainda usando o slice de strings: print('Geremias Corrêa'[::-1]) # Usar o reversed para fazer um laço inverso: for n in reversed(range(0,10)): print(n, end=' ') print()
import matplotlib.pyplot as plt # rename as plt x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [2, 3, 5, 3, 4, 7, 9, 7, 10, 8] # Definido título do gráfico plt.title("Título do meu gráfico") # define o título # Definindo nome aos eixos do gráfico: plt.xlabel("Eixo X") # eixo x plt.ylabel("Eixo Y") # eixo y plt.plot(x, y, label="Meus pontos", color="blue") # plot que recebe dois parametros de lista # com o label adc na identificação por cor dos pontos/dados gerados plt.show() # mostra o gráfico e mtela
# Dicas de padrão de código bem escrito do Pep8 """ [1] - CamelCase para nome de classes. class CalculadoraCientifica: pass # pass para não fazer nada mas não gerar erro por falta de código [2] - Utilize nomes em minusculo, separados por underline para funções ou variáveis def soma(a,b): return a+b [3] - Utilize quatro espaços para identação! (obrigatório) - e não utilize tabs, mas sim 'spaces', por conta de variação de configurações if x: pass # quatro espaços para escrita do pass abaixo [4] - Linhas em branco: Duas linhas em branco antes de qualquer definição de classe Separar funções e definições com duas linhas em branco Métodos dentro de uma classe devem ser separados com uma única linha em branco [5] - Imports devem ser feito sempre em linhas separadas, nunca na mesma linha Em caso de muitos imports de um mesmo pacote, recomendasse fazero "from pacote import (pacote1, pacote2, etc), sendo que cada pacote dentro do parentes estejam em uma linha, e o ')' numa outra linha extra [6] - Espaços em expressões e instruções: Não colocar espaços após e antes '(' ou '{' ou '[' etc, assim como antes de fechá-los Deixar UM espaço antes e depois do sinal d '=' [7] - Termine sempre uma instrução com uma nova linha [Extra] - Comentários à direita de código, com duplo espaço, então # e mais um espaço antes da escrita [Extra2] - Nomes dos scripts separados por por underline [Extra3] - Um linha, em Python, deve conter, no máximo, 79 caracteres [Extra4] - Sempre usar espaço antes de usar '+' da concatenação (como em print de variáveis) [Extra5] - Utilizar um linha extra em branco no fim de todo arquivo """
"""Dictionary Comprehension.""" """ Comprehension com uso em dicionários Pense no seguinte: tupla é (), lsita é [], set é {} Mas dicionário tem chave e valor: dicionario = {'a': 1, 'b': 2} Sintaxe: {chave:valor for valor in iterável} Em lista seria [valor for valor in iterável] """ # Exemplo 1: numeros = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} quadrado = {chave: valor ** 2 for chave, valor in numeros.items()} print(quadrado) # Obs: não modificamos, mas poderíamos ter tbm modificado a chave # Exemplo 2 - gerando um dicionário ao quadrado a partir de uma lista: lista = [1, 2, 3, 4, 5] quadrado_2 = {valor: valor ** 2 for valor in lista} print(quadrado_2) # Exemplo 3 - querendo misturas as chaves com valores em um dictionary: chaves = 'abcde' valores = [1, 2, 3, 4, 5] mistura = {chaves[i]: valores[i] for i in range(0, len(chaves))} print(mistura) # Exemplo 4 - Com lógica condicional: numeross = [1, 2, 3, 4, 5] res = {num: 'par' if num % 2 == 0 else 'impar' for num in numeross} print(res) # Obs: pode colocar entre parentes a condicional, como abaixo: # res = {num: ('par' if num % 2 == 0 else 'impar') for num in numeross}
""" POO - Propriedades (Properties). Getters e setters em conjunto da classe usada na aual de abstração e encaps.. Essa refatorando a classe anterior utilizando propriedades (decorators)!! @property para atributos, como se fosse um método Mas o acesso ao atributo é sem os paranteses!! Também do @atributo.setter, funcionando como método setter OBS: aviso para depois colocando aqui tbm: O acesso aos aitrbutos da classe pai por pate das classes filhas para evitar os erros do PyLance (por questão de boa escrita de código), devem ser declarados como protected, ou seja, com apenas um underline (_) Quanto possuo somente uma classe normal, sem filhos herdados delas, tudo bem declarar as variáveis privadas (__), porém quando possuo classes filhas e essas precisarão acessar tais atributos, o correto é criar como protected (_) Na aula de MRO utilizo o protected nos atributos, dar uma olhada lá """ from __future__ import annotations class Account: contador = 400 def __init__(self, titular: str, saldo: float, limite: float) -> None: """Constructor from the class Account. Now, all the atributtes are private.""" self.__titular = titular self.__saldo = saldo self.__limite = limite self.__numero = Account.contador + 1 Account.contador = self.__numero @property def numero(self): return self.__numero @property def limite(self): return self.__limite @property def saldo(self): return self.__saldo @property def titular(self): return self.__titular @limite.setter def limite(self, limite: float): """Docstring setter de limite.""" self.__limite = limite @property def valor_total(self): """Cria-se um atributo de algo que não é atributo, sem problemas.""" return self.__saldo + self.__limite def extract(self) -> None: """To see the actual extract.""" print(f"Saldo atual de: {self.__saldo}\nTitular: {self.__titular}") def deposit(self, valor: float) -> None: """Make a deposit in the account.""" self.__saldo += valor def take(self, valor: float) -> None: """Take a value from the account.""" if(valor > self.__limite): print(f"Saque maior que o limite de {self.__limite} permitido.") elif self.__saldo - valor < 0: print(f"Você não tem saldo suficiente para o saque deste valor") else: self.__saldo -= valor print( f"Saque de {valor} efetuado com sucesso! Seu saldo agora " f"é de {self.__saldo}" ) def transference(self, valor: float, conta_destino: Account) -> None: """Transference between two accounts. Was imported __future__ lib to recognize future calls of the class parameter Account in this function inside Account class.""" self.__saldo -= valor + 10 # 10 is the transference tax, for example conta_destino.__saldo += valor if __name__ == "__main__": c1 = Account('Gere', 1500.00, 500.00) c2 = Account('Gaby', 700.00, 500.00) print(c1.extract()) print(c2.extract()) soma = c1.saldo + c2.saldo print(f"O saldo soma das duas é: {soma}. ") print(f"Limite atual: {c1.limite}") # acessndo via propriedades c1.limite = 1300 # Atribuindo novo limite usando propriedades print(f"Limite atual: {c1.limite}")
""" Type hinting. É a ideia de dar a ideia do tipo de dado recebido no parametro e do tipo de retorno. Entra no Python 3.5 Já faço uso desde o início do curso. É importante entender a tipagem dinâmica Ajuda e muito aos desenvolvedores e a IDE para ter um controle e visão melhor do que está acontecendo. Não costumava usar para declaração/atribuição de varia´veis, assim como pas- -sar nos argumentos de chamadas, aparentemente é o ideal, sempre q possível Recomenda-se sempre o uso do type hinting Inclusive é conhecido como um recurso avançado do Python, fazer uso dele é de notável aprendizado e reconhecimento quanto a saber sobre Python avanc. Prós e contras (de outra aula) do Type hinting: Obs: como utilizo diversas extensões, qualquer erro simples dele a IDE me retorna. Um tanto quanto diferente do mostrado no vídeo Vantagens: Permite maior controle de código Fica mais claro para outros desenvolvedores e mesmo apra você Deixa o software mais robusto Desvantagem: Somente na 3.7 que o recurso se torna completo Deixa o código ainda um pouco mais lento (um pouco só) Se fizer o uso do mypy para checagem, ele só checa os que fazem uso do type hinting. Annotations: É a ideia de fazer anotações, como dizer que retorno da função é x, usar o docstring, utilização correta dos espaços, etc. Tudo que aumenta a clareza do código. Correto: texto: str ) -> str: alinhamento: tipo = valor nome: str = "Geek Un" ativo: bool = True fone: int Incorreto: text:str texto : str )->str: )-> str: ) ->str: alinhamento:tipo=valor alinhamento: tipo=valor alinhetamento:tipo = valor (etcc) """ import math # Exemplo ridículo demonstrativo. def cump(nome: str) -> str: return f"Olá, {nome}" # Desafio def cabecalho(texto: str, alinhamento: bool = True) -> str: if alinhamento: return f"{texto.title()}\n{'-' * len(texto)}" else: return f" {texto.title()} ".center(50, '#') # vai centralizar o conteudo, dado que serão criados # a totalizar 50 # caracteres, ficando o conteudo no meio. def circunferencia(raio: float) -> float: return 2 * math.pi * raio if __name__ == "__main__": print(cump('JJ')) print(cabecalho('geek un', True)) print(cabecalho('geek un', False)) print(circunferencia(5)) print(circunferencia.__annotations__) # Retorna as anotações de código esperadas
""" Operador Walrus. O operador Walrus permite fazer a atribuição e retorno em uma única expressão Apenas para garantir maior patricidade, não há nada novo Sintaxe: variavel := expressão Obs: precisa estar utilizando Python3.8+ para tal (atual 3.8.2) Quando você deve ou não usar este oepraodr: Quando você quiser, desde você conhece o recurso e achar necessário utiliz. """ # Exemplos de uso (direto, sem mostrar o padrão no python pq é óbvio): print(nome := 'Geremias Correa') cesta = [] while (fruta := input("Informe a fruta: ")) != 'jaca': cesta.append(fruta) print(cesta)
""" Teste de memória com Generators. """ from typing import List def fib_lista(max: int) -> List[int]: """Retorna a sequencia de fibonacci.""" nums = [] a, b = 0, 1 while (len(nums)) < max: # Eqnt quantidade de elem. em nums < max nums.append(b) # Insere o elemento b na lista nums a, b = b, a + b # a recebe b, e b recebe a + b return nums # Teste 1 - usou 489MB de consumo de RAM durante todo o proceso: for n in fib_lista(10): print(n) # Função usando geradores agora: def fib_gen(max: int): """Retorna a sequencia de fibonacci usando geradores, retorna yield.""" a, b, contador = 0, 1, 0 while contador < max: a, b = b, a + b yield a contador = contador + 1 # Teste 2 - geradores - 2,8MB de consumo de RAM durante todo o processo: for n in fib_gen(10): print(n) # OBS: Na minha máquina foi 0,3% de 4GB RAM e 77% de CPU, aprox
""" Forçando tipos de dados com decoradores. Vamos ter uma aplicação prática do mesmo Mas com o objetivo de forçar os tipos de dados com os decoradores """ from typing import List def forca_tipo(*tipos): def decorador(funcao): def converte(*args, **kwargs): novo_args = [] for(valor, tipo) in zip(args, tipos): novo_args.append(tipo(valor)) return funcao(*novo_args, **kwargs) return converte return decorador @forca_tipo(str, int) # str para msg, int para vezes def repeat_msg(msg: str, vezes: int): """Repete dada msg x vezes.""" for _ in range(vezes): print(msg) repeat_msg('Hey hey, you you', 5) @forca_tipo(float, float) def dividir(a: float, b: float) -> float: return a / b print(dividir(3, 5.2))
""" Ordered dict, do módulo Collections """ dicionario = {'a': 1, 'b': 2, 'c': 3} for chave, valor in dicionario.items(): print(f'chave {chave}; valor{valor}') # Aqui manteve a ordem, mas isso não é garantido, para isso se tem o Ordered from collections import OrderedDict dicionario = OrderedDict({'a': 1, 'b': 2, 'c': 3}) # Diferença entre dict e ordered dict: # Dicionário comum dic1 = {'a': 1, 'b': 2} dic2 = {'b': 2, 'a': 1} print(dic1 == dic2) # Retorna True, pq aqui a ordem não importa # Ordered Dict order_dic1 = OrderedDict({'a': 1, 'b': 2}) order_dic2 = OrderedDict({'b': 2, 'a': 1}) print(order_dic1 == order_dic2) # Retorna false, pq nele a ordem importa
"""Generators. O que seria o "tuple comprehension" é chamado de generator expression Por isso tal coisa não foi estuda no collections Sintaxe: Igual ao de list, mas ao invpes de [] usa () Ou seja, deixar tudo entre () indica estar usando generators A partir de conversão e uso, aqui o dado tbm é apagado da memória Seu uso é preferível ao uso do List Comprehension, por exemplo """ # Import para uso em um ex, retorna a qtd de bytes em memória do elemento from sys import getsizeof # Aquela verificação da aula passada, sobre se algum nome começa com 'C' # Poderia ter sido feita com generators nomes = ['Carlos', 'Mathilda', 'Leon', 'Julius', 'Carlinhos Bala', 'Vincent Vega'] print(tuple(nome[0] == 'C' for nome in nomes)) # Caso fizesse como list comprehension, bastava fazer em [] # Neste caso, estamos retorna True ou False por conta da condição solicitada # Mostrando quanto bytes a string x está ocupando em memória: x = "Nanananananana Na Beatles" print(getsizeof(x)) print(getsizeof(int)) print(getsizeof(90)) print(getsizeof(float)) print(getsizeof(str)) print(getsizeof(bool)) # Gerando uma lista de números com List Comprehension: list_comp = getsizeof([x * 10 for x in range(1000)]) # Genraod uma lista de num com set comprehension: set_comp = getsizeof({x * 10 for x in range(1000)}) # Gerando umma lista de num com dictionary comprehension: dict_comp = getsizeof({x: x * 10 for x in range(1000)}) # Gerando uma lista com generator: gen_comp = getsizeof(x * 10 for x in range(1000)) print(f"Size list 1000: {list_comp} bytes") print(f"Size set 1000: {set_comp} bytes") print(f"Size dictionary 1000: {dict_comp} bytes") print(f"Size Generator 1000: {gen_comp} bytes") # REPARE QUE CONSOME ABSURDAMENTE MENOS MEMÓRIA!! # Isso porque ele não gera automaticamente, só gera realmente quando for # realmente utilizar # O set e o dict ocupam mais por conta da questão de evitar repetição e # chaves únicas, respectivamente. São classes mais complexas # Iterando no Generator Expression: gen = (x * 10 for x in range(1000)) for num in gen: print(num, end=' ')
""" Escrevendo em arquivos CSV Temos a mesma ideia que na leitura, utilização de duas formas: writer() -> utiliza um escritor para csv writerow() -> escreve uma linha DictWriter -> Utiliza um dicionário para escrever A forma de abertura varia conforme o contexto, aqui foi usado w por exemplific """ from csv import writer from csv import DictWriter # Escrevendo utilizando o writer(): with open('filmes.csv', 'w') as arquivo: escritor_csv = writer(arquivo) filme = None escritor_csv.writerow(['Título', 'Gênero', 'Duração']) # Header # Se for utilizar um arquivo já criado, ele vai reescrev. o header while filme != 'sair': # While is not 'sair' filme = input("Informe o nome do filme: ") if filme != 'sair': genero = input('Informe o genero: ') # input duracao = input("Informe a duração (em minutos): ") # input escritor_csv.writerow([filme, genero, duracao]) # Write in the csv # Escrevendo utilizando o DictWriter(): # OBS: as chaves do dicionário devem ser exatamente as mesmas que as do cabeçalho with open('filmes2.csv', 'w') as arquivo: print("\nAgora inserindo dados via DictWriter: ") cabecalho = ['Título', 'Gênero', 'Duração'] escritor_csv = DictWriter(arquivo, fieldnames=cabecalho) # Passo a lista escritor_csv.writeheader() # Colomamos o header filme = None while filme != 'sair': # While is not 'sair' filme = input("Informe o nome do filme: ") if filme != 'sair': genero = input('Informe o genero: ') # input duracao = input("Informe a duração (em minutos): ") # input escritor_csv.writerow({"Título": filme, "Gênero": genero, "Duração": duracao}) # Write in the csv # Para escrever a linha utiliza o writerow igual anteriormente.
"""Decatorators com diferentes assinaturas. # Para situações de dois parametros quando se espera um, temos o uso de: Decorator pattern É a ideia de utilizar os *args e **kwargs nos parametros Permitindo essa flexibilidade Lembrando que args lançam uma tupla e kwargs um dicionário """ # Relembrando: def scream(funcao): def upper(nome): return funcao(nome).upper() return upper @scream def hey(nome: str): """Com o @ ali, executa o scream primeiro.""" return f'Olá, eu sou o {nome}' @scream def ordenar(principal: str, acompanhamento: str): return f'Gostaria de {principal} e {acompanhamento}' print(hey('Angelina')) # print(ordenar('picanha','batata frita')) # N funciona por conta de 2 args # Refatorando com o Decorator Pattern: def scream_pattern(funcao): """Agora podemos variar os parâmetros.""" def upper_pattern(*args, **kwargs): return funcao(*args, **kwargs).upper() return upper_pattern @scream_pattern def ordenar_pattern(principal: str, acompanhamento: str): """Pedido, agora podendo chamar o novo scream.""" return f'Gostaria de {principal} e {acompanhamento}' print(ordenar_pattern('picanha', 'batata frita')) print(ordenar_pattern(acompanhamento='picanha', principal='batata frita')) # Decorator function com argumentos: def verify_first_argument(value: str): def intern(funcao): def other(*args, **kwargs): if args and args[0] != value: return f"Incorreto! Primeiro argumento precisa ser {value}" return funcao(*args, **kwargs) return other return intern @verify_first_argument('pizza') # Implica que pizza precisa ser o 1º argumento def favorite_food(*args): print(args) print(favorite_food('lalala')) # Não aceita print(favorite_food('pizza', 'caldo de cana', 'lasanha')) # Aceita
''' Tipo Booleano, lá do George Boole 2 constantes: True e False Obs: sempre como inicial maiúscula ''' var1 = True var2 = False # Padrão: print (var1) # Negação: print(not var1) # Or (operação binária): print (var1 or var2) # Se um é verdadeiro, retorna True. Só retorna falso se ambos False # And (operação binária): print (var1 and var2) # Retorna verdadeiro se todos são verdadeiros. Caso contrário, retorna False #Exemplo de condicional usando os bool e as operações if var1 == True and var2 == True: print("Full ativo") elif var1 == True or var2 == True: print("Semi-ativo") else: print ("Desativado") #Retorno booleanos pelo print: print (5>6) print (2**4 < 14) print (65 == 5 * 13 or 123 == 234//2)
""" Named Tuples, o módulo collections Recap tupla: tupla = 1, 2, 3 É uma ideia de "tupla nomeada", são tuplas diferenciadas, em que especificamos um nome para a mesma e também parâmetros Fica bastante próximo de uma ideia de struct de C e tal, porém modificado no acesso Pois você define nome e todos os tipos dentro """ # Importando from collections import namedtuple # Definindo nome e parametros: # Forma 1 de declaração cachorro = namedtuple('cachorro', 'idade raca nome') # Forma 2 de declaração cachorro = namedtuple('cachorro', 'idade, raca, nome') # Forma 3 de declaração - melhor método cachorro = namedtuple('cachorro', ['idade', 'raca', 'nome']) # Usando: ray = cachorro(idade=2, raca='Chow Chow', nome='Ray') # Instanciando um cach. print(ray) # Acessando os dados # Forma 1 (ruim) print(ray[0]) # índice da idade # Forma 2 (melhor) print(ray.idade) print(ray.nome)
# analisando o crescimento da população brasileiro - datasus # Utilizando o arquivo .csv salvo na pasta # o arquivo csv atual está separado os dados por ";" import matplotlib.pyplot as plt dados = open("populacao_brasileira.csv").readlines() x = [] # armazena os anos y = [] # armazena a população for i in range(len(dados)): if i != 0: # ignora a primeira linha, cabeçalho linha = dados[i].split(";") x.append(int(linha[0])) # ano y.append(int(linha[1])) # população plt.bar(x, y, color="#04e4e4") plt.plot(x, y, color="k") plt.title ("Crescimento da população Brasileira 1980-2016") plt.xlabel("Ano") plt.ylabel("População (em milhões de pessoas)") plt.show() plt.savefig("populacao_brasileira.png", dpi=300)
#!/usr/bin/python print "Content-Type: text/html\n" f=open("lit.txt") r= f.read() f.close() print "<!DOCTYPE html>" print '''<html><head><title>Storify</title><style> body {background-size:100%}</style></head><body background = "https://media2.giphy.com/media/nYmXj4wLAgd7W/giphy.gif">''' print '''<a href="lit.txt">lit</a>''' print '<h1>Most Frequent Words</h1><table><tr><th>Word</th><th>Frequency</th>' blackmail=['to','i','we','has','have','was','can','be','he','the','of','a','in','it','that','she','is','for','but','and','him','her'] def context(text): newT = text[text.find("PRIDE"):] #finds the start of the story and splice it and removes everything before the story newT = newT[:newT.find("End of the Project Gutenberg EBook of Pride and")-1] #finds the end of the story and removes everything after the end return newT def wordonly(i): i = i.strip() #removes any extra spaces and new lines i = i.strip('".!,?:;') #removes the puncuation i = i.lower() #makes everything lowercase return i def instance(story):#our search function d={} L=(context(story)).split(" ") #takes the modify story and splits it into a list base on the spaces for i in L: i = wordonly(i) if i in d.keys(): d[i]+=1#if i is already in dictionary add to the number of occurences(<value>) in dictionary else: d[i]=1#if it is first occurence, add a new thing (i ) to dictionary return d def top30(r): d = instance(r) L=d.values() M=d.keys() counter=0 newstr='' while counter<30: if M[L.index(max(L))] in blackmail: M.pop(L.index(max(L))) #removes the largest variable to find the 2nd largest L.pop(L.index(max(L))) else: newstr+="<tr>"+"<td>"+M[L.index(max(L))]+"</td><td>"+str(max(L))+"</tr> \n" M.pop(L.index(max(L))) #removes the largest variable to find the 2nd largest L.pop(L.index(max(L))) counter+=1 return newstr print top30(r) print "</table>" print "</body> </html>"
class Node ( object ): def __init__ (self , v, n): self.value = v self.next = n class LinkedList ( object ): def __init__ ( self ): self.firstLink = None def add (self , newElement ): self.firstLink = Node ( newElement , self.firstLink ) def test (self , testValue ): currentLink = self.firstLink while currentLink != None: if currentLink.value == testValue: return True currentLink = currentLink.next return False def remove (self , testValue ): if not self.test(testValue): return False else: currentLink = self.firstLink previousLink = None while currentLink.value != testValue: previousLink = currentLink currentLink = currentLink.next if previousLink == None: self.firstLink = currentLink.next else: previousLink.next = currentLink.next del currentLink return True def len( self ): # return size of linked list length = 0 currentLink = self.firstLink while currentLink != None: length += 1 currentLink = currentLink.next return length def reverse ( self ): # return reverse linked list currentLink = self.firstLink previousLink = None postLink = self.firstLink while currentLink != None: postLink = currentLink.next currentLink.next = previousLink previousLink = currentLink currentLink=postLink self.firstLink = previousLink def Lprint ( self ): print('Current linked list: ',end="") currentLink = self.firstLink while currentLink != None: print("%d-->"%currentLink.value,end="") currentLink = currentLink.next print('none')
import math x1 = int(input('Enter x1--->')) y1 = int(input('Enter y1--->')) x2 = int(input('Enter x2--->')) y2 = int(input('Enter y2--->')) d1 = (x2-x1) * (x2-x1); d2 = (y2-y1) * (y2-y1); res = math.sqrt(d1+d2) print('Distance between two points:', res);
#Escribir un programa que pida al usuario un número entero positivo y muestre por pantalla la #cuenta atrás desde ese número hasta cero separados por comas. numero= int(input("Introduzca un numero entero positivo: \n")) while numero<0 : print("ERROR. Numero negativo") numero= int(input("Introduzca un numero entero positivo: \n")) for i in range(numero+1) : print(numero-i,end=",")
# Escribir un programa que guarde en una variable el diccionario {'Euro':'€', 'Dollar':'$', 'Yen':'¥'}, # pregunte al usuario por una divisa y muestre su símbolo o un mensaje de aviso si la divisa no está en el diccionario. diccionario= {'Euro':'€', 'Dollar':'$', 'Yen':'¥'} divisa= input("Introduce una divisa: ") print(diccionario.get(divisa.title(),"LA DIVISA INTRODUCIA NO FORMA PARTE DEL DICCIONARIO PREDEFINIDO"))
#Almacenar las matrices A(1 2 3) B(-1 0) # (4 5 6) ( 0 1) # ( 1 1) #en una lista y muestre por pantalla su producto. #Nota: Para representar matrices mediante listas usar listas anidadas, representando cada vector fila en una lista. # Las tuplas son como las listas pero se declaran con parentesis, no se pueden eliminar valores ni añadir etc.. tiempo de ejecucion menor a=((1, 2, 3), (4, 5, 6)) b=((-1, 0), (0, 1), (1,1)) c=[[0, 0], [0, 0]] for i in range(len(a)) : #de 0 a (numero de objetos en a)-1= 1 for j in range(len(b[0])) : #de 0 a (numero de objetos en el primer objeto de b)-1=2 for k in range(len(b)) : #de 0 a (numero de objetos en b)-1= 2 c[i][j] += a[i][k] * b[k][j] print("El resultado de la multiplicacion entre la matriz A y B representado por una LISTA es de: ") for i in range(len(c)) : print(c[i]) #Para convertir el resultado en otra TUPLA de manera que quede guardado e inmodificable, siguiente codigo for i in range(len(c)) : c[i]=tuple(c[i]) c=tuple(c) print("El resultado de la multiplicacion entre la matriz A y B representado por una TUPLA es de: ") for i in range(len(c)) : print(c[i]) print("\nNOTA: Las TUPLAS van entre PARENTESIS y las LISTAS van entre CORCHETES")
#Escribir un programa que almacene las asignaturas de un curso (por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista, #pregunte al usuario la nota que ha sacado en cada asignatura, y después las muestre por pantalla con el mensaje En <asignatura> has sacado <nota> #donde <asignatura> es cada una des las asignaturas de la lista y <nota> cada una de las correspondientes notas introducidas por el usuario. asignaturas= ["Matematicas", "Fisica", "Quimica", "Historia", "Informatica"] notas=[] for i in asignaturas : nota=float(input("Introduzca la nota de "+i+":")) notas.append(nota) print("") for i in range(len(notas)) : print("Tu nota en",str(asignaturas[i]),"es de",str(notas[i]))