text
stringlengths
37
1.41M
import random, time def print_guide_board(): print("7|8|9") print("-+-+-") print("4|5|6") print("-+-+-") print("1|2|3") def new_board(): board = {"upperLeft": " ", "upperMiddle": " ", "upperRight": " ", "midLeft": " ", "midMiddle": " ", "midRight": " ", "bottomLeft": " ", "bottomMiddle": " ", "bottomRight": " "} return board def set_letters(): while True: print("What letter do you want to be? X or O?", end=" ") letter = input().upper() if letter == "X": player_letter = "X" computer_letter = "O" break elif letter == "O": player_letter = "O" computer_letter = "X" break else: print("Please enter X or O.") return [player_letter, computer_letter] def first_move(): players = ["Player", "Computer"] turn = random.choice(players) return turn def print_board(current_board): print(current_board["upperLeft"] + "|" + current_board["upperMiddle"] + "|" + current_board["upperRight"]) print("-+-+-") print(current_board["midLeft"] + "|" + current_board["midMiddle"] + "|" + current_board["midRight"]) print("-+-+-") print(current_board["bottomLeft"] + "|" + current_board["bottomMiddle"] + "|" + current_board["bottomRight"]) def get_player_move(current_board): while True: decision = int(input()) if decision >= 1 and decision <= 9: if decision == 1: decision = "bottomLeft" elif decision == 2: decision = "bottomMiddle" elif decision == 3: decision = "bottomRight" elif decision == 4: decision = "midLeft" elif decision == 5: decision = "midMiddle" elif decision == 6: decision = "midRight" elif decision == 7: decision = "upperLeft" elif decision == 8: decision = "upperMiddle" elif decision == 9: decision = "upperRight" if current_board[decision] == " ": break else: print("Enter an empty space.") return decision def make_move(current_board, letter, move): current_board[move] = letter def is_winner(current_board, letter): # Top horizontal if current_board["upperLeft"] == letter and current_board["upperMiddle"] == letter and current_board["upperRight"] == letter: return True # Mid horizontal elif current_board["midLeft"] == letter and current_board["midMiddle"] == letter and current_board["midRight"] == letter: return True # Bottom horizontal elif current_board["bottomLeft"] == letter and current_board["bottomMiddle"] == letter and current_board["bottomRight"] == letter: return True # Left vertical elif current_board["upperLeft"] == letter and current_board["midLeft"] == letter and current_board["bottomLeft"] == letter: return True # Mid vertical elif current_board["upperMiddle"] == letter and current_board["midMiddle"] == letter and current_board["bottomMiddle"] == letter: return True # Right vertical elif current_board["upperRight"] == letter and current_board["midRight"] == letter and current_board["bottomRight"] == letter: return True # Cross 1 elif current_board["upperLeft"] == letter and current_board["midMiddle"] == letter and current_board["bottomRight"] == letter: return True # Cross 2 elif current_board["upperRight"] == letter and current_board["midMiddle"] == letter and current_board["bottomLeft"] == letter: return True else: return False def board_is_full(current_board): empty_spaces = 0 for value in current_board.values(): if value == " ": empty_spaces += 1 if empty_spaces == 0: return True else: return False def check_game(board, turn, letter): if is_winner(board, letter): print() print(f"{turn} wins!!") print() print_board(board) print() game_is_playing = False return [turn, False] else: if board_is_full(board): print() print("IT'S A TIE") print() print_board(board) print() game_is_playing = False return [turn, False] else: if turn == "Computer": turn = "Player" return ["Player", True] else: turn = "Computer" return ["Computer", True] def get_computer_move(current_board, letter): if letter == "X": player_let = "O" elif letter == "O": player_let = "X" # First try to make a winning move. copy_board = current_board.copy() for key in copy_board.keys(): if current_board[key] == " ": make_move(copy_board, letter, key) if is_winner(copy_board, letter): return key # Second, try to avoid loosing the game. copy_board = current_board.copy() for key in copy_board.keys(): if current_board[key] == " ": make_move(copy_board, player_let, key) if is_winner(copy_board, player_let): return key # Third, try to make one of the corners. corner_moves = ["upperLeft", "upperRight", "bottomLeft", "bottomRight"] possible_corner_moves = [] for corner in corner_moves: if copy_board[corner] == " ": possible_corner_moves.append(corner) if len(possible_corner_moves) > 0: choice = random.choice(possible_corner_moves) return choice # Fourth, try to make the center. if copy_board["midMiddle"] == " ": choice = "midMiddle" return choice # Fifth, try to make one of the sides. side_moves = ["upperMiddle", "midRight", "midLeft", "bottomMiddle"] possible_side_moves = [] for side in side_moves: if copy_board[side] == " ": possible_side_moves.append(side) if len(possible_side_moves) > 0: choice = random.choice(possible_side_moves) return choice def game(board, turn, player_letter, computer_letter): game_is_playing = True move_number = 1 print() print_board(board) while game_is_playing: time.sleep(1) print() # Player if turn == "Player": print(f"Move {move_number}: {turn}.", end=" ") player_move = get_player_move(board) make_move(board, player_letter, player_move) print_board(board) turn, game_is_playing = check_game(board, turn, player_letter) move_number += 1 # Computer else: print(f"Move {move_number}: {turn}.") computer_move = get_computer_move(board, computer_letter) make_move(board, computer_letter, computer_move) print_board(board) turn, game_is_playing = check_game(board, turn, computer_letter) move_number += 1 def play_again(): print("Do you want to play again? Y or N.", end=" ") while True: again = input().upper() if again == "Y" or again == "N": break else: print("Type Y or N.") continue if again == "Y": tic_tac_toe() else: print() print("Goodbye!") return False def tic_tac_toe(): while True: print() time.sleep(0.5) print_guide_board() print() board = new_board() player_letter, computer_letter = set_letters() turn = first_move() game(board, turn, player_letter, computer_letter) if not play_again(): break # Program print("TIC TAC TOE!") tic_tac_toe()
#!/usr/bin/python # -*- coding: utf-8 -*- dp = {} a = 0 def find_num(n,nums): global dp global a if int(nums[0:n] ) > 26: return 0 if int(nums) < 10: return 1 if nums[n:] == "": num = 0 else: num = int(nums[n:]) if num < 10: return 1 if nums[n:] not in dp: dp[nums[n:]] = find_num(1,nums[n:])+find_num(2,nums[n:]) return dp[nums[n:]] str= "222222226" print(find_num(1,str)+find_num(2,str)) print(dp)
#快速排序算法,快排算法需要注意的是比较基准数大小需要送右边开始比较!!! import time import random #arr = [5,12,6,25,34,15,8,9,7,2,31,22,74] arr = [] for i in range(0,999): arr.append(random.randrange(1 , round(time.time()/100),1)) def quicksort(left,right): if left > right: return a = arr[left] i = left j = right while i != j: while arr[j] >= a and i < j: j = j-1 while arr[i] <= a and i < j: i = i+1 if i < j: t = arr[i] arr[i] = arr[j] arr[j] = t arr[left] = arr[i] arr[i] = a quicksort(left,i-1) quicksort(i+1,right) quicksort(0,998) print (arr)
#!/usr/bin/env python # -*- coding: utf-8 -*- class DICTIONARY(): def __init__(self): self.data = [] self.data_dict = {} self.read_dictionary("dictionary.txt") self.create_dict() def read_dictionary(self, dictionary_name): # 辞書の読み込み dict_data_tmp = open(dictionary_name, "r") for line in dict_data_tmp: self.data.append(line) dict_data_tmp.close() def create_dict(self): # separate by number of chars of a word # ex. "rabbit" enters data_dict[6] self.data_dict[2] = [] self.data_dict[3] = [] self.data_dict[4] = [] self.data_dict[5] = [] self.data_dict[6] = [] self.data_dict[7] = [] self.data_dict[8] = [] self.data_dict[9] = [] self.data_dict[10] = [] self.data_dict[11] = [] self.data_dict[12] = [] self.data_dict[13] = [] self.data_dict[14] = [] self.data_dict[15] = [] self.data_dict[16] = [] self.data_dict[17] = [] self.data_dict[18] = [] for word in self.data: # 単語の分割.文字を一つずつ取り出してリストに入れる chars = list(word.lower()) # ex. chars: ['b', 'l', 'a', 'd', 'e', 's', '\n'] need to delete \n chars[len(chars)-1:]=[] self.data_dict[len(chars)].append(chars) ''' 入力文字列 s_p に 辞書の単語 tag_p の各文字が含まれているかを調べる関数 ''' def find_common_char(tag_p, s_p): tag_p_cp = tag_p[:] s_p_cp = s_p[:] found_list = [] count = 0 # len(tag_p_cp) =< len(s_cp_p) がこのプログラムでは常に成り立つので,tag_cp_pが先に空になる while tag_p_cp!=[]: count = 0 for s in range(len(s_p_cp)): count +=1 if tag_p_cp[0] == s_p_cp[s]: found_list.append(tag_p_cp[0]) del tag_p_cp[0] del s_p_cp[s] break if count == len(s_p_cp): del tag_p_cp[0] break return found_list ''' s: 入力文字列 (ゲームで与えられる文字の列) count: sの長さ dictionary.data_dict: 辞書の単語をアルファベット順ではなく,文字の長さで分けたもの(辞書) dictionary.data_dict[i][word_count]: iは文字の長さ(2-18にした),word_countはそのうち何番目か ex. dictionary.data_dict[12][0] => ['a', 'f', 'r', 'o', 'c', 'e', 'n', 't', 'r', 'i', 's', 'm'] intersection: s とdictionary.data_dict[i][word_count] で被っている文字のリスト ex. s: ['m', 'o', 'o', 'n'] と dictionary.data_dict[i][word_count]: ['m', 'o', 'o', 'o', 'm'] なら,['m', 'o', 'o'] candidate: sを元に出来た単語の文字列リスト(最高点計算用) ex. [['m', 'o', 'o', 'n'], [...], [...]] candidate_tag: sを元に出来た単語の文字列リスト(最終結果表示用) ex. ['moon', '...', '...'] point: candidateそれぞれの得点(正確な計算ではないが十分な計算) max_idx: 最高点を出すcandidateのインデックス ''' if __name__ == '__main__': dictionary = DICTIONARY() # 終了はCtrl+cで行う while True: # 文字の入力 s = raw_input("Enter alphabets: ") # sのアルファベットを全て小文字にして,リストに一つずつ入れる s = list(s.lower()) count = len(s) candidate = [] candidate_tag = [] # 辞書の中の文字数が多いものから検索 for i in range(count, 1, -1): for word_count in range(len(dictionary.data_dict[i])): # 辞書の単語の文字が 入力文字列に含まれているか調べる # 含まれている文字をリストに入れていく intersection = find_common_char(dictionary.data_dict[i][word_count], s) # もし上で出来たリストと辞書の単語のリストの長さが一緒なら,文字が全部含まれていることになる if len(intersection) > 0 and len(intersection) == len(dictionary.data_dict[i][word_count]): # candidate: 最高点計算用の文字列リスト # ex. [['m', 'o', 'o', 'n'], [...], [...]] candidate.append(intersection) # candidate_tag: 最終結果表示用の文字列リスト # ex. ['moon', '...', '...'] candidate_tag.append(''.join(dictionary.data_dict[i][word_count])) # candidateから点数の高いものを選ぶ point = [] for word in candidate: tmp = 0 for s in word: if s == 'j' or s == 'k' or s == 'q' or s == 'x' or s == 'z': tmp+=3 elif s == 'c' or s == 'f' or s == 'h' or s == 'l' or s == 'm' or s == 'p' or s == 'v' or s == 'w' or s == 'y': tmp+=2 else: tmp+=1 point.append(tmp) if len(point) > 0: max_idx = point.index(max(point)) print ("I found: {} {}").format(candidate_tag[max_idx], max(point)) else: print "PASS"
###QUESTION 2### usersInt = (int(input("Give me an integer: "))) def factorial(n): """Function to work out the factorial of a number""" i = 1 while n >= 1: # Keep looping while int being used is above or equal to 1, factorials do not get multiplied by 0 i = i * n # The multiplication of 'i' with the iteratively reduced 'n' the main calculation with factorials n = n - 1 # N - 1 so that the factorial can proceed down the next multiplication level return i # Returning the i integer which holds the final result of the calculations, the factorial of the given int def trailingZeros(n): """Function to count the number of trailing zeros in a number""" counter = 0 # Setting the counter for number of 0s found within the number in a variable while n % 10 == 0: # While the number can receive no remainder on a mathematical division by 10 n = n / 10 # Dividing the factorial number by 10 counter = counter + 1 # Keeping track of the number of times that it has been divided return counter # Returning the total times the given number has been divided by returning the counter variable factorialNumber = factorial(usersInt) trailing = trailingZeros(factorialNumber) print("The Factorial number is: " + str(factorialNumber)) #print(factorialNumber) print("The number of trailing zeros is: " + str(trailing)) """Description""" """This is a program to count the number of trailing zeros from a factorial number. I decided to use 2 functions to split up the calculations. The first function works out the factorial of a given number. This is calculated using an iterative method of multiplying the given integer against an integer of the same value, then each time the loop is run, deducting 1 from the latter. This returns the factorial of a number. The second function takes the factorial and using the modulus operator iteratively divides by 10 till it cant without resulting in a remainder. A counter is ran within the loop and is then returned at the end. This counter is the indication of how many trailing 0s are present in the factorial number.""" """Big O Notation""" """The Big O notation is 0(n)"""
""" price is an array of price with the length = (index+1) and the correspoding price is the value in the array n is the length of rod """ def cut_a_rod(price, n): if n <= 0: return 0 result = 0 for i in xrange(n): result = max(result, price[i] + cut_a_rod(price, n - i - 1)) return result def cut_a_rod2(price, n): if n <= 0 : return 0 dp = [0 for x in xrange(n+1)] for i in xrange(1,n+1): m = 0 for j in xrange(0, i): m = max(m, dp[i-j-1]+price[j]) dp[i] = m return dp[n] print cut_a_rod([1, 5, 8, 9, 10, 17, 17, 20], 8) print cut_a_rod2([1, 5, 8, 9, 10, 17, 17, 20], 8)
""" Given a collection of integers that might contain duplicates, nums, return all possible subsets. """ def subsetWithDup(nums): result = [[]] nums.sort() for i in xrange(len(nums)): if i == 0 or nums[i] != nums[i-1]: l = len(result) for j in xrange(len(result) - l , len(result)): result.append(result[j] + [nums[i]]) return result print subsetWithDup([1,2,2,3])
#!/usr/bin/env python # coding: utf-8 import requests import pandas as pd from time import sleep from datetime import datetime import sqlite3 ''' Created by: Pavithra Coimbatore Sainath Date: 15th Apr 2021 ''' ''' This function returns the date range for the given start and end dates This will be used to generate the list of timestamps for the given dates ''' CAR_PARK_URL = 'https://api.data.gov.sg/v1/transport/carpark-availability' def get_date_range(start_date, end_date): datelist = [str(i).replace(' ', 'T') for i in pd.date_range(start=start_date, end=end_date, freq="15min")] return datelist ''' This function returns the json response for the given url with its parameters ''' def get_response(url, param, timeout=60): response = requests.get(url, params=param) if response.status_code != 200: sleep(10) return get_response(url, param) else: res_json = response.json() return res_json ''' This function normalizes the data and transforms the data into a dataframe format ''' def normalize(timestamp, response): for t in response['items']: df = pd.DataFrame.from_dict( pd.json_normalize(t['carpark_data'], 'carpark_info', ['carpark_number', 'update_datetime'])) df['timestamp'] = timestamp return df ''' This function used to create database table and insert the data to the database The table is created only if is not already available ''' def write_to_db(dataframe): if not dataframe is None: try: db = sqlite3.connect('Carpark_15min') cursor = db.cursor() cursor.execute('''create table if not exists carpark_availability_15min (total_lots varchar(20),lot_type varchar(5), lots_available varchar(10),carpark_number varchar(20),update_datetime datetime,timestamp datetime, PRIMARY KEY (carpark_number,lot_type,timestamp))''') except Exception as E: print('Error :', E) else: print('table created or updated') try: dataframe.to_sql(name='carpark_availability_15min', con=db, if_exists='append', index=False) except Exception as E: print('Error : ', E) db.commit() print('data inserted') else: print('Empty DF') ''' Configured 60 seconds sleep as throttling in the api.data.gov.sg imposes rate limiting ''' if __name__ == "__main__": start_dt = input('Enter start date').replace('/', '-') end_dt = input('Enter end date').replace('/', '-') if datetime.strptime(start_dt, '%Y-%m-%d') > datetime.strptime(end_dt, '%Y-%m-%d'): print('Please enter a valid start and end date. End date should be larger than the start date.') else: date_list = get_date_range(start_dt, end_dt) for date in date_list: PARAM = {'date_time': date} response_data = get_response(CAR_PARK_URL, PARAM) write_to_db(normalize(date, response_data)) sleep(60)
#!/usr/bin/env python # # Copyright (c) 2015 # Massachusetts Institute of Technology # # All Rights Reserved # """ Authors: Kelly Geyer Installation: Python 2.7 on Windows 7 File: pyTweet.py Installation: Python 2.7 on Windows 7 Author: Kelly Geyer Date: June 24, 2015 Description: This script is an example of using pyTweet to create a Twitter dataset with breadth first sampling. """ import pyTweet, os, datetime def main(): # PARAMETERS # Enter proxy host and port information host = 'your.host' port = 'your.port' # Beginning dates of time lines that you plan to collect. These timelines will range from the start_date to the current date start_date = datetime.date(year=2015, month=3, day=1) # Set locations for the profile and timeline directory to save .JSONs. The default will be your current working # directory. save_dir = {'twitter_profiles': '', 'twitter_timelines': ''} # SAMPLING OPTIONS # Specify your graph constrains with the variable hop_out_limits. First determine the maximum number of hops to make # the graph with 'max_hops', then decide the maximum amount of data to collect in 'max_data'. This will be the # combined profile and timeline .JSON files. Set it to 'None' if you don't want to limit the amount of data # collected. Next, Set limits (per individual) on how many friends, followers, replied to users, and mentioned # users to include on the next hop. You can specify values [0, Inf) or None. Specifying 'None' implies that you do # not wish to limit the collection, and will expand the graph on as many as these edges as possible. Occasionlly, # you may get back fewer edges for a user than the limit you set. Note that friends and followers will be saved in # the fields 'friends_list' and 'followers_list' automatically. The reply and mention users are saved in timelines. hop_out_limits = {'max_hops': 5, # Maximin number of hops in graph 'max_data': 10, # Maximum amount of data (in GB) 'friends': None, # Maximum friends per user to include in next hop 'followers': None, # Maximum followers per user to include in next hop 'in_reply_to_user_id': 1, # Maximum 'in_reply_to_user_id' per user's timeline to include in next hop 'user_mention_id': 1} # Maximum 'user_mention_id' per user's timeline to include in next hop # Suppose that you want to store friends or followers, but do not want to expand the graph based on them. Specify # limitations on collecting friends and followers below. Notice that reply and mention users are saved in the # timelines. The largest possible length of 'friends_list' will be the greater of hops out limit and collection # limit, or MAX(hops_out_limit['friends'], collection_limits['friends']). The same description follows for # 'followers_list'. collection_limits = {'friends': None, # Maximum number of friends per user to save within the profile .JSON 'followers': 200} # Maximum number of followers per user to save within the profile .JSON # Load your seed of Twitter handles into the list username_seed below. It's not necessary to include the '@' username_seed = ['user1', 'user2', 'user3'] # BUILD NETWORK print "\nBuild network and get user information" pyTweet.breadth_first_search(user_seed=username_seed, timeline_start_date=start_date, host=host, port=port, save_dir=save_dir, hop_out_limits=hop_out_limits, collection_limits=collection_limits) if __name__ == '__main__': main()
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' def sliding_window_max(nums, k): arr = nums return_arr = [] n = len(arr) beg = 0 end = beg + k while end <= n: current_arr = arr[beg:end] return_arr.append(max(current_arr)) beg += 1 end += 1 return return_arr if __name__ == '__main__': # Use the main function here to test out your implementation arr = [70, 37, 100, 66, 1, 45, 27, 62, 75, 57, 92, 66, 9, 39, 15, 69, 46, 72, 35, 68, 54, 51, 35, 36, 13, 27, 27, 24, 6, 33, 83, 97, 55, 5, 25, 85, 56, 4, 100, 38, 38, 83, 29, 1, 11, 27, 64, 99, 64, 29, 41, 95, 59, 46, 75, 67, 40, 49, 62, 30, 56, 88, 71, 77, 43, 79, 27, 65, 24, 18, 74, 50, 23, 47, 45, 60, 62, 84, 53, 2, 90, 29, 99, 75, 59, 44, 71, 7, 59, 59, 27, 72, 6, 89, 90, 40, 51, 45, 43, 86] k = 5 print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
import heapq import sys import math input = sys.stdin.readline def getLength(a, b): x1, y1 = a x2, y2 = b return math.sqrt(((x1 - x2) ** 2 + (y1 - y2) ** 2)) def findParent(x): if x == parent[x]: return x return findParent(parent[x]) def union(x, y): x = findParent(x) y = findParent(y) if x == y: return False elif x < y: parent[y] = x else: parent[x] = y return True n, m = map(int, input().split()) coord = [] for _ in range(n): x, y = map(int, input().split()) coord.append((x, y)) arr = [] for i in range(n): for j in range(i + 1, n): arr.append((getLength(coord[i], coord[j]), i + 1, j + 1)) parent = {} for i in range(1, n + 1): parent[i] = i for _ in range(m): x, y = map(int, input().split()) union(x, y) result = 0 arr.sort(key=lambda x: x[0]) for length, x, y in arr: if union(x, y): result += length print("%0.2f" % result)
import folium import pandas #Loads data from Volcanoes.txt into a DataFrame data = pandas.read_csv("UdemyCourse\WebMap\Volcanoes.txt") #Creates lat, long, elev, and name lists from the data frame lat = list(data["LAT"]) lon = list(data["LON"]) elev = list(data["ELEV"]) name = list(data["NAME"]) #Changes color of the icon based on the elevation of the volcano def colorPicker(elevation): if elevation < 1000: return 'green' elif 1000 <= elevation < 3000: return 'orange' else: return 'red' #HTML to be used to perform a google search on the volcano name html = """ Volcano name:<br> <a href="https://www.google.com/search?q=%%22%s%%22" target="_blank">%s</a><br> Height: %s m """ #Location is based off longitude/latitude coordinates map = folium.Map(location=[42.3601, -71.0589], zoom_start=10, tiles="Stamen Terrain") #Creates a feature group for the volcano data fgv = folium.FeatureGroup(name="Volcano Map") #Creates a feature group for the popuilation data fgp = folium.FeatureGroup(name="Population") #Adds markers to the feature group for lt, ln, el, name in zip(lat, lon, elev, name): iframe = folium.IFrame(html = html % (name, name, el), width = 200, height = 100) fgv.add_child(folium.CircleMarker(location=[lt, ln], radius=5, popup=folium.Popup(iframe), fill_color = colorPicker(el), color = 'grey', fill_opacity = 0.7)) #Adds and colors polygons for different countries based on their populations fgp.add_child(folium.GeoJson(data=open('UdemyCourse\WebMap\world.json', 'r', encoding='utf-8-sig').read(), style_function = lambda x: {'fillColor':'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'})) #Adds the feature groups to the map map.add_child(fgv) map.add_child(fgp) #Adds layer control feature to the map map.add_child(folium.LayerControl()) #Creates the map file map.save("Map1.html")
def computepay(h, r): if h <= 40 : return h*r else : return (40*r + (h-40)*r) hours = float(input("Enter hours:")) rate = float(input("Enter rate :")) pay = computepay(hours, rate) print("Pay", pay)
# 多重判断 ''' if 条件1: 条件1成立执行的代码1 ... elif 条件2: 条件成立执行的代码2 ... else: 以上条件都不成立执行的代码3 ... ''' age=int(input('请输入你的年龄:')) # 童工 if age < 18: print(f'你的年龄是{age}岁,为童工,不合法') # 18-60 合法 elif 18 <= age <=60: #化简得来的 print(f'你的年龄是{age}岁,为合法工作年龄') # 大于60退休 else: print(f'你的年龄是{age}岁,为退休年龄')
#集合 --可变类型 #创建集合 --使用set()或{},但是空集合只能使用set(),因为空子典占用了{} #集合内没用重复数据,可以去重 #1.创建有数据的集合 s1 = {10,20,30,40,50,60,70} print(s1) #集合没有顺序,不支持下标查找 s2 = {1,1,2,3,4,4,5} print(s2) #去重功能 s3 = set('fdsafd123') #set()创建集合,其中不能有int类型数据,而且只能有一个字符串 print(s3) #2.创建空集合:set() s4 = set() #空集合 print(s4) #set() print(type(s4)) s5 = {} #空子典 print(type(s5))
# while语法 ''' while 条件: 条件成立重复执行的代码1 条件成立重复执行的代码2 ... ''' # 需求:重复打印10次 i = 1 while i <= 10: print('巴拉') i+=1 print("游戏结束") ''' # 计数器习惯写法 i = 0 #计算机计数习惯性从0开始 while i < 5 : #总计还是5次(0,1,2,3,4) '''
#认识字符串 # 单引号 a = 'hello' #单引号不支持回车换行 print(a) print(type(a)) b = "TOM" print(type(b)) # 三引号 e = '''i am TOM''' print(type(e)) f = """I am TOM""" # 三引号支持回车换行 print(type(f)) print(f) #I`m TOM c = "I'm TOM" q = 'i\'m TOM' #加上转义符号 print(c) print(q) #字符串输出 name = 'Tom' print('我的名字是%s'%name) print(f'我的名字是{name}') #字符串输入 #input() 接受用户输入 输入的任何类型数据都会转变成字符串类型数据 password = input('请输入您的密码:') print(f'您输入的密码是:{password}') print(type(password))
import speech_recognition as sr import pyttsx3 import datetime import wikipedia import webbrowser import os engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) def speak(audio): engine.say(audio) engine.runAndWait() # Without runAndwait command, speech will not be audible to us. def wishMe(): hour = int(datetime.datetime.now().hour) if hour >= 0 and hour < 12: speak("subho sokal , moharaj") elif hour >= 12 and hour < 17: speak(" subho dupur , moharaj") else: speak("subho sondha , moharaj") speak("ami vidhura , ami upnar ki seba korte pari? ") def takeCommand(): # It takes microphone input from the user and returns string output r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source) try: print("Recognizing...") # Using google for voice recognition. query = r.recognize_google(audio, language='en-in') print(f"Lord said : {query}\n") # User query will be printed. except Exception as e: print("Say that again please...") return "None" # None string will be returned return query if __name__ == "__main__": wishMe() while True: query = takeCommand().lower() #Converting user query into lower case # Logic for executing tasks based on query if'exit' in query: speak("Thank you very much sir , wish your day is fantabulous!") exit() elif'quit' in query: speak("Thank you very much sir , wish your day is fantabulous!") exit() elif 'wikipedia' in query: #if wikipedia found in the query then this block will be executed speak('Searching Wikipedia...') query = query.replace("wikipedia", "") results = wikipedia.summary(query, sentences = 2) speak("According to Wikipedia") print(results) speak(results) elif 'youtube' in query: speak("opening youtube in your web browser") webbrowser.open("Youtube.com") elif 'google' in query: speak("opening google in your web browser") webbrowser.open("google.com") elif 'open music' in query: speak("Opening your awesome music files!") music_dir = 'E:\\code\\python\\vidura' songs = os.listdir(music_dir) print(songs) os.startfile(os.path.join(music_dir, songs[0])) elif 'time' in query: strTime = datetime.datetime.now().strftime("%H:%M:%S") speak(f"Sir, the time is {strTime}")
def shellSort(arr, N): count = 0 interval = N / 2 while interval > 0: for i in range(interval, N): count += 1 temp = arr[i] j = i while j >= interval and arr[j - interval] > temp: arr[j] = arr[j - interval] j -= interval arr[j] = temp interval /= 2 print("Final Count: " + str(count)) return arr arr1 = [10, 2, 3, 4, 1, 5, 7, 6, 8, 9] arr2 = [1, 2, 2, 4, 1, 5, 2, 8, 8, 2] arr3 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] print(shellSort(arr1, len(arr1))) print(shellSort(arr2, len(arr2))) print(shellSort(arr3, len(arr3)))
#!/usr/bin/env python # coding: utf-8 # In[2]: #Assignment #Spider Game #Importing random library import random #Creating variables for each player playerx1 = ["","","","","","","","","",""] playerx2 = ["","","","","","","","","",""] playerx3 = ["","","","","","","","","",""] playerx4 = ["","","","","","","","","",""] #Greeting the user print("Welcome to the game! ") print("How many players do u want? (2-4)") player = int(input()) #Display function def display(lst): for char in lst: if char in "//\(OO)/\\": print(char, end = ' ') #Creating main function for the spider game def spider(player1, player2, player3, player4): #Describing the rules to the user print("Each player will be given a chance to throw a dice and whoever complete the spider first will win! ") i = 0 k = 0 j = 0 l = 0 #A loop for providing the condition while (True): x = random.randint(1,6) y = random.randint(1,6) a = random.randint(1,6) b = random.randint(1,6) #Parameters for creating the spider #For First Player #For spider's body if (x==6): if (player1[3] != "("): player1[3] = "(" else: player1[6] = ")" #For spider's eyes if (x == 1): if player1[3] == "(" and player1[6] == ")": if (player1[4] != "O"): player1[4] = "O" else: player1[5] = "O" #For spider's legs if (x == 4 or x == 3): if player1[3] == "(" and player1[6] == ")": if (player1[0] != "/"): player1[0] = "/" elif (player1[1] != "/"): player1[1] = "/" elif (player1[2] != "\\"): player1[2] = "\\" elif (player1[7] != "/"): player1[7] = "/" elif (player1[8] != "\\"): player1[8] = "\\" elif (player1[9] != "\\"): player1[9] = "\\" #For increment i += 1 #Printing out the status of first player ch = '' ch = ch.join(playerx1) print('Player 01 Status:',ch) if (player1[0] == "/" and player1[1] == "/" and player1[2] == "\\" and player1[3] == "(" and player1[4] == "O" and player1[5] == "O" and player1[6] == ")" and player1[7] == "/" and player1[8] == "\\" and player1[9] == "\\"): #First player winning message print("Player 01 won in "+str(i)+" tries! ") print(r"//\(OO)/\\") break #For Second Player if (y == 6): if (player2[3] != "("): player2[3] = "(" else: player2[6] = ")" if (y == 1): if player2[3] == "(" and player2[6] == ")": if (player2[4] != "O"): player2[4] = "O" else: player2[5] = "O" if (y == 4 or y == 3): if player2[3] == "(" and player2[6] == ")": if (player2[0] != "/"): player2[0] = "/" elif (player2[1] != "/"): player2[1] = "/" elif (player2[2] != "\\"): player2[2] = "\\" elif (player2[7] != "/"): player2[7] = "/" elif (player2[8] != "\\"): player2[8] = "\\" elif (player2[9] != "\\"): player2[9] = "\\" #Status for second player ch1 = '' ch1 = ch1.join(player2) print("Player 02 Status: ",ch1) k += 1 if (player2[0] == "/" and player2[1] == "/" and player2[2] == "\\" and player2[3] == "(" and player2[4] == "O" and player2[5] == "O" and player2[6] == ")" and player2[7] == "/" and player2[8] == "\\" and player2[9] == "\\"): #Second player winning message print("Player 02 won in ",k," tries! ") print(r"//\(OO)/\\") break #For Third Player if (a == 6): if (player3[3] != "("): player3[3] = "(" else: player3[6] = ")" if (a == 1): if player3[3] == "(" and player3[6] == ")": if (player3[4] != "O"): player3[4] = "O" else: player3[5] = "O" if (a == 4 or a == 3): if player3[3] == "(" and player3[6] == ")": if (player3[0] != "/"): player3[0] = "/" elif (player3[1] != "/"): player3[1] = "/" elif (player3[2] != "\\"): player3[2] = "\\" elif (player3[7] != "/"): player3[7] = "/" elif (player3[8] != "\\"): player3[8] = "\\" elif (player3[9] != "\\"): player3[9] = "\\" if (player == 3 or player == 4): ch2 = '' ch2 = ch2.join(player3) print("Player 03 Status: " ,ch2) #Variable for increment j += 1 if (player3[0] == "/" and player3[1] == "/" and player3[2] == "\\" and player3[3] == "(" and player3[4] == "O" and player3[5] == "O" and player3[6] == ")" and player3[7] == "/" and player3[8] == "\\" and player3[9] == "\\"): #Third player's winning message print("Player 03 won in ",j," tries! ") print(r"//\(OO)/\\") break #For Forth Player if (b == 6): if (player4[3] != "("): player4[3] = "(" else: player4[6] = ")" if(b == 1): if player4[3] == "(" and player4[6] == ")": if (player4[4] != "O"): player4[4] = "O" else: player4[5] = "O" if (b == 4 or b == 3): if player4[3] == "(" and player4[6] == ")": if (player4[0] != "/"): player4[0] = "/" elif (player4[1] != "/"): player4[1] = "/" elif (player4[2] != "\\"): player4[2] = "\\" elif (player4[7] != "/"): player4[7] = "/" elif (player4[8] != "\\"): player4[8] = "\\" elif (player4[9] != "\\"): player4[9] = "\\" if (player == 4): #printing out fourth player's status ch3 = '' ch3 = ch3.join(player4) print("Player 04 status: " ,ch3) l += 1 if (player4[0] == "/" and player4[1] == "/" and player4[2] == "\\" and player4[3] == "(" and player4[4] == "O" and player4[5] == "O" and player4[6] == ")" and player4[7] == "/" and player4[8] == "\\" and player4[9] == "\\"): #Printing fourth player's winning message print("Player 04 won in ",l," tries! ") print(r"//\(OO)/\\") break #Calling spider() function spider(playerx1, playerx2, playerx3, playerx4) #Loop for asking the user to restart the game while(True): print("Do you want to play again? (y,n)") i = input() #If the user wants to play again if (i == "y"): player = int(input('How many players are there? ')) playerx1 = ["","","","","","","","","",""] playerx2 = ["","","","","","","","","",""] playerx3 = ["","","","","","","","","",""] playerx4 = ["","","","","","","","","",""] spider(playerx1,playerx2,playerx3,playerx4) else: print("Bye!") break # In[ ]:
# this file deletes a row of data to the table import sqlite3 def main(): deleteRow() def deleteRow(): # this names the database dog_file = 'Dog_Database.sqlite' # this names the table dog_table = 'Dog_Table' #this points to the dog name which we will use to delete by dogName = "Doggo_Name" # Connecting to the database file conn = sqlite3.connect(dog_file) c = conn.cursor() try: # gets User input userDelete = input("Type the name of the Doggo you want to delete: ") #delete one entry from table c.execute('DELETE FROM {tn} WHERE {cn}={user}'.format(tn=dog_table, cn=dogName,user=userDelete)) print(dogName + "has been deleted from the table!") except sqlite3.Error: print("Cannot delete that dog at this time. Please try again!") # commit changes made conn.commit() # close the DB connection conn.close() # main()
""" Public and Private decorators. Public decorator allows to get and set only attributes that were passed to them during decoration. Example: @public('data', 'size') - set and get operations will work only for 'data' and 'size' attributes. All other attributes (if any) are private and cannot be gotten and set. Private decorator works vice versa. Example: @private('data', 'size') - set and get operations will prohibited for attributes 'data' and 'size'. All other attributes (if any) are public and can be gotten and set. P.S. Run this file with -O key to prevent decoration: #>>> python3 -O public_private_dec.py """ trace = False def tracer(*args): if trace: print('[' + ' '.join(map(str, args)) + ']') def accessControl(failif): def onDecorator(aClass): if not __debug__: return aClass else: class OnInstance: def __init__(self, *args, **kwargs): self.__wrapped = aClass(*args, **kwargs) def __getattr__(self, attr): tracer('get:', attr) if failif(attr): raise TypeError('private attribute fetch ' + attr) else: return getattr(self.__wrapped, attr) def __setattr__(self, attr, value): tracer('set:', attr, value) if attr == '_OnInstance__wrapped': self.__dict__[attr] = value elif failif(attr): raise TypeError('private attribute change ' + attr) else: setattr(self.__wrapped, attr, value) return OnInstance return onDecorator def private(*attributes): return accessControl(failif=lambda attr: attr in attributes) def public(*attributes): return accessControl(failif=lambda attr: attr not in attributes) if __name__ == '__main__': trace = True @private('data', 'size') class Doubler: def __init__(self, label, start): self.label = label self.data = start def size(self): return len(self.data) def double(self): for i in range(self.size()): self.data[i] = self.data[i] * 2 def display(self): print('{0} => {1}'.format(self.label, self.data)) x = Doubler('x is', [1, 2, 3]) y = Doubler('y is', [-10, -20, -30]) print(x.label) x.display(); x.double(); x.display() print(y.label) y.display(); y.double() y.label = 'Spam' y.display() print(x.size()) # This part will raise exceptions for @private decorator ''' print(x.size()) print(x.data) x.data = [1, 1, 1] x.size = lambda s: 0 print(y.data) print(y.size()) '''
from auxiliary import * def insertion_sort(arr, verbose=False): for sort_len in range(1, len(arr)): cur_item = arr[sort_len] if verbose: print('Cur item:', cur_item) insert_index = sort_len while insert_index > 0 and cur_item < arr[insert_index - 1]: arr[insert_index] = arr[insert_index - 1] insert_index -= 1 arr[insert_index] = cur_item if verbose: print('Insert ind:', insert_index) print('Arr:', arr) return arr if __name__ == '__main__': run(insertion_sort, True) compare(insertion_sort, 'Insertion Sort')
import smtplib import email.utils import sys import mailconfig import getpass mailserver = mailconfig.smtpservername From = input('From: ').strip() To = input('To: ').strip() Tos = To.split(';') Subj = input('Subject: ').strip() Date = email.utils.formatdate() text = 'From: {0}\nTo: {1}\nDate: {2}\nSubject: {3}\n\n'.format(From, To, Date, Subj) """ Uncomment the string below and comment the previous one. Then type "To: fakeaddr" followed by an empty string in the message body. As result: fakeaddr will be in the "To:" field, but the message will be sent to the real recipient """ # text = 'From: {0}\nDate: {1}\nSubject: {2}\n'.format(From, Date, Subj) print('Type message text, end with line=[Ctrl+d (Unix), Ctrl+z (Windows)]') while True: line = sys.stdin.readline() if not line: break # Exit (Ctrl+d/z) text += line print('Connecting...') server = smtplib.SMTP(mailserver) #server.login(mailconfig.smtpusername, getpass.getpass('Password:')) # If authentication required failed = server.sendmail(From, Tos, text) server.quit() if failed: print('Failed recipients:', failed) else: print('No errors') print('Bye.')
"""exercicio036.py em 2018-10-09. Projeto Practice Python. No exercício anterior, contamos quantos aniversários há em cada mês em nosso dicionário de aniversários. Neste exercício, use a biblioteca Python bokeh para traçar um histograma em que meses os cientistas têm aniversários! Como levaria muito tempo para você inserir os meses de vários cientistas, você pode usar meu arquivo JSON de aniversário dos cientistas. Basta analisar os meses (se você não sabe como, sugiro olhar para o exercício anterior ou sua solução) e desenhar seu histograma. Se você estiver usando uma interface puramente baseada na Web para codificação, este exercício não funcionará para você, pois é necessário instalar o pacote bokeh Python. Agora pode ser uma boa hora para instalar o Python em seu próprio computador. """ import json from bokeh.plotting import figure, show, output_file from collections import Counter from cicero import cabecalho def plot(): """Faz plotagem dos dados do arquivo Json """ # lê o arquivo Json e armazena em um dicionário with open('json/cientistas.json', 'r') as f: cientistas = json.load(f) lista = [] x = [] y = [] # carrega somente os meses para uma lista for v in cientistas.values(): lista.append(str(v).split(' ')[2]) # cria listas para plotagem dos meses e ocorrências for k, v in Counter(lista).items(): x.append(k) y.append(v) y = sorted(y, reverse=True) # cria a plotagem output_file('html/aniversarios.html') x_categories = list(Counter(lista)) p = figure(x_range=x_categories) p.vbar(x=x, top=y, width=0.5) show(p) if __name__ == '__main__': cabecalho('Aniversários') plot()
"""exercicio012.py em 2018-09-30. Projeto Practice Python. Escreva um programa que tenha uma lista de números (por exemplo, a = [5, 10, 15, 20, 25]) e faça uma nova lista apenas com o primeiro e o último elemento da lista dada. Para praticar, escreva este código dentro de uma função. """ from cicero import cabecalho def extremos_lista(lista: list) -> list: """retorna uma lista com o primeiro e o último elemento :param lista: uma lista :type lista: list :return: lista com com os dois itens :rtype: list """ return [lista[0], lista[-1]] if __name__ == '__main__': cabecalho('Fim da lista') a = [5, 10, 15, 20, 25] print(extremos_lista(a))
"""exercicio001.py em 2018-09-29. Projeto Practice Python. tipos de strings de entrada int Crie um programa que peça ao usuário para inserir seu nome e sua idade. Imprima uma mensagem endereçada a eles, informando o ano em que completará 100 anos. """ from datetime import datetime from cicero import cabecalho def idade_100(nome: str, idade: int) -> object: """Obtem nome e idade e retorna o ano em que fará 100 anos :param nome: nome do usuário :type nome: str :param idade: idade do usuário :type idade: int :return: ano em que completará 100 anos :rtype: object """ return print(f'Olá {nome}! Você completará 100 anos em {(datetime.now().year - idade) + 100}.') if __name__ == '__main__': cabecalho('Entrada de dados') n = str(input('Digite seu nome: ')) i = int(input('Digite sua idade: ')) idade_100(n, i)
"""exercicio002.py em 2018-09-29. Projeto Practice Python. entrada se tipos int números de comparação de igualdade mod Peça ao usuário um número. Dependendo se o número é par ou ímpar, imprima uma mensagem apropriada para o usuário. Dica: como um número par / ímpar reage diferentemente quando dividido por 2? Extras: Se o número for um múltiplo de 4, imprima uma mensagem diferente. Peça ao usuário dois números: um número para marcar (chame de num) e um número para dividir por (check). Se a verificação se for divisível por num, informe isso ao usuário. Caso contrário, imprima uma mensagem apropriada diferente. """ from cicero import cabecalho def par_impar(numero: int, divisor: int) -> object: """Verifica se o número é par ou ímpar; se par verifica se é múltiplo de 4. Verifica se o numero é divisível pelo divisor sem resto :param numero: estrada do usuário :type numero: int :param divisor: entrada do usuário :type divisor: int :return: par ou impar; se é múltiplo de 4 e se o número é divisível pelo divisor sem resto :rtype: object """ if numero % 2 == 0: if numero % 4 == 0: msg = f'O número {numero} é par e multiplo de 4.' else: msg = f'O número {numero} é par.' else: msg = f'O número {numero} é impar.' if numero % divisor == 0: return print(f'{msg}\nOs números {num} e {check} são múltiplos entre si.') else: return print(f'{msg}\nOs números {num} e {check} NÃO são múltiplos entre si.') if __name__ == '__main__': cabecalho('Par ou ímpar') num = int(input('Digite um número: ')) check = int(input('Digite um número para ser divisor: ')) par_impar(num, check)
"""exercicio017.py em 2018-10-01. Projeto Practice Python. Use o BeautifulSoup e solicite pacotes Python para imprimir uma lista de todos os títulos de artigos na página inicial do New York Times. """ import requests from bs4 import BeautifulSoup from cicero import cabecalho def decodificador(url: str): """Imprime os títulos do NY Times :param url: endereço de pesquisa no NY Times :type url: str """ titulos = [] soup = BeautifulSoup(requests.get(url).text, features='html.parser') titulo = soup.findAll('h2', {'class': 'css-78b01r esl82me2'}) for linha in titulo: titulos.append(linha.text) for i in range(len(titulos)): print(titulos[i]) if __name__ == '__main__': cabecalho('Decodificar uma página da web') decodificador('http://www.nytimes.com/')
'''kode ini akan menerima N entri sesuai yang diinput, lalu selama data yang diinput bukan -999 , maka akan menyimpan terus data-datanya sampai N entri. Setelah N entri data disimpan, program akan memproses dan menghitung rata-rata data , lalu data terbesar yang ada di N buah data dan juga data terkecilnya. Syarat pengolahan data terjadi apabila data yang diinput antara 100 dan 200 (100 dan 200 tidak diinclude). Jika data tidak antara 100 dan 200, program tetap berlanjut, tetapi tidak akan diolah. Contoh : 5 buah entri data dengan masing-masing = 1 , 150 , 300 , 15 , -5 ----maka program hanya akan mengolah data 150 dan 300 saja untuk selanjutnya dihitung rata-rata dan nilai max dan min nya. ''' N = int(input ("jumlah entry :")) k = [] for i in range(1, N+1): a = int (input ("masukkan data :")) if a != -999 : if 100 < a < 200 : k.append(a) else : print ("sesuaikan syarat!") continue else : print ("data tidak valid!") break print (k) print ("rata2 nya :" , sum(k)/float(len(k))) print ("Data terbesar :" , max(k)) print ("Data terkecil :" , min(k))
a = float(input('Zadej stranu ctverce v cm: ')) cislo_je_spravne = a > 0 if cislo_je_spravne: print('Obvod ctverce se stranou', a, 'cm je', 4 * a, 'cm') print('Obsah ctverce se stranou', a, 'cm je', a * a, 'cm2') else: print('Strana musi byt kladna, jinak z toho nebude ctverec') print('Dekujeme za pouziti geometricke kalkulacky')
value = ['pes', 'kocka', 'andulka', 'kralik', 'had'] key = [] for i in value: key.append(i[1:]) animals_dict = dict(zip(key, value)) #print(animals_dict) sorted_animals = [] for key in sorted(animals_dict): sorted_animals.append(animals_dict[key]) print(sorted_animals)
def wordCounter(string): x = 1 i = 0 while i < len(string): if(string[i] == ' '): x = x + 1 i = i + 1 return x print('\nThis program will determine the number of words in a sentence.')
import xlrd3 workbook = xlrd3.open_workbook('test01.xlsx') sheet = workbook.sheet_by_name('Sheet1') print(sheet.cell_value(0,3)) print(sheet.cell_value(1,0)) print(sheet.merged_cells) # 查看合并单元格行、列信息,数组包含四个元素(起始行、结束行、起始列、结束列) # 给出一个单元格行列,判断一个单元格是否是合并过的 x = 2 y = 0 if x>=1 and x<5: if y>=0 and y<1: print('被合并的单元格') else: print("不是合并单元格") else: print("不是合并单元格") # for 循环支持同时使用元组中的多个变量做成参数 for (min_row,max_row,min_col,max_col) in [(1, 5, 0, 1)]: print(min_row,max_row,min_col,max_col) # 解决合并单元格值为空的问题 row_index = 3 ; col_index = 2 cell_value = None for (min_row,max_row,min_col,max_col) in sheet.merged_cells: if row_index >= min_row and row_index < max_row: if col_index >= min_col and col_index < max_col: cell_value = sheet.cell_value(min_row,min_col) # 合并单元格的值等于合并起点的值(第一个单元格的值) else: cell_value = sheet.cell_value(row_index,col_index) else: cell_value = sheet.cell_value(row_index, col_index) print(cell_value) # 做成方法 def get_cell_merged_value(row_index,col_index): cell_value = None for (min_row, max_row, min_col, max_col) in sheet.merged_cells: if row_index >= min_row and row_index < max_row: if col_index >= min_col and col_index < max_col: cell_value = sheet.cell_value(min_row, min_col) # 合并单元格的值等于合并起点的值(第一个单元格的值) else: cell_value = sheet.cell_value(row_index, col_index) else: cell_value = sheet.cell_value(row_index, col_index) return cell_value
#Altere o programa dado em aula para exibir os resultados no mesmo formato de uma tabuada: #2 × 1 = 2, 2 × 2 = 4, . . . n = int(input("Tabuada de:")) x = 1 while x <= 10: tabuada = n * x print(f"{n}x{x}={tabuada}") x = x + 1
a = 4 b = 2 expressao1 = (a/b)+(b/a) expressao2 = a/b + b/a print(expressao1 == expressao2) expressao3 = a/(b+b)/a expressao4 = a/b+b/a print(expressao3 == expressao4) expressao5 = (a+b)*b-a expressao6 = a+b*b-a print(expressao5 == expressao6) #sei que eu poderia ter simplesmente colocado as expressões direto #e ficaria muito mais simples #porém fiz assim para treinar variáveis :)
#!/usr/bin/env python3 def main(): menu = ['tuna', 'ham', 'roast beef', 'turkey', 'caprese', 'pastrami'] sandwich_orders = [] finished_sandwiches = [] print("Here is today's menu:", *menu, sep="\n* ") order_sandwich(sandwich_orders) make_sandwich(sandwich_orders, finished_sandwiches) deliver_sandwich(finished_sandwiches) def order_sandwich(orders): try: while True: order = input("What kind of sandwiches would you like? (^D to exit) ") if str(order): orders.append(order) except: print() return orders def make_sandwich(orders, completed): for order in range(len(orders)): if orders[-1] == "pastrami": print("Sorry! We're out of pastrami.") orders.pop() else: completed.append(orders.pop()) return completed def deliver_sandwich(order): print("Your order is ready! Here it is:") for sandwich in order: print(sandwich.capitalize(), "sandwich") if __name__ == "__main__" : main()
def wine(wine_type): print "Mmm, yes, this will pair nicely with my %s" % wine_type def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" print "We can just give the function numbers directly:" cheese_and_crackers(20, 30) print "OR, we can use variables from our script:" amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) print "We can even do math inside too:" cheese_and_crackers(10 + 20, 5 + 6) print "And we can combine the two, variables and math:" cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) print "What sort of wine should we bring?" vino = raw_input() wine(vino)
a=input("enter the number: ") if(a%2==0): print("given value is even") else: print("given value is odd")
from math import pow N = int(input()) def solution(N): i = 0 M = N/2 if N in [0,1]: return N else: while i <= M: mid = int((i + M)/2) if pow(mid, 2) > N: M = mid - 1 elif pow(mid-1, 2) < N: i = mid + 1 if pow(M, 2) >= N: return M else: return i print(solution(N))
lst = list(map(int, input().split())) def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr)//2] less, equal, more = [], [], [] for i in arr: if i < pivot: less.append(i) elif i > pivot: more.append(i) else: equal.append(i) return quick_sort(less) + equal + quick_sort(more) def partition(arr, start, end): pivot = arr[start] left = start + 1 right = end done = False while not done: while left <= right and arr[left] <= pivot: left += 1 while left <= right and pivot <= arr[right]: right -= 1 if left > right: done = True else: arr[left], arr[right] = arr[right], arr[left] arr[start], arr[right] = arr[right], arr[start] return right def quicksort(arr, start, end): if start < end: pivot = partition(arr, start, end) quicksort(arr, start, pivot-1) quicksort(arr, pivot+1, end) return arr print(quicksort(lst, 0, len(lst) - 1)) print(quick_sort(lst))
""" Extend a simple calculator. Add and Subtract has been included for you. Your mission. If you choose to accept it, is to add the following functionality to this program. 1. Division 2. Multiplication To run this program (I am assuming you have python installed on a windows machine.) 1. Open the command line terminal. The quickest way is to enter WINDOWS KEY + R. When the Run dialog is open type cmd then Enter. 2. Navigate to your project folder in the terminal. `cd <Location of this file on your system>` 3. type `python3 main.py` and Enter. Ask all questions on digitallypink.slack.com """ # Math Operations # Add two numbers def add(x, y): return x + y # Subtract two numbers def subtract(x, y): return x - y # Add other functions here that perform math operations. # Take operation input from user. The 'input' function is used to receive input from the user. operation = input("Enter operation (e.g. + or -): ") x = float(input("Enter first number: ")) y = float(input("Enter second number: ")) # Using if statements to perform the desired operation if operation == '+': print(x, operation, y, "=", add(x, y)) elif operation == '-': print(x, operation, y, "=", subtract(x, y)) # Add other conditions following the examples above # The else below happens when no condition has been met else: print("Invalid Input.", "Cannot perform: ", x, operation, y)
def bubblesort(arr=[]): if arr is None or len(arr) == 0: return arr arr_length = len(arr) for i in range(arr_length): something_sorted = False for j in range(0, arr_length - 1 - i): if arr[j] < arr[j + 1]: continue something_sorted = True arr[j], arr[j + 1] = arr[j + 1], arr[j] if not something_sorted: break return arr
def selectionsort(arr=[]): if arr is None or len(arr) == 0: return arr sorted_arr = [] for _ in range(len(arr)): smallest = min(arr) sorted_arr.append(smallest) arr.remove(smallest) return sorted_arr
class Matrix: def __init__(self,matr): self.matr = matr def __str__(self): new_matr = '' buf2 = list(map(str, self.matr)) for i in range(len(self.matr)): buf = ' '.join(buf2[i].split(',')) new_matr += f'{buf[1:-1]}\n' return new_matr def __add__(self, other): try: new_matr = [] rez_matr = [] for i in range(len(self.matr)): new_matr.clear() for j in range(len(self.matr[0])): rez = self.matr[i][j] + other.matr[i][j] new_matr.append(rez) rez_matr.append(new_matr[:]) return Matrix(rez_matr) except IndexError as err: return f'Матрицы должны быть одного размера!! {err}' m = Matrix([[1, 2, 3], [4, 5, 6], [1, 1, 1]]) m2 = Matrix([[1, 2, 3], [4, 5, 6]]) rez = m+m2 print(rez)
rate = [] first_try = True while True: while True: try: element = int(input('Введите число: ')) break except ValueError: print('Не правильный формат данных.') if first_try == True or element < rate[-1]: rate.append(element) first_try = False print(rate) elif element > rate[0]: rate.insert(0, element) print(rate) elif element in rate: rate.insert(rate.index(element) + rate.count(element), element) print(rate) else: first_meet = True for el in rate: while first_meet: if el < element: rate.insert(rate.index(el), element) print(rate) first_meet = False
def int_func(new_word_list): new_word_list = ' '.join(list(map(str.capitalize, new_word_list))) return new_word_list word = input('Введите слово с маленькой буквы: ').split(' ') print(int_func(word))
def fact(n): for el in list(range(1, n+1)): if el == 1: rez = el yield rez else: rez = rez * el yield rez n = int(input('Введите чило: ')) for el in fact(n): print(el)
from string import ascii_lowercase def reacting(polymer): lowest = 0 while True: x = 0 prev_len = len(polymer) while True: if (polymer[x].islower() and polymer[x + 1].isupper()) or (polymer[x].isupper() and polymer[x + 1].islower()): if polymer[x].lower() == polymer[x + 1].lower(): # print('removing {} {}'.format(polymer[x], polymer[x+1])) del polymer[x:x + 2] break else: x = x + 1 else: x = x + 1 if x == prev_len - 1: lowest = x break if len(polymer) == prev_len: break return lowest with open('input') as file: poly = list(file.readline()) print('lowest unit in polymer: {}'.format(reacting(poly))) for letter in ascii_lowercase: polym = [x for x in poly if x.lower() != letter] print('Removing {} and reacting gives: {}'.format(letter, reacting(polym)))
import sys import argparse class Stock: def __init__(self, name, price, shares): self.name = name self.price = price self.shares = shares def update_stock_price(self, new_price): self.price = new_price def update_stock_name(self, new_name): self.name = new_name def update_stock_share(self, new_shares): self.shares = new_shares if __name__ == '__main__': print("hello") #if sys.argc > 1: # print("Error: Please enter the path of the input file.") parser = argparse.ArgumentParser(description='Rearranging Books') args, inputfile = parser.parse_known_args() # initialize an empty string str1 = " " # return string s = (str1.join(inputfile)) output = open("output.txt", "w+") with open(s,"r") as fp: line = fp.readline() cnt = 1 while line: output.write(line) #print("Line {}: {}".format(cnt, line.strip())) line = fp.readline() cnt += 1 # output.write(f.read()) print(output.read())
def find_pairs_of_numbers(num_list,n): count=0 s=len(num_list) for i in range(0,s): for j in range(i+1,s): if(num_list[i]+num_list[j]==n): count+=1 return(count) num_list=[10,30,40,50,60] n=90 print(find_pairs_of_numbers(num_list,n))
def calculate(distance,no_of_passengers): pass price=70 ticket_cost=80 mileage=10 route_cost=(distance/mileage)*price total_ticket_cost=(no_of_passengers*ticket_cost) if(total_ticket_cost>route_cost): profit=total_ticket_cost-route_cost return profit else: return (-1) distance=30 no_of_passengers=2 print(calculate(distance,no_of_passengers))
#!/usr/bin/python3 ########################################################################### # Script Name: rename.py # Create Date: 06/19/2019 # Description: The purpose of this script is to rename files in a directory by # replacing spaces with underscores, and converting all characters to lowercase. # Author: Mr. Machine # Tags: python, utility, files ########################################################################### # Library imports import os import time path = os.getcwd() files = os.listdir(path) for f in files: string = f for a in string: if (a.isspace()) == True: os.rename(f,f.replace(' ','_').lower()) print("Removing spaces in " + f) os.rename(f,f.replace('_-_','_').lower()) print("Removing '_-_' characters in " + f) else: pass time.sleep(.5) print("\nCurrent directory files:") for root, dirs, files in os.walk("."): for file in files: print("\t" + file) # TO DO # Add code block to only rename newly added files.
#!/usr/bin/env python ########################################################################### # Script Name: webscraper.py # Create Date: 12/05/2018 # Description: The purpose of this file is to enter a website url and perform a # simple scrape of the webpage's content and parse through the text objects using # regular expressions. # Author: Mr. Machine # Tags: python, utility, web, url # Resources: https://towardsdatascience.com/web-scraping-regular-expressions-and-data-visualization-doing-it-all-in-python-37a1aade7924 ########################################################################### # Library imports import requests import re from bs4 import BeautifulSoup # Define the desired URL to scrape # url = http://www.cleveland.com/metro/index.ssf/2017/12/case_western_reserve_university_president_barbara_snyders_base_salary_and_bonus_pay_tops_among_private_colleges_in_ohio.html # Example web URL for scraping demo web_url = input("Enter the complete URL to scrape: ") print("You entered " + web_url) confirm = input("Is this entry correct? (Y/n)") if confirm == Y or y: pass else: break # Make the GET request to the defined URL of website # r = requests.get(url) # Example GET request for demo r = requests.get(web_url) # Extract the content c = r.content # Create soup object soup = BeautifulSoup(c) # Find the desired element on the webpage # main_content = soup.find('div', attrs = {'class': 'entry-content'}) #Example entries for main content html tag main_content = soup.find() # Extract the relevant content as text # content = main_content.find('ul').text # Example html 'ul' tag to search unordered lists within main content content = main_content.find().text # Create a pattern to match names name_pattern = re.compile(r'^([A-Z]{1}.+?)(?:,)', flags = re.M) # Find all occurrences of the pattern names = name_pattern.findall(content) # FMake school pattern nd extract schools school_pattern = re.compile(r'(?:,|,\s)([A-Z]{1}.*?)(?:\s\(|:|,)') schools = school_pattern.findall(content) # Pattern to match the salaries salary_pattern = re.compile(r'\$.+') salaries = salary_pattern.findall(content) # Convert salaries to numbers in a list comprehension [int(''.join(s[1:].split(','))) for s in salaries]
#!/usr/bin/python i = 8 if(i % 2 == 0): print ("Even Number") else: print ("Odd Number") #% means modulus # i%2 ==0 means a number is even def evens(set): total=0 for el in set: if el%2==0: total+=el return total som=[1,2,3,4] evens(som) def get_age(): age =int( input("please enter your age")) if (age>=45): print('you are old') else: print('you are young') get_age() def find_age(): yob=int(input('enter your year of birth')) age=2019-yob print("you are ",age,'years old' ) find_age() def leapYear(): yob=int(input('enter your year of birth')) if yob%4==0: return True return False leapYear()
# beer song using For loop for qty in range(99,0,-1): if(qty>1): print(qty,"Bottles of beer on the wall,",qty,"bottles of beer") suffix= str(qty-1) + " bottle"+('s' if (qty!=2) else '')+" of beer on the wall" else : print("1 bottle of beer on the wall,1 bottle of beer") suffix="No more beer on the wall" print ("Take one down and pass it around,",suffix) print ("----------------------")
tabby_cat = '\tI\'m tabbed in.' persian_cat = 'I\'m split\non a line.' backslash_cat = 'I\'m \\ a \\ cat' fat_cat = ''' I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass ''' print tabby_cat print persian_cat print backslash_cat print fat_cat tricky_string_1 = 'This sentence has a backspace\b\n' tricky_string_2 = 'This sentence has a sound \a\n' tricky_string_3 = 'This sentence has a set of "double-quotes"\n\ and \'escaped\' single-quotes\'\n' tricky_string_4 = 'This word needs some space\tfrom this word\ and this number %d\n' % (75) print 'Here is what I wrote %r and here it is again: %s' % (tricky_string_1, tricky_string_1) print 'These are strings within another string...%s...within a string\ ...within a...%s...' % (tricky_string_2 + tricky_string_3, tricky_string_1) print tricky_string_4 string_test = 'This is a test "sentence"' print 'Using %%r: %r\nUsing %%s: %s' % (string_test, string_test)
print 'What is your name?', name = raw_input() print 'Where were you born?', birthplace = raw_input() print 'What is your favorite sport?', sport = raw_input() print 'So, your name is %s, born in %s, \ and you like %s' % (name, birthplace, sport)
# hackerrank - Algorithms: Is Fibo # Written by James Andreou, University of Waterloo import math def perfect_square(n): r = math.sqrt(n) return int(r + 0.5) ** 2 == n T = int(raw_input()) for t in range(0, T): N = int(raw_input())**2 * 5 if perfect_square(N+4) or perfect_square(N-4): print 'IsFibo' else: print 'IsNotFibo'
# hackerrank - Algorithms: Maximizing XOR # Written by James Andreou, University of Waterloo L = int(raw_input()) R = int(raw_input()) max = 0 for a in range(L, R+1): for b in range(a, R+1): if a ^ b > max: max = a ^ b print max
# There are N network nodes, labelled 1 to N. # # Given times, a list of travel times as directed edges times[i] = (u, v, w), # where u is the source node, v is the target node, and w is the time it takes # for a signal to travel from source to target. # # Now, we send a signal from a certain node K. How long will it take for all # nodes to receive the signal? If it is impossible, return -1. # # Note: # N will be in the range [1, 100]. # K will be in the range [1, N]. # The length of times will be in the range [1, 6000]. # All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100. import heapq class Solution: def networkDelayTime(self, times, N, K): """ :type times: List[List[int]] :type N: int :type K: int :rtype: int """ graph: object = collections.defaultdict(list) distances = {} distances[starting_vertex] = 0 entry_lookup = {} pq = [(0, K)] for u, v, w in times: entry = (v, w) heapq.heappush(pq, entry)
__author__ = 'ralph' from math import sqrt def is_prime(x): if x < 2: return False for i in range(2, int(sqrt(x)) + 1): if x % i == 0: return False return True # filter applied to range print([x for x in range(101) if is_prime(x)]) from pprint import pprint as pp # Combining a filtering predicate with a transformation # Dictionary transformation which maps numbers with three divisors prime_square_divisors = {x*x:(1, x, x*x) for x in range(101) if is_prime(x)} pp(prime_square_divisors)
# using a hashtable to count individual items # define a set of items that we want to count items = ["apple", "pear", "orange", "banana", "apple", "orange", "apple", "pear", "banana", "orange", "apple", "kiwi", "pear", "apple", "orange"] # TODO: create a hashtable object to hold the items and counts counter = None # TODO: iterate over each item and increment the count for each one # print the results print(counter)
# Datetime Module Part I from datetime import datetime now = datetime.now() print(now.date()) print(now.year) print(now.month) print(now.hour) print(now.minute) print(now.second) print(now.time())
# use a hashtable to filter out duplicate items # define a set of items that we want to reduce duplicates items = ["apple", "pear", "orange", "banana", "apple", "orange", "apple", "pear", "banana", "orange", "apple", "kiwi", "pear", "apple", "orange"] # TODO: create a hashtable to perform a filter # TODO: loop over each item and add to the hashtable # TODO: create a set from the resulting keys in the hashtable
#!/usr/bin/env python # -*- coding: utf-8 -*- # Template Version: 2017-04-13 # ~~ Future First ~~ from __future__ import division # Future imports must be called before everything else, including triple-quote docs! """ URL, Intro to Multithreading: https://medium.com/@bfortuner/python-multithreading-vs-multiprocessing-73072ce5600b RESULT: """ """ ~~ Process -vs- Thread ~~ A process is an instance of program (e.g. Jupyter notebook, Python interpreter). Processes spawn threads (sub-processes) to handle subtasks like reading keystrokes, loading HTML pages, saving files. Threads live inside processes and share the same memory space. * Threads are like mini-processes that live inside a process * They share memory space and efficiently read and write to the same variables * Two threads cannot execute code simultaneously in the same python program (although there are workarounds*) ~~ CPU vs Core ~~ The CPU, or processor, manages the fundamental computational work of the computer. CPUs have one or more cores, allowing the CPU to execute code simultaneously. ~~ Python’s GIL problem ~~ CPython (the standard python implementation) has something called the GIL (Global Interpreter Lock), which prevent two threads from executing simultaneously in the same program. There are workarounds, however, and libraries like Numpy bypass this limitation by running external code in C. ~ When to use threads vs processes? ~ * Processes speed up Python operations that are CPU intensive because they benefit from multiple cores and avoid the GIL. * Threads are best for IO tasks or tasks involving external systems because threads can combine their work more efficiently. Processes need to pickle their results to combine them which takes time. Threads provide no benefit in python for CPU intensive tasks because of the GIL. """
#!/usr/bin/env python """ This code originally written by Craig Finch https://github.com/cfinch/Shocksolution_Examples/blob/master/Plotting/matplotlib/plot_without_axes.py """ import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.text import Text import numpy fig1 = plt.figure(facecolor='white') ax1 = plt.axes(frameon=False) #ax1.set_frame_on(False) # Alternate way to turn frame off ax1.get_xaxis().tick_bottom() # Turn off ticks at top of plot #ax1.axes.get_xaxis().set_visible(False) ax1.axes.get_yaxis().set_visible(False) # Hide y axis # Add a plot y_offset = 2.0 x = numpy.arange(-5.0, 5.0, 0.1) for i in range(3): ax1.plot(x, numpy.sin((i + 1) * x) + i * y_offset, label=str(i+1)) ax1.grid(False) # Remove any lines from the plot area for tic in ax1.xaxis.get_major_ticks(): tic.tick1On = tic.tick2On = False tic.label1On = tic.label2On = False # plt.legend(loc='lower right') # Draw the x axis line # Note that this must be done after plotting, to get the correct # view interval xmin, xmax = ax1.get_xaxis().get_view_interval() ymin, ymax = ax1.get_yaxis().get_view_interval() ax1.add_artist(Line2D((xmin, xmax), (ymin, ymin), color='black', linewidth=2)) plt.show()
def func_with_args( foo , bar , baz , **kwargs ): """ Simple function with three named args """ print "Got named args:" , foo , bar , baz , if 'other' in kwargs: print kwargs['other'] else: print argDict = { 'foo':1 , 'bar':2 , 'baz':3 , 'other':4 } # The dictionary will also populate '**kwargs'! func_with_args( **argDict ) # Got named args: 1 2 3 4
# -*- coding: utf-8 -*- for i in xrange(4000): print i, if i > 5: break # "0 1 2 3 4 5 6" import random for i in range(10): for j in range(10): num = random.randrange(1,11) print i , "," , j , ":" , num if num > 5: print "break" break """ 0 , 0 : 5 0 , 1 : 5 0 , 2 : 6 break <---- Only breaks from the innermost loop! 1 , 0 : 10 break 2 , 0 : 10 """ print broken = False for i in range(10): if broken: break for j in range(10): num = random.randrange(1,11) print i , "," , j , ":" , num if num > 5: print "break" broken = True break """ 0 , 0 : 4 0 , 1 : 1 0 , 2 : 8 break <--- Breaks all the way out! """
zeros = [ [0,0,0] , [0,0,0] , [0,0,0] ] print zeros for rDex , row in enumerate( zeros ): # Operate on the list as we go row[rDex] = 1 print zeros """ [[0, 0, 0], [0, 0, 0], [0, 0, 0]] [[1, 0, 0], [0, 1, 0], [0, 0, 1]] """
# -*- coding: utf-8 -*- """ URL, Priority Queue: https://en.wikipedia.org/wiki/Priority_queue A priority queue is an abstract data type which is like a regular queue or stack data structure, but where additionally each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. """ from Queue import PriorityQueue q1 = PriorityQueue() q1.put(10) q1.put(1) q1.put(5) while not q1.empty(): print q1.get(), # 1 5 10 print q2 = PriorityQueue() q2.put( (10,'foo') ) q2.put( ( 1,'bar') ) q2.put( ( 5,'baz') ) while not q2.empty(): print q2.get(), # (1, 'bar') (5, 'baz') (10, 'foo') print q2.put( (10,'foo') ) q2.put( ( 1,'bar') ) q2.put( ( 5,'baz') ) print "There are",len(q2),"items in 'q2'" while not q2.empty(): print q2.get()[1], # bar baz foo
class Foo: """ A silly class for testing membership """ def __init__( self ): """ Init some silly vars """ self.bar = 1 self.baz = 2 def check_for_baz( self ): """ Check if this instance has a baz """ return hasattr( self , 'baz' ) xur = Foo() if hasattr( xur , 'bar' ): print "xur has a bar!" # xur has a bar! if hasattr( xur , 'baz' ): print "xur has a baz!" # xur has a baz! if hasattr( xur , 'ank' ): print "xur has an ank!" else: print "xur has no ank!" # xur has no ank! print "xur has a baz?:" , xur.check_for_baz() """ xur has a bar! xur has a baz! xur has no ank! xur has a baz?: True """
# -*- coding: utf-8 -*- foo = lambda x, y: (x+y, x-y) # OK : lambda can return one value #bar = lambda x, y: x+y, x-y # ERROR : Cannot use multiple returns as you can with a def function, with lambda you must # pack multiple values into a single structure if multiple values must be returned print foo(2,3) # (5, -1) #print bar(2,3) # sorry, no dice
#!/usr/bin/env python """ RESULT: If the elements in a list are themselves iterables , you can decompose the nested elements with the pattern: 'for [ subElem1 , subElem2 ] in superList' for a list that takes the form superList = [ ... , [ i1 , i2 ] , ... ] """ from random import randint listList = [] N = 10 for i in xrange( N ): listList.append( [ randint( 1 , 5 ) , randint( 6 , 10 ) ] ) for [ op1 , op2 ] in listList: print "Decomposed pair:" , op1 , "and" , op2
# -*- coding: utf-8 -*- def cls_declare_print(clsName): print "Class",clsName,"was declared!" class Foo(object): cls_declare_print('Foo') def __init__(self): print "One new Foo!" class Bar(object): cls_declare_print('Bar') def __init__(self): print "One new Bar!" theFoo = Foo() theBar = Bar() anotherFoo = Foo() anotherBar = Bar() # Class Foo was declared! # As expected, 'cls_declare_print' was only called once in the declaration of each class! # Class Bar was declared! # One new Foo! # One new Bar! # One new Foo! # One new Bar!
import os import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import matplotlib.animation as animation def plot_a_sequence_of_images(list_arr): """ :param list_arr: list of 2d arrays of the same dimension :return: animation having the sequence of images as input """ fig = plt.figure(1, figsize=(7, 7), dpi=100) fig.subplots_adjust(left=0.04, right=0.98, top=0.92, bottom=0.08) ax = fig.add_subplot(111) plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) ims = [] for arr in list_arr: im = plt.imshow(arr, cmap='Greys', interpolation='nearest', animated=True) ims.append([im]) im_ani = animation.ArtistAnimation(fig, ims, interval=100, repeat_delay=3000, blit=False) #plt.show() return im_ani
# 1. fill in this class # it will need to provide for what happens below in the # main, so you will at least need a constructor that takes the values as (Brand, Price, Safety Rating), # a function called showEvaluation, and an attribute carCount import sys class CarEvaluation: 'A simple class that represents a car evaluation' #all your logic here carCount = 0 def __init__(self, name, price, safety): self.name = name self.price = price self.safety = safety CarEvaluation.carCount += 1 def __repr__(self): return self.name def showEvaluation(self): print "The %s has a %s price and it's safety is rated a %s" % (self.name, self.price, self.safety) #2. fill in this function # it takes a list of CarEvaluation objects for input and either "asc" or "des" # if it gets "asc" return a list of car names order by ascending price # otherwise by descending price def sortbyprice(listCarEvaluation, order): #you fill in the rest listCarEvaluation.sort(key = lambda x: {"High":3,"Med":2,"Low":1}[x.price],reverse={"asc":False,"des":True}[order]) return listCarEvaluation #return a value #return listCarEvaluation.sort(key = lambda x: {"High":3,"Med":2,"Low":1}[x.price])#return a value #3. fill in this function # it takes a list for input of CarEvaluation objects and a value to search for # it returns true if the value is in the safety attribute of an entry on the list, # otherwise false def searchforsafety(a, b): #you fill in the rest return b in [car.safety for car in a] #return a value # This is the main of the program. Expected outputs are in comments after the function calls. if __name__ == "__main__": eval1 = CarEvaluation("Ford", "High", 2) eval2 = CarEvaluation("GMC", "Med", 4) eval3 = CarEvaluation("Toyota", "Low", 3) print "Car Count = %d" % CarEvaluation.carCount # Car Count = 3 eval1.showEvaluation() #The Ford has a High price and it's safety is rated a 2 eval2.showEvaluation() #The GMC has a Med price and it's safety is rated a 4 eval3.showEvaluation() #The Toyota has a Low price and it's safety is rated a 3 L = [eval1, eval2, eval3] print sortbyprice(L, "asc"); #[Toyota, GMC, Ford] print sortbyprice(L, "des"); #[Ford, GMC, Toyota] print searchforsafety(L, 2); #true print searchforsafety(L, 1); #false # Part II rewrite the main using introspection #Get current module this_module = sys.modules[__name__] eval4 = getattr(this_module,"CarEvaluation")("Ford","High",2) eval5 = getattr(this_module,"CarEvaluation")("GMC","Med",4) eval6 = getattr(this_module,"CarEvaluation")("Toyoto","Low",3) print "Car Count = %d" % getattr(getattr(this_module,"CarEvaluation"),"carCount") # Car Count = 6 getattr(eval4,"showEvaluation")() getattr(eval5,"showEvaluation")() getattr(eval6,"showEvaluation")() L1 = [eval4,eval5,eval6] print getattr(this_module,"sortbyprice")(L1,"asc") #[Toyota, GMC, Ford] print getattr(this_module,"sortbyprice")(L1,"des") #[Ford, GMC, Toyota] print getattr(this_module,"searchforsafety")(L1,2)#true print getattr(this_module,"searchforsafety")(L1,1) #false
__author__ = 'Mohan Kandaraj' import Tkinter import sys import tkFileDialog from scipy.optimize import curve_fit import numpy import matplotlib.pyplot as pyplot def linear_regression(data): """Compute Linear Regression for univariate model""" x_values = [x for x, y in data] #Get x values y_values = [y for x, y in data] #Get y values x_mean = sum(x_values) / len(x_values) #Compute mean value of x y_mean = sum(y_values) / len(y_values) #Compute mean value of y # Compute coefficient = sum([(x - x_mean) * (y-y_mean) for x,y in data]) / sum([(x - x_mean) ** 2 for x in x_values]) intercept = y_mean - coefficient * x_mean # Compute Intercept return((coefficient,intercept)) #Define function for linear model def quad(x,a,b,c): """ Linear Equation """ return a * x ** 2 + b * x + c #Define function for quadratic def lm(x,a,b): """ Linear Equation """ return a * x + b if __name__ == "__main__": """Main function to execute the program""" Tkinter.Tk().withdraw() try: file = tkFileDialog.askopenfile() # Ask user for the file and open the file in read mode if file is None: sys.exit() # Read Input, split input into lines, split fields in a line to a list and store as nested list brainandbody = [lines.split(",") for lines in file.read().splitlines()][1:] # Compute regression formula and print.. regression =linear_regression([[float(brain),float(body)] for name,body,brain in brainandbody]) print "Regression Model" print "bo = %s br + %s" % regression print "Regression Model after converting body weight to gram (i.e to same unit as brain)" print "bo = %s br + %s" % (regression[0]*1000,regression[1]*1000) brainandbody_n=numpy.array([[body,brain] for name,body,brain in brainandbody],float) coeff,covar=curve_fit(lm,brainandbody_n[:,1],brainandbody_n[:,0]) print "Linear Regression Model using numpy Curve Fitting" print "bo = %s br + %s" % (coeff[0],coeff[1]) print "\n" brain=[float(br) for name,bo,br in brainandbody] actual_body=[float(bo) for name,bo,br in brainandbody] linear_body=[lm(br,coeff[0],coeff[1]) for br in brain] import timeit setup="from __main__ import brainandbody,linear_regression" t=timeit.Timer("linear_regression([[float(brain),float(body)] for name,body,brain in brainandbody])",setup) setup="from __main__ import brainandbody_n,lm;from scipy.optimize import curve_fit" print "Time taken for manual linear Regression 5 loops : %s" % (t.timeit(5)) t=timeit.Timer("curve_fit(lm,brainandbody_n[:,1],brainandbody_n[:,0])",setup) print "Time taken for scipy curve fit Regression 5 loops: %s" % (t.timeit(5)) print "\n" coeff,covar=curve_fit(quad,brainandbody_n[:,1],brainandbody_n[:,0]) print "Quadratic Model using numpy Curve Fitting" print "bo = %s br^2 + %s br + %s" % (coeff[0],coeff[1],coeff[2]) quad_body=[quad(br,coeff[0],coeff[1],coeff[2]) for br in brain] #Plot the data, linear and quadratic models dat,=pyplot.plot(brain,actual_body,"go",label="Actual") linear_line,=pyplot.plot(brain,linear_body,"b-",label="Linear") quad_line,=pyplot.plot(brain,quad_body,"ro",label="Quadratic") pyplot.legend(handles=[dat,linear_line,quad_line],loc=2) pyplot.title("Linear and Quadratic Fits") pyplot.show() except Exception, e: print "Error: " + str(e) sys.exit(e) finally: if file is not None: file.close()
# 예외처리 import random def numguess(try_cnt = 5, answer = random.randint(1, 100)): while True: if try_cnt == 0: print("your try Count is sold out\n Correct is {}".format(answer)) break try: your_input = int(input("input the answer : ")) except Exception as e: print(e) else: if answer == your_input: print("Correct : answer is {}".format(answer)) break elif answer > your_input: try_cnt -= 1 print(("bigger than {}".format(your_input))) else: try_cnt -= 1 print(("smaller than {}".format(your_input))) # finally # 나의 Exception class MyError(Exception): def __str__(self): return "My Custom Error"
""" The xml_simple_reader.py script is an xml parser that can parse a line separated xml text. This xml parser will read a line seperated xml text and produce a tree of the xml with a document element. Each element can have an attribute table, childNodes, a class name, parentNode, text and a link to the document element. This example gets an xml tree for the xml file boolean.xml. This example is run in a terminal in the folder which contains boolean.xml and xml_simple_reader.py. > python Python 2.5.1 (r251:54863, Sep 22 2007, 01:43:31) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> fileName = 'boolean.xml' >>> file = open(fileName, 'r') >>> xmlText = file.read() >>> file.close() >>> from xml_simple_reader import DocumentNode >>> xmlParser = DocumentNode(fileName, xmlText) >>> print( xmlParser ) ?xml, {'version': '1.0'} ArtOfIllusion, {'xmlns:bf': '//babelfiche/codec', 'version': '2.0', 'fileversion': '3'} Scene, {'bf:id': 'theScene'} materials, {'bf:elem-type': 'java.lang.Object', 'bf:list': 'collection', 'bf:id': '1', 'bf:type': 'java.util.Vector'} .. many more lines of the xml tree .. """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.geometry.geometry_utilities import evaluate from fabmetheus_utilities.geometry.geometry_utilities import matrix from fabmetheus_utilities import archive from fabmetheus_utilities import euclidean from fabmetheus_utilities import xml_simple_writer import cStringIO __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __credits__ = 'Nophead <http://hydraraptor.blogspot.com/>\nArt of Illusion <http://www.artofillusion.org/>' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' globalGetAccessibleAttributeSet = set('getPaths getPreviousVertex getPreviousElementNode getVertexes parentNode'.split()) def createAppendByText(parentNode, xmlText): 'Create and append the child nodes from the xmlText.' monad = OpenMonad(parentNode) for character in xmlText: monad = monad.getNextMonad(character) def createAppendByTextb(parentNode, xmlText): 'Create and append the child nodes from the xmlText.' monad = OpenMonad(parentNode) for character in xmlText: monad = monad.getNextMonad(character) def getChildElementsByLocalName(childNodes, localName): 'Get the childNodes which have the given local name.' childElementsByLocalName = [] for childNode in childNodes: if localName.lower() == childNode.getNodeName(): childElementsByLocalName.append(childNode) return childElementsByLocalName def getDocumentNode(fileName): 'Get the document from the file name.' xmlText = getFileText('test.xml') return DocumentNode(fileName, xmlText) def getElementsByLocalName(childNodes, localName): 'Get the descendents which have the given local name.' elementsByLocalName = getChildElementsByLocalName(childNodes, localName) for childNode in childNodes: if childNode.getNodeType() == 1: elementsByLocalName += childNode.getElementsByLocalName(localName) return elementsByLocalName def getFileText(fileName, printWarning=True, readMode='r'): 'Get the entire text of a file.' try: file = open(fileName, readMode) fileText = file.read() file.close() return fileText except IOError: if printWarning: print('The file ' + fileName + ' does not exist.') return '' class CDATASectionMonad: 'A monad to handle a CDATASection node.' def __init__(self, input, parentNode): 'Initialize.' self.input = input self.parentNode = parentNode def getNextMonad(self, character): 'Get the next monad.' self.input.write(character) if character == '>': inputString = self.input.getvalue() if inputString.endswith(']]>'): textContent = '<%s\n' % inputString self.parentNode.childNodes.append(CDATASectionNode(self.parentNode, textContent)) return OpenMonad(self.parentNode) return self class CDATASectionNode: 'A CDATASection node.' def __init__(self, parentNode, textContent=''): 'Initialize.' self.parentNode = parentNode self.textContent = textContent def __repr__(self): 'Get the string representation of this CDATASection node.' return self.textContent def addToIdentifierDictionaries(self): 'Add the element to the owner document identifier dictionaries.' pass def addXML(self, depth, output): 'Add xml for this CDATASection node.' output.write(self.textContent) def appendSelfToParent(self): 'Append self to the parentNode.' self.parentNode.appendChild(self) def copyXMLChildNodes(self, idSuffix, parentNode): 'Copy the xml childNodes.' pass def getAttributes(self): 'Get the attributes.' return {} def getChildNodes(self): 'Get the empty set.' return [] def getCopy(self, idSuffix, parentNode): 'Copy the xml element, set its dictionary and add it to the parentNode.' copy = self.getCopyShallow() copy.parentNode = parentNode copy.appendSelfToParent() return copy def getCopyShallow(self, attributes=None): 'Copy the node and set its parentNode.' return CDATASectionNode(self.parentNode, self.textContent) def getNodeName(self): 'Get the node name.' return '#cdata-section' def getNodeType(self): 'Get the node type.' return 4 def getOwnerDocument(self): 'Get the owner document.' return self.parentNode.getOwnerDocument() def getTextContent(self): 'Get the text content.' return self.textContent def removeChildNodesFromIDNameParent(self): 'Remove the childNodes from the id and name dictionaries and the childNodes.' pass def removeFromIDNameParent(self): 'Remove this from the id and name dictionaries and the childNodes of the parentNode.' if self.parentNode is not None: self.parentNode.childNodes.remove(self) def setParentAddToChildNodes(self, parentNode): 'Set the parentNode and add this to its childNodes.' self.parentNode = parentNode if self.parentNode is not None: self.parentNode.childNodes.append(self) attributes = property(getAttributes) childNodes = property(getChildNodes) nodeName = property(getNodeName) nodeType = property(getNodeType) ownerDocument = property(getOwnerDocument) class CommentMonad(CDATASectionMonad): 'A monad to handle a comment node.' def getNextMonad(self, character): 'Get the next monad.' self.input.write(character) if character == '>': inputString = self.input.getvalue() if inputString.endswith('-->'): textContent = '<%s\n' % inputString self.parentNode.childNodes.append(CommentNode(self.parentNode, textContent)) return OpenMonad(self.parentNode) return self class CommentNode(CDATASectionNode): 'A comment node.' def getCopyShallow(self, attributes=None): 'Copy the node and set its parentNode.' return CommentNode(self.parentNode, self.textContent) def getNodeName(self): 'Get the node name.' return '#comment' def getNodeType(self): 'Get the node type.' return 8 nodeName = property(getNodeName) nodeType = property(getNodeType) class DocumentNode: 'A class to parse an xml text and store the elements.' def __init__(self, fileName, xmlText): 'Initialize.' self.childNodes = [] self.fileName = fileName self.idDictionary = {} self.nameDictionary = {} self.parentNode = None self.tagDictionary = {} self.xmlText = xmlText createAppendByText(self, xmlText) def __repr__(self): 'Get the string representation of this xml document.' output = cStringIO.StringIO() for childNode in self.childNodes: childNode.addXML(0, output) return output.getvalue() def appendChild(self, elementNode): 'Append child elementNode to the child nodes.' self.childNodes.append(elementNode) elementNode.addToIdentifierDictionaries() return elementNode def getAttributes(self): 'Get the attributes.' return {} def getCascadeBoolean(self, defaultBoolean, key): 'Get the cascade boolean.' return defaultBoolean def getCascadeFloat(self, defaultFloat, key): 'Get the cascade float.' return defaultFloat def getDocumentElement(self): 'Get the document element.' if len(self.childNodes) == 0: return None return self.childNodes[-1] def getElementsByLocalName(self, localName): 'Get the descendents which have the given local name.' return getElementsByLocalName(self.childNodes, localName) def getImportNameChain(self, suffix=''): 'Get the import name chain with the suffix at the end.' return suffix def getNodeName(self): 'Get the node name.' return '#document' def getNodeType(self): 'Get the node type.' return 9 def getOriginalRoot(self): 'Get the original reparsed document element.' if evaluate.getEvaluatedBoolean(True, self.documentElement, 'getOriginalRoot'): return DocumentNode(self.fileName, self.xmlText).documentElement return None def getOwnerDocument(self): 'Get the owner document.' return self attributes = property(getAttributes) documentElement = property(getDocumentElement) nodeName = property(getNodeName) nodeType = property(getNodeType) ownerDocument = property(getOwnerDocument) class DocumentTypeMonad(CDATASectionMonad): 'A monad to handle a document type node.' def getNextMonad(self, character): 'Get the next monad.' self.input.write(character) if character == '>': inputString = self.input.getvalue() if inputString.endswith('?>'): textContent = '%s\n' % inputString self.parentNode.childNodes.append(DocumentTypeNode(self.parentNode, textContent)) return OpenMonad(self.parentNode) return self class DocumentTypeNode(CDATASectionNode): 'A document type node.' def getCopyShallow(self, attributes=None): 'Copy the node and set its parentNode.' return DocumentTypeNode(self.parentNode, self.textContent) def getNodeName(self): 'Get the node name.' return '#forNowDocumentType' def getNodeType(self): 'Get the node type.' return 10 nodeName = property(getNodeName) nodeType = property(getNodeType) class ElementEndMonad: 'A monad to look for the end of an ElementNode tag.' def __init__(self, parentNode): 'Initialize.' self.parentNode = parentNode def getNextMonad(self, character): 'Get the next monad.' if character == '>': return TextMonad(self.parentNode) return self class ElementLocalNameMonad: 'A monad to set the local name of an ElementNode.' def __init__(self, character, parentNode): 'Initialize.' self.input = cStringIO.StringIO() self.input.write(character) self.parentNode = parentNode def getNextMonad(self, character): 'Get the next monad.' if character == '[': if (self.input.getvalue() + character).startswith('![CDATA['): self.input.write(character) return CDATASectionMonad(self.input, self.parentNode) if character == '-': if (self.input.getvalue() + character).startswith('!--'): self.input.write(character) return CommentMonad(self.input, self.parentNode) if character.isspace(): self.setLocalName() return ElementReadMonad(self.elementNode) if character == '/': self.setLocalName() self.elementNode.appendSelfToParent() return ElementEndMonad(self.elementNode.parentNode) if character == '>': self.setLocalName() self.elementNode.appendSelfToParent() return TextMonad(self.elementNode) self.input.write(character) return self def setLocalName(self): 'Set the class name.' self.elementNode = ElementNode(self.parentNode) self.elementNode.localName = self.input.getvalue().lower().strip() class ElementNode: 'An xml element.' def __init__(self, parentNode=None): 'Initialize.' self.attributes = {} self.childNodes = [] self.localName = '' self.parentNode = parentNode self.xmlObject = None def __repr__(self): 'Get the string representation of this xml document.' return '%s\n%s\n%s' % (self.localName, self.attributes, self.getTextContent()) def _getAccessibleAttribute(self, attributeName): 'Get the accessible attribute.' global globalGetAccessibleAttributeSet if attributeName in globalGetAccessibleAttributeSet: return getattr(self, attributeName, None) return None def addSuffixToID(self, idSuffix): 'Add the suffix to the id.' if 'id' in self.attributes: self.attributes['id'] += idSuffix def addToIdentifierDictionaries(self): 'Add the element to the owner document identifier dictionaries.' ownerDocument = self.getOwnerDocument() importNameChain = self.getImportNameChain() idKey = self.getStrippedAttributesValue('id') if idKey is not None: ownerDocument.idDictionary[importNameChain + idKey] = self nameKey = self.getStrippedAttributesValue('name') if nameKey is not None: euclidean.addElementToListDictionaryIfNotThere(self, importNameChain + nameKey, ownerDocument.nameDictionary) for tagKey in self.getTagKeys(): euclidean.addElementToListDictionaryIfNotThere(self, tagKey, ownerDocument.tagDictionary) def addXML(self, depth, output): 'Add xml for this elementNode.' innerOutput = cStringIO.StringIO() xml_simple_writer.addXMLFromObjects(depth + 1, self.childNodes, innerOutput) innerText = innerOutput.getvalue() xml_simple_writer.addBeginEndInnerXMLTag(self.attributes, depth, innerText, self.localName, output, self.getTextContent()) def appendChild(self, elementNode): 'Append child elementNode to the child nodes.' self.childNodes.append(elementNode) elementNode.addToIdentifierDictionaries() return elementNode def appendSelfToParent(self): 'Append self to the parentNode.' self.parentNode.appendChild(self) def copyXMLChildNodes(self, idSuffix, parentNode): 'Copy the xml childNodes.' for childNode in self.childNodes: childNode.getCopy(idSuffix, parentNode) def getCascadeBoolean(self, defaultBoolean, key): 'Get the cascade boolean.' if key in self.attributes: value = evaluate.getEvaluatedBoolean(None, self, key) if value is not None: return value return self.parentNode.getCascadeBoolean(defaultBoolean, key) def getCascadeFloat(self, defaultFloat, key): 'Get the cascade float.' if key in self.attributes: value = evaluate.getEvaluatedFloat(None, self, key) if value is not None: return value return self.parentNode.getCascadeFloat(defaultFloat, key) def getChildElementsByLocalName(self, localName): 'Get the childNodes which have the given local name.' return getChildElementsByLocalName(self.childNodes, localName) def getCopy(self, idSuffix, parentNode): 'Copy the xml element, set its dictionary and add it to the parentNode.' matrix4X4 = matrix.getBranchMatrixSetElementNode(self) attributesCopy = self.attributes.copy() attributesCopy.update(matrix4X4.getAttributes('matrix.')) copy = self.getCopyShallow(attributesCopy) copy.setParentAddToChildNodes(parentNode) copy.addSuffixToID(idSuffix) copy.addToIdentifierDictionaries() self.copyXMLChildNodes(idSuffix, copy) return copy def getCopyShallow(self, attributes=None): 'Copy the xml element and set its dictionary and parentNode.' if attributes is None: # to evade default initialization bug where a dictionary is initialized to the last dictionary attributes = {} copyShallow = ElementNode(self.parentNode) copyShallow.attributes = attributes copyShallow.localName = self.localName return copyShallow def getDocumentElement(self): 'Get the document element.' return self.getOwnerDocument().getDocumentElement() def getElementNodeByID(self, idKey): 'Get the xml element by id.' idDictionary = self.getOwnerDocument().idDictionary idKey = self.getImportNameChain() + idKey if idKey in idDictionary: return idDictionary[idKey] return None def getElementNodesByName(self, nameKey): 'Get the xml elements by name.' nameDictionary = self.getOwnerDocument().nameDictionary nameKey = self.getImportNameChain() + nameKey if nameKey in nameDictionary: return nameDictionary[nameKey] return None def getElementNodesByTag(self, tagKey): 'Get the xml elements by tag.' tagDictionary = self.getOwnerDocument().tagDictionary if tagKey in tagDictionary: return tagDictionary[tagKey] return None def getElementsByLocalName(self, localName): 'Get the descendents which have the given local name.' return getElementsByLocalName(self.childNodes, localName) def getFirstChildByLocalName(self, localName): 'Get the first childNode which has the given class name.' for childNode in self.childNodes: if localName.lower() == childNode.getNodeName(): return childNode return None def getIDSuffix(self, elementIndex=None): 'Get the id suffix from the dictionary.' suffix = self.localName if 'id' in self.attributes: suffix = self.attributes['id'] if elementIndex is None: return '_%s' % suffix return '_%s_%s' % (suffix, elementIndex) def getImportNameChain(self, suffix=''): 'Get the import name chain with the suffix at the end.' importName = self.getStrippedAttributesValue('_importName') if importName is not None: suffix = '%s.%s' % (importName, suffix) return self.parentNode.getImportNameChain(suffix) def getNodeName(self): 'Get the node name.' return self.localName def getNodeType(self): 'Get the node type.' return 1 def getOwnerDocument(self): 'Get the owner document.' return self.parentNode.getOwnerDocument() def getParser(self): 'Get the parser.' return self.getOwnerDocument() def getPaths(self): 'Get all paths.' if self.xmlObject is None: return [] return self.xmlObject.getPaths() def getPreviousElementNode(self): 'Get previous ElementNode if it exists.' if self.parentNode is None: return None previousElementNodeIndex = self.parentNode.childNodes.index(self) - 1 if previousElementNodeIndex < 0: return None return self.parentNode.childNodes[previousElementNodeIndex] def getPreviousVertex(self, defaultVector3=None): 'Get previous vertex if it exists.' if self.parentNode is None: return defaultVector3 if self.parentNode.xmlObject is None: return defaultVector3 if len(self.parentNode.xmlObject.vertexes) < 1: return defaultVector3 return self.parentNode.xmlObject.vertexes[-1] def getStrippedAttributesValue(self, keyString): 'Get the stripped attribute value if the length is at least one, otherwise return None.' if keyString in self.attributes: strippedAttributesValue = self.attributes[keyString].strip() if len(strippedAttributesValue) > 0: return strippedAttributesValue return None def getSubChildWithID( self, idReference ): 'Get the childNode which has the idReference.' for childNode in self.childNodes: if 'bf:id' in childNode.attributes: if childNode.attributes['bf:id'] == idReference: return childNode subChildWithID = childNode.getSubChildWithID( idReference ) if subChildWithID is not None: return subChildWithID return None def getTagKeys(self): 'Get stripped tag keys.' if 'tags' not in self.attributes: return [] tagKeys = [] tagString = self.attributes['tags'] if tagString.startswith('='): tagString = tagString[1 :] if tagString.startswith('['): tagString = tagString[1 :] if tagString.endswith(']'): tagString = tagString[: -1] for tagWord in tagString.split(','): tagKey = tagWord.strip() if tagKey != '': tagKeys.append(tagKey) return tagKeys def getTextContent(self): 'Get the text from the child nodes.' if len(self.childNodes) == 0: return '' firstNode = self.childNodes[0] if firstNode.nodeType == 3: return firstNode.textContent return '' def getValueByKey( self, key ): 'Get value by the key.' if key in evaluate.globalElementValueDictionary: return evaluate.globalElementValueDictionary[key](self) if key in self.attributes: return evaluate.getEvaluatedLinkValue(self, self.attributes[key]) return None def getVertexes(self): 'Get the vertexes.' if self.xmlObject is None: return [] return self.xmlObject.getVertexes() def getXMLProcessor(self): 'Get the xmlProcessor.' return self.getDocumentElement().xmlProcessor def linkObject(self, xmlObject): 'Link self to xmlObject and add xmlObject to archivableObjects.' self.xmlObject = xmlObject self.xmlObject.elementNode = self self.parentNode.xmlObject.archivableObjects.append(self.xmlObject) def printAllVariables(self): 'Print all variables.' print('attributes') print(self.attributes) print('childNodes') print(self.childNodes) print('localName') print(self.localName) print('parentNode') print(self.parentNode.getNodeName()) print('text') print(self.getTextContent()) print('xmlObject') print(self.xmlObject) print('') def printAllVariablesRoot(self): 'Print all variables and the document element variables.' self.printAllVariables() documentElement = self.getDocumentElement() if documentElement is not None: print('') print('Root variables:') documentElement.printAllVariables() def removeChildNodesFromIDNameParent(self): 'Remove the childNodes from the id and name dictionaries and the childNodes.' childNodesCopy = self.childNodes[:] for childNode in childNodesCopy: childNode.removeFromIDNameParent() def removeFromIDNameParent(self): 'Remove this from the id and name dictionaries and the childNodes of the parentNode.' self.removeChildNodesFromIDNameParent() idKey = self.getStrippedAttributesValue('id') if idKey is not None: idDictionary = self.getOwnerDocument().idDictionary idKey = self.getImportNameChain() + idKey if idKey in idDictionary: del idDictionary[idKey] nameKey = self.getStrippedAttributesValue('name') if nameKey is not None: euclidean.removeElementFromListTable(self, self.getImportNameChain() + nameKey, self.getOwnerDocument().nameDictionary) for tagKey in self.getTagKeys(): euclidean.removeElementFromListTable(self, tagKey, self.getOwnerDocument().tagDictionary) if self.parentNode is not None: self.parentNode.childNodes.remove(self) def setParentAddToChildNodes(self, parentNode): 'Set the parentNode and add this to its childNodes.' self.parentNode = parentNode if self.parentNode is not None: self.parentNode.childNodes.append(self) def setTextContent(self, textContent=''): 'Get the text from the child nodes.' if len(self.childNodes) == 0: self.childNodes.append(TextNode(self, textContent)) return firstNode = self.childNodes[0] if firstNode.nodeType == 3: firstNode.textContent = textContent self.childNodes.append(TextNode(self, textContent)) nodeName = property(getNodeName) nodeType = property(getNodeType) ownerDocument = property(getOwnerDocument) textContent = property(getTextContent) class ElementReadMonad: 'A monad to read the attributes of the ElementNode tag.' def __init__(self, elementNode): 'Initialize.' self.elementNode = elementNode def getNextMonad(self, character): 'Get the next monad.' if character.isspace(): return self if character == '/': self.elementNode.appendSelfToParent() return ElementEndMonad(self.elementNode.parentNode) if character == '>': self.elementNode.appendSelfToParent() return TextMonad(self.elementNode) return KeyMonad(character, self.elementNode) class KeyMonad: 'A monad to set the key of an attribute of an ElementNode.' def __init__(self, character, elementNode): 'Initialize.' self.input = cStringIO.StringIO() self.input.write(character) self.elementNode = elementNode def getNextMonad(self, character): 'Get the next monad.' if character == '=': return ValueMonad(self.elementNode, self.input.getvalue().strip()) self.input.write(character) return self class OpenChooseMonad(ElementEndMonad): 'A monad to choose the next monad.' def getNextMonad(self, character): 'Get the next monad.' if character.isspace(): return self if character == '?': input = cStringIO.StringIO() input.write('<?') return DocumentTypeMonad(input, self.parentNode) if character == '/': return ElementEndMonad(self.parentNode.parentNode) return ElementLocalNameMonad(character, self.parentNode) class OpenMonad(ElementEndMonad): 'A monad to handle the open tag character.' def getNextMonad(self, character): 'Get the next monad.' if character == '<': return OpenChooseMonad(self.parentNode) return self class TextMonad: 'A monad to handle the open tag character and set the text.' def __init__(self, parentNode): 'Initialize.' self.input = cStringIO.StringIO() self.parentNode = parentNode def getNextMonad(self, character): 'Get the next monad.' if character == '<': inputString = self.input.getvalue().strip() if len(inputString) > 0: self.parentNode.childNodes.append(TextNode(self.parentNode, inputString)) return OpenChooseMonad(self.parentNode) self.input.write(character) return self class TextNode(CDATASectionNode): 'A text node.' def addXML(self, depth, output): 'Add xml for this text node.' pass def getCopyShallow(self, attributes=None): 'Copy the node and set its parentNode.' return TextNode(self.parentNode, self.textContent) def getNodeName(self): 'Get the node name.' return '#text' def getNodeType(self): 'Get the node type.' return 3 nodeName = property(getNodeName) nodeType = property(getNodeType) class ValueMonad: 'A monad to set the value of an attribute of an ElementNode.' def __init__(self, elementNode, key): 'Initialize.' self.elementNode = elementNode self.input = cStringIO.StringIO() self.key = key self.quoteCharacter = None def getNextMonad(self, character): 'Get the next monad.' if self.quoteCharacter is None: if character == '"' or character == "'": self.quoteCharacter = character return self if self.quoteCharacter == character: self.elementNode.attributes[self.key] = self.input.getvalue() return ElementReadMonad(self.elementNode) self.input.write(character) return self
print("구구단 몇단을 계산할까요?") number = input() print("구구단 " + number + "단을 계산합니다") for i in range(1,10): result = int(number)*i print (number, "X", i, "=", result) # + 사용시 int값과 str값을 연산할수 없다는 오류가 나옴!
str = "I love you" reverse = "" for char in str: # str의 첫번째 인덱스 부터 char에 대입 reverse = char + reverse # reverse의 첫번째 인덱스값이 밀려나면서 계속 대입됨 # "I" -> " I" -> "l I" -> "ol I"..... print (reverse)
''' Leetcode - 887. Super Egg Drop Time complexity - O(K*N) space complexity - O(K*N) Approach - DP 1) First, we need to create Trys+1 and k+1 matrix 2) At each cell we need to find maximum number of floors required for x trys and y eggs. 3) At particular cell when we reach >= N floors then we stop it. 4) In the end we need to return trys. ''' class Solution: def superEggDrop(self, K: int, N: int) -> int: dp=[[0 for _ in range(K+1)] for _ in range (N+1)] trys=0 while dp[trys][K]<N: trys+=1 for egg in range(1,K+1): dp[trys][egg]=1+dp[trys-1][egg-1]+dp[trys-1][egg] return trys
""" Python File Open The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file: "r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists In addition you can specify if the file should be handled as binary or text mode "t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images) """ #To open a file for reading it is enough to specify the name of the file: #Because "r" for read, and "t" for text are the default values, you do not need to specify them. #Note: Make sure the file exist, or else you will get an error. f = open("demofile.txt") #The open() function returns a file object, #which has a read() method for reading the content of the file: f = open("demofile.txt", "r") print(f.read()) #By default the read() method returns the whole text, #but you can also specify how many character you want to return: #Return the 5 first characters of the file: f = open("demofile.txt", "r") print(f.read(5)) #You can return one line by using the readline() method: #Read one line of the file: f = open("demofile.txt", "r") print(f.readline()) #By looping through the lines of the file, you can read the whole file, #line by line: #Loop through the file line by line: f = open("demofile.txt", "r") for x in f: print(x) """ Write to an Existing File To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content """ #Open the file "demofile.txt" and append content to the file: f = open("demofile.txt", "a") f.write("Now the file has one more line!") #Open the file "demofile.txt" and overwrite the content: f = open("demofile.txt", "w") f.write("Woops! I have deleted the content!") """ Create a New File To create a new file in Python, use the open() method, with one of the following parameters: "x" - Create - will create a file, returns an error if the file exist "a" - Append - will create a file if the specified file does not exist "w" - Write - will create a file if the specified file does not exist """ #Create a file called "myfile.txt": #f = open("myfile.txt", "x") #Create a new file if it does not exist: f = open("myfile.txt", "w")
# Filename: samanthasjw_p01q02.py # Name: Samantha Siau Jing Wen # Description: Input radius and length of a cylinder and computes its volume # Prompt user for radius in m radius = float(input("Enter radius of cylinder in m: ")) # Prompt user for length in m length = float(input("Enter length of cylinder in m: ")) # Define pi from math import pi # Compute area area = radius*radius*pi # Compute volume volume = area*length # Display result #print("{0:20s} {1:.20f} {2:3s}".format("Volume of cylinder: ", volume, "m^3")) print("{0:20s} {1:.2f} {2:3s}".format("Volume of cylinder: ", volume, "m^3")) #Sam put in the decimals up to 1 place or 2 places. The truncation in the # format is quite severe as it could be .9 or .1. # marks = 4/5
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carrying = 0 result = ListNode(0) temp = result while l1 is not None or l2 is not None: x = 0 y = 0 if l1 is not None: x = l1.val l1 = l1.next if l2 is not None: y = l2.val l2 = l2.next num = x + y + carrying if num >= 10: carrying = 1 num = num - 10 else: carrying = 0 temp.next = ListNode(num) temp = temp.next if carrying > 0: temp.next = ListNode(carrying) return result.next
import random def clear_output(): print('\n' * 50) # Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation. The first item in the list is a throwaway. def display_board(board): print(board[1] + '|' + board[2] + '|' + board[3]) print('-----') print(board[4] + '|' + board[5] + '|' + board[6]) print('-----') print(board[7] + '|' + board[8] + '|' + board[9]) # Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. Think about using while loops to continually ask until you get a correct answer. def player_input(): marker = '' while not (marker == 'X' or marker == 'O'): marker = input('Player 1 - please choose a marker (X or O): ').upper() if marker == 'X': return ('#', 'X', 'O') else: return ('#', 'O', 'X') # Step 3: Write a function that takes in the board list object, a marker ('X' or 'O'), and a desired position (number 1-9) and assigns it to the board. def place_marker(board, marker, position): board[position] = marker return board # Step 4: Write a function that takes in a board and a mark (X or O) and then checks to see if that mark has won. def win_check(board, mark): return ((board[1] == mark and board[2] == mark and board[3] == mark) or # across top (board[4] == mark and board[5] == mark and board[6] == mark) or # across middle (board[7] == mark and board[8] == mark and board[9] == mark) or # across bottom (board[1] == mark and board[4] == mark and board[7] == mark) or # down left (board[2] == mark and board[5] == mark and board[8] == mark) or # down middle (board[3] == mark and board[6] == mark and board[9] == mark) or # down right (board[1] == mark and board[5] == mark and board[9] == mark) or # diagonal (board[3] == mark and board[5] == mark and board[7] == mark)) # diagonal # Step 5: Write a function that uses the random module to randomly decide which player goes first. You may want to lookup random.randint() Return a string of which player went first. def choose_first(): return random.randint(1,2) # Step 6: Write a function that returns a boolean indicating whether a space on the board is freely available. def space_check(board, position): return board[position] == ' ' # Step 7: Write a function that checks if the board is full and returns a boolean value. True if full, False otherwise. def full_board_check(board): for i in range(1,10): if (space_check(board, i)): return False return True # Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if it's a free position. If it is, then return the position for later use. def player_choice(board): next = 0 while next not in range(1,10) or not space_check(board, next): temp = input('Please select your next position (1-9): ') try: next = int(temp) except ValueError: next = 0 return next # Step 9: Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again. def replay(): return input('Do you want to play again? (Yes or No): ').lower() == 'yes'
#!/usr/bin/env python # Charley Schaefer, University of York, 2020 # CLUSTER DETECTION - conditional dilation algorithm # > scan elements of 2D binary matrix # > find a 'seed' (a matrix element with value 1) # > dilate the seed to find 4-connected matrix elements # (referred to as a cluster) # get_cluster_list: # get list with seed locations # and size of associated clusters # get_cluster: # get coordinates of all matrix elements # belonging to the same cluster # select_largest_cluster: # read matrix and create binary matrix with ones # only at the location of the largest cluster # analyse_cluster: # get size of cluster, mean xy position, and std xy position import sys import numpy as np import math #from decimal import Decimal def get_cluster_list(matrix): M=len(matrix) N=len(matrix[0]) analysed=np.zeros([M,N], int) # keep track of what matrix entries are analysed clusters=np.empty((0,3), int) Nclusters=0 for i in range(M): for j in range(N): if ((analysed[i,j]==0) & (matrix[i,j]>0)): # New cluster analysed[i,j]=1 Nclusters+=1 clustersize=1; nn_list=np.empty((0,2), int); Nnn=0 # length of nn_list # get neighbour sites if (j>0): k=i; l=j-1; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( j<N-1 ): k=i; l=j+1; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( i>0 ): k=i-1; l=j; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( i<M-1 ): k=i+1; l=j; if (analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; # analyse neighbours while (Nnn>0): # analyse neighbours m=nn_list[Nnn-1,0]; # analyse neighbour n=nn_list[Nnn-1,1]; # analyse neighbour nn_list=np.delete( nn_list, Nnn-1, axis=0) ; Nnn=Nnn-1; if ( analysed[m,n]!=1): analysed[m,n]=1; if ( matrix[m,n]>0): # new element in cluster clustersize=clustersize+1; # Get new neighbours # get neighbour sites if ( n>0 ): k=m; l=n-1; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( n<N-1 ): k=m; l=n+1; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( m>0 ): k=m-1; n=j; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( m<M-1 ): k=m+1; n=j; if (analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; # end while loop: cluster completed clusters=np.append(clusters, [[i,j,clustersize]], axis=0) return clusters def get_cluster(matrix, seed): i=seed[0] j=seed[1] M=len(matrix) N=len(matrix[0]) analysed=np.zeros([M,N], int) # keep track of what matrix entries are analysed cluster=np.empty((0,2), int) # will contain coordinates if ((analysed[i,j]==0) & (matrix[i,j]>0)): # New cluster analysed[i,j]=1 cluster= np.append(cluster, [[i,j]], axis=0); nn_list=np.empty((0,2), int); Nnn=0 # length of nn_list # get neighbour sites if (j>0): k=i; l=j-1; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( j<N-1 ): k=i; l=j+1; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( i>0 ): k=i-1; l=j; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( i<M-1 ): k=i+1; l=j; if (analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; # analyse neighbours while (Nnn>0): # analyse neighbours m=nn_list[Nnn-1,0]; # analyse neighbour n=nn_list[Nnn-1,1]; # analyse neighbour nn_list=np.delete( nn_list, Nnn-1, axis=0) ; Nnn=Nnn-1; if ( analysed[m,n]!=1): analysed[m,n]=1; if ( matrix[m,n]>0): # new element in cluster cluster=np.append(cluster, [[m,n]], axis=0) # Get new neighbours # get neighbour sites if ( n>0 ): k=m; l=n-1; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( n<N-1 ): k=m; l=n+1; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( m>0 ): k=m-1; n=j; if ( analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; if ( m<M-1 ): k=m+1; n=j; if (analysed[k,l]==0): nn_list=np.append(nn_list, [[k,l]], axis=0); Nnn=Nnn+1; # end while loop: cluster completed return cluster def select_largest_cluster(matrix_in): # Detect clusters clusters=get_cluster_list(matrix_in) Nclusters=len(clusters) # Get largest cluster max_cluster_size = max(clusters[:,2]) max_index = np.argmax(clusters[:,2]) seed=[clusters[max_index,0], clusters[max_index,1]] cluster=get_cluster(matrix_in, seed) cluster_size=len(cluster) matrix_out=np.zeros([len(matrix_in), len(matrix_in[0])]) for i in range(cluster_size): matrix_out[cluster[i,0],cluster[i,1]]=1 return matrix_out def analyse_cluster(matrix): M=len(matrix); N=len(matrix[0]); cluster_size=0 ; xi=0 ; yi=0 # mean position for i in range(M): for j in range(N): if (matrix[i][j]==1): xi+=i yi+=j cluster_size=cluster_size+1 # cluster size xi=xi/cluster_size yi=yi/cluster_size xistd=0; yistd=0; # standard deviation for i in range(M): for j in range(N): if (matrix[i][j]==1): xistd+=(i-xi)**2 yistd+=(j-yi)**2 xistd=np.sqrt(xistd/cluster_size) yistd=np.sqrt(yistd/cluster_size) arr=[cluster_size, xi, xistd, yi, yistd] return arr
''' Never give file name similar to module name. eg. numpy,array,pandas,matlab,List,etc. numpy: 1.It is extended version of array. 2.It is use for do complex numeric calculation like matrix operation 3.numpy library is written in C language 4.It is use in data science To install numpy: pip3 install numpy (windows powershell (windows icon>R_click>select windows powershell)) To install in pycharm: setting>project>project interpreter> + > numpy > install ''' import numpy as np val = np.array([1, 2, 6, 8]) val1 = np.array([1, 2, 6, 8]) a = val + val1 b = val - val1 c = val * val1 d = val / val1 e = val // val1 print(a) print(b) print(c) print(d) print(e) val2=np.array([[1,2],[4,9]]) val3=np.array([[1,2],[4,9]]) d=val2+val3 print(d) #To find dimension of array eg. 1dimensional,2dimensional print(val.shape) print(val1.shape) val4=np.zeros([5,5]) print(val4) val5=np.ones([5,5]) print(val5)
''' Abstraction: To hide some data. We only declare function in abstract class and we can define it when needed. Interface: It Only contain all function with declaration. Difference between Abstract Class and Interface: Abstract Class Interface constructor support not supported object support not supported function define and undefine function only define function ''' class person: def showProf(self): pass class Doctor(person): def showProf(self): print("Doctor") class Engineer(person): def showProf(self): print("Engineering") a=Engineer() a.showProf() b=Doctor() b.showProf()
''' Loops: Some lines of code we want use repeately upto certain condition then we use loop. Ther are 3 types of loops: 1.while 2.for 3.do while. While loop: Syntax: ................code.............. initialization while (condition): #() is optional but in standard way is to not use () ................code.......... ................code.......... ................code.......... increament/decrement ..........code.................... Drawback: We have initialize one variable. continue in not working in while. ''' #To print 1 to 10 number print("Start!!!") a=1 while a<11: print(a) a=a+1 #a++/a-- is not supported in python. print("End!!!") #To break a while loop at specific condition print("Start!!!") a=1 while a<=10: if a==8: break else: print(a) a=a+1 print("End!!!") #To pass specific condition in while loop print("Start!!!") a=1 while a<=10: if a==8: pass else: print(a) a=a+1 print("End!!!")
#To check odd and even Number a=int(input("Enter number to check whether it is ood or even")) if a%2==0: print("Number is Even") else: print("Number is odd")
##Python class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ length = len(matrix) for i in range(int(length/2)): matrix[i],matrix[length-1-i] = matrix[length-1-i],matrix[i] for m in range(length): for n in range(m): matrix[m][n],matrix[n][m] = matrix[n][m],matrix[m][n] ##C++ class Solution { public: void rotate(vector<vector<int>>& matrix) { if (!matrix.size()) return; const int N = matrix.size(); for (int i = 0; i < N; i ++) { for (int j = 0; j < N / 2; j ++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[i][N - j - 1]; matrix[i][N - j - 1] = tmp; } } for (int i = 0; i < N; i ++) { for (int j = 0; j < N - i; j ++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[N - j - 1][N - i - 1]; matrix[N - j - 1][N - i - 1] = tmp; } } } }; --------------------- 作者:负雪明烛 来源:CSDN 原文:https://blog.csdn.net/fuxuemingzhu/article/details/79451733 版权声明:本文为博主原创文章,转载请附上博文链接!
#https://leetcode.com/problems/super-ugly-number/discuss/169815/Python-DP-solution-beats-93.7-extremely-detailed-explanation class Solution: """ @param n: a positive integer @param primes: the given prime list @return: the nth super ugly number """ def nthSuperUglyNumber(self, n, primes): # write your code here size = len(primes) ugly,dp,index,ugly_nums = 1,[1],[0]*size,[1]*size for i in range(1,n): #compute possibly ugly numbers for j in range(0,size): if ugly_nums[j] == ugly: ugly_nums[j] = dp[index[j]]*primes[j] index[j] += 1 #get the min ugly = min(ugly_nums) dp.append(ugly) return dp[-1]
''' Created on Aug 17, 2019 @author: amitbatajoo ''' # # from chatterbot import ChatBot # from chatterbot.trainers import ChatterBotCorpusTrainer # # bot = ChatBot('MyChand') # bot.set_trainer(cha) # # conversation=open('chats.txt').readlines() # bot.train(conversation) # # while True: # message = input('You:') # if message.strip()!= 'Bye': # reply = bot.get_response(message) # print('ChatBot:',reply) # if message.strip()=='Bye': # print('ChatBot:Bye') # break from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot('Ron Obvious') # Create a new trainer for the chatbot trainer = ChatterBotCorpusTrainer(chatbot) # Train the chatbot based on the english corpus trainer.train("chatterbot.corpus.english") # Get a response to an input statement print(chatbot.get_response("Hello, how are you today?"))
#!/usr/bin/python def printMax(a, b): if a > b: print(a, 'is max') elif a == b: print(a, 'is equal to ', b) else: print(b, 'is max') #printMax(3,4) a = int(input('a:')) b = int(input('b:')) printMax(a, b) x = 50 def func(): global x print('x is',x) x = 2 print('Change x to',x) func() print('x is still', x)
def game_of_life_generator(seed): game = GameOfLife(seed) while True: yield game.tick() class GameOfLife(object): def __init__(self, seed): self.alive_cells = seed def tick(self): self.alive_cells = set.union(self.survivors(), self.births()) return self.alive_cells def survivors(self): survivors = [cell for cell in self.alive_cells if len(self.live_neighbours(cell)) in [2, 3]] return set(survivors) def live_neighbours(self, cell): live_neighbours = [neighbour for neighbour in neighbours(cell) if neighbour in self.alive_cells] return set(live_neighbours) def births(self): births = [candidate for candidate in self.birth_candidates() if len(self.live_neighbours(candidate)) == 3] return set(births) def birth_candidates(self): dead_with_one_live_neighbour = [self.dead_neighbours(cell) for cell in self.alive_cells] if not dead_with_one_live_neighbour: return set() return set.union(*dead_with_one_live_neighbour) def dead_neighbours(self, cell): dead_neighbours = [neighbour for neighbour in neighbours(cell) if neighbour not in self.alive_cells] return set(dead_neighbours) def neighbours(cell): deltas = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] x, y = cell return [(x+dx, y+dy) for (dx, dy) in deltas] def test_GameOfLife_tick(): seed = set() game = GameOfLife(seed) next_generation = game.tick() assert next_generation == set() def test_GameOfLife_tick_with_one_death(): seed = set([(0, 0)]) game = GameOfLife(seed) game.tick() assert game.alive_cells == set() def test_GameOfLife_tick_with_a_survival(): """ stable foursome .**. .**. """ seed = set([(1, 0), (2, 0), (1, 1), (2, 1)]) game = GameOfLife(seed) assert game.tick() == seed def test_GameOfLife_live_neighbours_with_no_live_neighbours(): """ .*. """ live_neighbours = GameOfLife(set([(1, 0)])).live_neighbours((1, 0)) assert live_neighbours == set() def test_GameOfLife_live_neighbours_with_one_live_neighbour(): """ .**. """ live_neighbours = GameOfLife(set([(1, 0), (2, 0)])).live_neighbours((1, 0)) assert live_neighbours == set([(2, 0)]) def test_GameOfLife_births(): """ .* ** """ seed = set([(1, 0), (0, 1), (1, 1)]) game = GameOfLife(seed) assert game.births() == set([(0, 0)]) def test_GameOfLife_birth_candidates(): """ *. """ seed = set([(0, 0)]) game = GameOfLife(seed) candidates = game.birth_candidates() assert len(candidates) == 8 assert candidates == set(neighbours((0, 0))) def test_neighbours_at_origin(): my_neighbours = neighbours((0, 0)) assert len(my_neighbours) == 8 assert (0, 0) not in my_neighbours def test_neighbours(): my_neighbours = neighbours((1, 0)) assert len(my_neighbours) == 8 assert (1, 0) not in my_neighbours assert (0, 0) in my_neighbours assert (0, 1) in my_neighbours assert (-1, 0) not in my_neighbours def test_blinker_several_generations(): """ blinker: ..... .***. ..... -> ..*.. ..*.. ..*.. """ seed = set([(1, 1), (2, 1), (3, 1)]) game = game_of_life_generator(seed) assert game.next() == set([(2, 0), (2, 1), (2, 2)]) assert game.next() == set([(1, 1), (2, 1), (3, 1)]) def test_generations(): seed = set() game = game_of_life_generator(seed) assert game.next() == set()
# -------------------------------------------------------------------------- # Simple web server route that serves database information from buspatrol.db # By Hajrudin Satrovic # -------------------------------------------------------------------------- import sqlite3 import sys from flask import Flask, jsonify, request from flask_restful import Api, Resource app = Flask(__name__) api = Api(app) class Challenge(Resource): def get(self, name): """Opens the database 'buspatrol.db' to retrieve information from and returns the job description and job title of the user requested.""" try: conn = sqlite3.connect('buspatrol.db') cur = conn.cursor() cur.execute('SELECT TITLE FROM JOBS, USERS WHERE USERS.NAME == ? AND USERS.job == JOBS.id', (name,)) #Here, we write the query to get the job title of the user that has been requested and then execute it. #The attribute 'job' from USERS has the same values when corresponded to 'id' from JOBS for each user. title = cur.fetchall() cur.execute('SELECT DESCRIPTION FROM JOBS, USERS WHERE USERS.NAME == ? AND USERS.job == JOBS.id', (name,)) #Similarly, we write the query to retrieve the job description of the user that has been requested and then execute it. description = cur.fetchall() except lite.Error as e: print ("Error {}:".format(e.args[0])) sys.exit(1) return jsonify( {"job_title": title, "job_description":description}) conn.close() api.add_resource(Challenge, "/users/<name>") if __name__ == "__main__": app.run(debug=True)
test_integer = 1000 print(test_integer + 10) # 加算(足し算) print(test_integer - 10) # 減算(引き算) print(test_integer * 10) # 乗算(掛け算) print(test_integer / 10) # 除算(割り算) test_str = '1000' print(int(test_str) + 1000) test_str = '1000.5' print(float(test_str) + 1000) test_float = .5 print(test_float) test_complex = 1000 + 5j print(test_complex) print(test_complex.real) print(test_complex.imag)
value = 3 if value == 1: print('valueの値は1です') elif value == 2: print('valueの値は2です') elif value == 3: print('valueの値は3です') else: print('該当する値はありません') value_1 = 'python' value_2 = 'sgt' if value_1 == 'Python': pass elif value_1 == 'python' and value_2 == 'sgt': print('2番目の条件式がTrue') elif value_1 == "SGT" or value_2 == "PYTHON": print('3番目の条件式がTrue') value_1 = 'python' value_2 = 'sgt' if value_1 == 'Python': pass elif value_1 == 'python' and value_2 == 'sgt': print('2番目の条件式がTrue') elif value_1 == "SGT" or value_2 == "PYTHON": print('3番目の条件式がTrue') is_male = True is_tall = True if is_male and is_tall: print("You are a tall male") elif is_male and not(is_tall): print("You are a short male") elif not(is_male) and is_tall: print("You are not a male but are tall") else: print("You neither not male or not tall or both")