text
stringlengths
37
1.41M
class Task: type = "none" def __init__(self, description): self.description = description # this method lets you use print() with Task objects def __str__(self): if self.type == "none": return self.description elif self.type == "due": return self.description + " " + "Due on " + self.date def setDueDate(self, date): self.type = "due" self.date = date
def is_prime(n): '''is_prime(n) -> boolean returns True if n is prime, False otherwise''' if n < 2: return False for divisor in range(2,int(n**0.5)+1): if n % divisor == 0: return False return True def sum_of_prime_cubes(n): '''sum_of_prime_cubes(n) -> int returns sum of cubes of all primes <=n''' return sum([n**3 for n in range (n+1) if is_prime (n)]) # test case print(sum_of_prime_cubes(10)) # should be 503 print(sum_of_prime_cubes(200)) # this is your answer
def encipher_fence(plaintext,numRails): '''encipher_fence(plaintext,numRails) -> str encodes plaintext using the railfence cipher numRails is the number of rails''' textList = list (plaintext) #maps each character to a number index = 0 railNum = 0 cipher = "" railLists = [] #create a list with lists for each rail for i in range (numRails): railLists.append ([]) for o in range (numRails): #for each rail in the dictionary for p in range (len(textList)): #for each character in the sentence railLists [o].append (textList [index]) #append that value to the corresponding rail index += numRails if index > (len (textList)-1): #if the index goes out of range, it's time to restart at the next rail railNum+=1 index = railNum break #so it goes to the outer loop index = len(railLists)-1 for k in range(len(railLists)): #add the strings backwards cipher += "".join (railLists [index]) index -=1 return cipher def decipher_fence(ciphertext,numRails): '''decipher_fence(ciphertext,numRails) -> str returns decoding of ciphertext using railfence cipher with numRails rails''' cipherList = list (ciphertext) #assign each char to a number and split it into the according rails rails = [] #list with all our rails divisor = numRails #variable to divide by the number of rails left to remove for i in range (numRails): #for each rail if i == numRails-1: #on the final iteration, append the whole list rails.append (cipherList) break rails.append (cipherList[:((len (cipherList)//divisor))]) #remove each rail and assign it to a list del cipherList[:((len (cipherList)//divisor))] divisor -= 1 rails = rails [::-1] #reverse the rails into the original order railIndex = 0 charIndex = 0 originalText = "" for p in range (len(ciphertext)): #for each character, add the matching indexes of each list into a string try: #in case charIndex goes out of range originalText += rails [railIndex][charIndex] except IndexError: break railIndex +=1 if railIndex >= numRails: #if it goes out of the rail range railIndex = 0 charIndex +=1 #goes to next character after first char of each list is obtained if charIndex >= len (rails [railIndex]): #if the index is out of range, stop break return originalText def decode_text(ciphertext,wordfilename): '''decode_text(ciphertext,wordfilename) -> str attempts to decode ciphertext using railfence cipher wordfilename is a file with a list of valid words''' outFile = open (wordfilename, 'r') outFile = outFile.readlines () points = 0 #determine which text has the greater number of words maxPoints = 0 decoded = "" #text to return for rails in range (11): #decode the text with a different rail each time text = decipher_fence (ciphertext, rails) text = text.split () #split text into individual words for word in text: #for every word, check if it's in dictionary if word + "\n" in outFile: #if it's in file, increase the amount of points the word has points +=1 if points > maxPoints: #found word with highest amount of words maxPoints = points decoded = " ".join (text) points = 0 #reset points return decoded outFile.close () # test cases # enciphering print(encipher_fence("abcdefghi", 3)) # should print: cfibehadg print(encipher_fence("This is a test.", 2)) # should print: hsi etTi sats. print(encipher_fence("This is a test.", 3)) # should print: iiae.h ttTss s print(encipher_fence("Happy birthday to you!", 4)) # should print: pidtopbh ya ty !Hyraou # deciphering print(decipher_fence("hsi etTi sats.",2)) # should print: This is a test. print(decipher_fence("iiae.h ttTss s",3)) # should print: This is a test. print(decipher_fence("pidtopbh ya ty !Hyraou",4)) # should print: Happy birthday to you! # decoding print(decode_text(" cr pvtl eibnxmo yghu wou rezotqkofjsehad", 'wordlist.txt')) # should print: the quick brown fox jumps over the lazy dog print(decode_text("unt S.frynPs aPiosse Aa'lgn lt noncIniha ", 'wordlist.txt')) # should print... we'll let you find out!
def get_base_number(num,base): '''get_base_number(num,base) -> int returns value of num as a base number in the given base''' num = list (num) #convert into a list and reverse since the values of the bases are reversed num = num [::-1] #always start counting from last digit anyways index = 0 #traverse through list values result = 0 for i in range (len(num)): result += int(num [index]) * (base**index) #for example, the last digit is just 1x2^0 index +=1 return result # test cases print(get_base_number('10011',2)) # should be 19 print(get_base_number('3202',5)) # should be 427 print(get_base_number('611023',7))
num1 = input("num1:") num2 = input("num2:") num3 = input("num3:") max_num = 0 if num1>num2: max_num = num1 if max_num > num3: print("max number is ",max_num) else: print("max number is ",num3) else: max_num = num2 if max_num > num3: print("max number is ",max_num) else: print("max number is",num3) #if num1>num2: # max_num= num1 # if max_num > num3: # print("Max NUM is",max_num) # else: # print("Max NUM is",num3) #else: # max_num = num2 # if max_num > num3: # print("Max NUM is",max_num) # else: # print("Max NUM is",num3) #num1 = input("Please input num1: ") #num2 = input("Please input num2: ") #num3 = input("Please input num3: ") #min_num = 0 #if num1 < num2: # min_num = num1 # if min_num > num3: # print("The min_num is ",num3) # else: # print("The min_num is ",min_num) #else: # if num2 < num3: # print("The min_num is ",min_num) # else: # print("The min_num is ",num3)
# メッセージボックスの作成 import tkinter import tkinter.messagebox # messageboxモジュールをインポート # ボタンをクリックした時の関数を定義 def c_btn(): tkinter.messagebox.showinfo("情報", "再起動します……") # showinfo()命令でメッセージボックスを表示 # tkinter.messagebox.showwarning("危険!", "おしまいDETH!") # showwarningで警告表示 window = tkinter.Tk() window.title("メッセージボックス") window.geometry("800x600") # ボタンの作成 btn = tkinter.Button(text="絶対に押さないでください", command=c_btn) btn.pack() window.mainloop()
# 自爆スイッチの配置 import tkinter def click_btn(): jibaku["text"] = "押してしまった……" window = tkinter.Tk() window.title("自爆スイッチ") window.geometry("1000x550") jibaku = tkinter.Button(window, text="自爆スイッチ〜絶対に押すな!と言われたら押したくなっちゃうよね〜", font=("Toppan Bunkyu Mincho", 24), command=click_btn) jibaku.place(x=60, y=200) window.mainloop()
class ListNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next def insert_after(self, value): """This makes me think about some sort of while loop. where we are searching for the actual value at that point we can break the link and set up a new, connection 1 3 5 6 9 10 and i have a new value 7 i want to set the 7 after the 6. """ new_node = ListNode(value) current = self next_node = current.next prev_node = current.prev new_node.set_prev(current)#current node becomes the previous for new node new_node.set_next(next_node) # next node is now next for the new node current.next = new_node # some way go find the value. def insert_before(self, value): new_node = ListNode(value) # create new node new_node.prev = self.prev new_node.next = self self.prev = new_node def delete(self): if self.prev is not None: self.prev.next = self.next if self.next is not None: self.next.prev = self.prev def get_value(self): return self.value def get_next(self): return self.next def set_next(self, new_next): self.next = new_next def get_prev(self): return self.prev def set_prev(self, new_prev): self.prev = new_prev class DoublyLinkedList: def __init__(self, node=None): self.head = node self.tail = node def add_to_head(self, value): if self.head is None: self.head = ListNode(value) #if there is no head self.tail = ListNode(value) #go ahead and set the list up else: new_node = ListNode(value) #create the node. new_node.set_next(self.head) # going in front of head so current head next. self.head.set_prev(new_node) # new_node will come before head so setting prev. self.head = new_node #making the head change def remove_from_head(self): node_to_remove = self if self.head == None: return self.head else: returning = self.head.get_value() self.head = self.head.get_next() if self.head is None: self.tail = None return returning # get previous on head isn't needed because this isn't set # up in a circular setting it was then if head was removed previous # would be the tail so a connect with the new head and tail would have to be made. # because it is not a circle connection all other connections should be set. def add_to_tail(self, value): new_node = ListNode(value) # create the node. new_node.set_prev(self.tail) # came before so prev has to be set up. self.tail.set_next(new_node) # set self.tail next to new node. # new node doesn't have a new next because it is now the tail. if self.head is None and self.tail is None: self.tail = new_node self.head = new_node else: self.tail = new_node def remove_from_tail(self): node_to_remove = self.tail previous_node = self.tail.get_prev() previous_node.set_next(None)# cutting the link off from the current tail. self.tail = previous_node # making the change. return node_to_remove.get_value() def move_to_front(self, node): # current_head = self.head # grab the current head # traveling_node_next = node.get_next() # traveling_node_prev = node.get_prev() # #What this is doing is allowing for a new connection to be set up # #I can then connect these to nodes together to keep the chain. # # 1 2 3 # # we are grabing 2 # # 1 3 # # we now need 1 and 3 to be connected. # if traveling_node_next: # traveling_node_prev.set_next(traveling_node_next) #1>>3next # if traveling_node_prev: # traveling_node_next.set_prev(traveling_node_prev) # 1<<3previous # #connected 1 >><<3 # #now set the node up to the front. # self.head = node # node.set_next(current_head) # connect so 1 2 3 4 5 take 4 # # we already connected 3 and 5 on lines 90 and 91. # # now take the 4 and connect it 4 >> to 1(what was the head) # current_head.set_prev(node) # #now connect what was the head to the new head 4 <<< 1 node.delete self.add_to_head(node.value) def move_to_end(self, node): # #very similar to move_to_front only in reverse # current_tail = self.tail # traveling_node_next = node.get_next() # traveling_node_prev = node.get_prev() # # 1 2 3 4 5 6 # # 3 is being moved to the end # # current_tail = 6 node = 3 # # traveling_node_prev = 2 # #traveling_node_next = 4 # if traveling_node_next : # traveling_node_prev.set_next(traveling_node_next) #2>>4next # if traveling_node_prev: # traveling_node_next.set_prev(traveling_node_prev) # 2<<4previous # #connected 2 >><<4 # #now set the node up to the end. # self.tail = node # node.set_prev(current_tail) # connect so 1 2 3 4 5 6 take 3 # # we already connected 2 to 4 on lines 112 and 113 # # now take the 3 and connect it to <<< the 6(what was the tail) # current_tail.set_next(node) # # now connect what was the tail to the new tail 6>>>3 node.delete() self.add_to_tail(node.value) def delete(self, node): """ just have to link out the node take the connect of the node and connect so left connection and right connection just needs to be connected. """ #I believe this is similar to the functions move only we won't be reconnecting the node. node_next = node.get_next() node_prev = node.get_prev() # 1 2 3 node = 2 # now we have to connect 1 and 3 node_prev.set_next(node_next) node_next.set_prev(node_prev)
#!python3 """ 给定一个字符串,找出不含有重复字符的最长子串的长度。 示例: 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。 给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。 给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串。 """ class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ sub_long_str = '' for i, item_i in enumerate(s): sub_str = item_i for j, item_j in enumerate(s[i + 1:]): if item_j not in sub_str: sub_str += item_j else: break if len(sub_str) > len(sub_long_str): sub_long_str = sub_str return len(sub_long_str) if __name__ == '__main__': # s = "abcabcbb" # s = "bbbbb" s = "pwwkew" # s = 'c' res = Solution().lengthOfLongestSubstring(s) print(res)
from card_deck import * from blackjack_book import * class PlayerHand: """ Represents a hand of cards and is used to calculate the value of the hand. """ def __init__(self, cards=[]): """ :param cards: List of Card objects """ self.cards = cards self.soft = False self.value = self.value_cards() def reset_hand(self): self.cards = [] self.soft = False self.value = self.value_cards() def receive_card(self, deck): """ Add cards to the hand from a deck and update the hand value :param deck: The deck to take a card from :return: """ self.cards.append(deck.draw_card()) self.value = self.value_cards() def check_split(self): """ Make sure that the cards are the same type to split """ if len(self.cards) != 2: return False else: return ((len(self.cards) == 2) & (self.cards[0].c_type == self.cards[1].c_type)) def value_cards(self): """ Calculate the value of the hand based on the card-types :return: value fo the hand """ val = 0 for card in self.cards: if card.c_type in ('K', 'Q', 'J'): val += 10 elif card.c_type == 'A': continue else: val += int(card.c_type) for card in self.cards: if card.c_type == 'A': if val + 11 < 22: val += 11 self.soft = True else: val += 1 self.soft = False self.value = val return val def print_cards(self): return "Hand: " + ", ".join([card.c_type for card in self.cards]) class Player: """ Track the hands of the player and the moves to make on each hand. """ def __init__(self, hand=None, name='Player'): self.hands = [] self.name = name if hand is None: self.set_hands() else: self.input_hand(hand) def set_hands(self): """ Set the players hand. """ self.hands.append(PlayerHand([])) def input_hand(self, hand): """ Set the players hand as the input hand. """ self.hands.append(hand) def reset_hands(self): """ Re-set the player's hand. """ self.hands = [PlayerHand([])] def split_hand(self, hand_idx): """ Split a hand where the cards value matches. :param hand_idx: The index of the hand to split """ new_hand = PlayerHand([self.hands[hand_idx].cards.pop()]) self.hands.insert(hand_idx + 1, new_hand) self.hands[hand_idx].value_cards() def play(self, dealer_show, deck): """ Go through each hand and make moves by the book :param dealer_show: The dealers car that is showing :param deck: The deck to pull from """ # Track total hands in order to increment for splits total_hands = len(self.hands) xx = 0 while xx < total_hands: hand = self.hands[xx] done = 0 hand_value = hand.value while (done == 0) & (hand_value < 21): # Always hit after a split print('Player Value: {} {}'.format(hand_value, hand.print_cards())) move = input("What is your move?") # Execute the moves if move == 'hit': print('Player Hit!') hand.receive_card(deck) elif move == 'stand': print('Player Stand!') done = 1 elif move == 'double': print('Player Double!') # todo: disallowed double after first move hand.receive_card(deck) done = 1 elif move == 'split': print('Player Split!') self.split_hand(xx) total_hands += 1 elif move == 'surrender': print('Player Surrender!') hand.reset_hand() done = 1 hand_value = hand.value xx += 1 # Clear cards on a bust if hand.value > 21: print('Player Bust! Value: {} {}'.format(hand_value, hand.print_cards())) hand.reset_hand() return 0 class NPC(Player): """ Track the hand of the dealer and the moves to make on the hand """ def __init__(self, name='NPC'): super().__init__(name=name) def play(self, dealer_show, deck): """ Go through each hand and make moves by the book :param dealer_show: The dealers car that is showing :param deck: The deck to pull from """ # Track total hands in order to increment for splits total_hands = len(self.hands) xx = 0 while xx < total_hands: hand = self.hands[xx] done = 0 hand_value = hand.value while (done == 0) & (hand_value < 21): # Always hit after a split if len(hand.cards) == 1: move = 'hit' # Use split book when cards match elif hand.check_split() and (hand_value not in (10, 20)): c_type = hand.cards[0].c_type move = BOOK_KEY[SPLIT_BOOK[c_type][dealer_show-2]] # Soft book when there is a soft ace elif hand.soft: move = BOOK_KEY[SOFT_BOOK[hand_value][dealer_show-2]] # Hard book for all other moves else: move = BOOK_KEY[HARD_BOOK[hand_value][dealer_show-2]] # Execute the moves if move == 'hit': print('NPC Hit! Value: {} {}'.format(hand_value, hand.print_cards())) hand.receive_card(deck) elif move == 'stand': print('NPC Stand! Value: {} {}'.format(hand_value, hand.print_cards())) done = 1 elif move == 'double': print('NPC Double! Value: {} {}'.format(hand_value, hand.print_cards())) hand.receive_card(deck) done = 1 elif move == 'split': print('NPC Split! Value: {} {}'.format(hand_value, hand.print_cards())) self.split_hand(xx) total_hands += 1 elif move == 'surrender': print('NPC Surrender! Value: {} {}'.format(hand_value, hand.print_cards())) hand.reset_hand() done = 1 hand_value = hand.value xx += 1 # Clear cards on a bust if hand.value > 21: print('NPC Bust! Value: {} {}'.format(hand_value, hand.print_cards())) hand.reset_hand() return 0 class Dealer(Player): """ Track the hand of the dealer and the moves to make on the hand """ def __init__(self): super().__init__(name='Dealer') def play(self, dealer_show, deck): """ The dealer makes moves based on the hand. :param deck: the deck to pull from :return: """ for xx in range(len(self.hands)): hand = self.hands[xx] done = 0 hand_value = hand.value while (done == 0) & (hand_value < 21): # todo: Implement soft 17 hit if hand_value < 17: print('Dealer Hit! {}'.format(hand_value)) hand.receive_card(deck) else: print('Dealer Stand! {}'.format(hand_value)) done = 1 hand_value = hand.value # Hand cleared when dealer bust if hand.value > 21: print('Dealer Bust! {}'.format(hand_value)) hand.reset_hand() class Blackjack: """ The game of blackjack. Tracks all players in the game and the deck of cards """ def __init__(self, players=[Player()], deck_count=1): self.players = players self.players.append(Dealer()) assert deck_count > 0 self.deck = Deck(deck_count) def full_round(self): """ Run through an entire round of NPCs playing by the book """ self.deal() self.hand_values() self.play() self.results() self.clear_hands() def deal(self): """ Deal two cards to each player and dealer in order """ if len(self.deck.cards) < (len(self.players) * 5): print('Shuffling!') self.deck.init_deck() print('Dealing Cards') for xx in range(2): for player in self.players: for hand in player.hands: hand.receive_card(self.deck) def hand_values(self): """ Print values of hands for NPCs but not the dealer """ # todo: print the cards that the players have for xx in range(len(self.players) - 1): player = self.players[xx] for hand in player.hands: print("Value: " + str(hand.value) + " " + hand.print_cards()) def play(self): """ Each player makes the moves for their hands """ dealer_card = self.players[-1].hands[0].cards[0] d_card_val = show_card_value(dealer_card) print('Dealer showing {}'.format(dealer_card.c_type)) print('\n') for player in self.players: player.play(d_card_val, self.deck) print('\n') def results(self): """ Print the results for remaining hands at end of the round """ dealer_hand = self.players[-1].hands[0].value if dealer_hand == 0: print('Dealer busted!') else: print('Dealer Stand with {}'.format(dealer_hand)) for xx in range(len(self.players) - 1): player = self.players[xx] for hand in player.hands: hand_value = hand.value if hand_value == 0: continue else: if hand_value > 21: print('{} bust! {}'.format(player.name, hand_value)) elif hand_value == dealer_hand: print('{} push! {}'.format(player.name, hand_value)) elif hand_value < dealer_hand: print('{} loss! {}'.format(player.name, hand_value)) elif hand_value > dealer_hand: print('{} win! {}'.format(player.name, hand_value)) else: print('!!! Forgot something !!!') print('\n') def clear_hands(self): for player in self.players: player.reset_hands() def show_card_value(card): if card.c_type in ('K', 'Q', 'J'): return 10 elif card.c_type == 'A': return 11 else: return int(card.c_type) game = Blackjack([Player(), NPC()], 2) for xx in range(1000): game.full_round()
#! python3 # email_control.py # Author: Michael Koundouros """ Write a program that checks an email account every 15 minutes for any instructions you email it and executes those instructions automatically. For example, BitTorrent is a peer-to-peer downloading system. Using free BitTorrent software such as qBittorrent, you can download large media files on your home computer. If you email the program a ( completely legal, not at all piratical) BitTorrent link, the program will eventually check its email, find this message, extract the link, and then launch qBittorrent to start downloading the file. This way, you can have your home computer begin downloads while you’re away, and the (completely legal, not at all piratical) download can be finished by the time you return home. Chapter 17 covers how to launch programs on your computer using the subprocess.Popen() function. For example, the following call would launch the qBittorrent program, along with a torrent file: qbProcess = subprocess.Popen(['C:\\Program Files (x86)\\qBittorrent\\ qbittorrent.exe', 'shakespeare_complete_works.torrent']) Of course, you’ll want the program to make sure the emails come from you. In particular, you might want to require that the emails contain a password, since it is fairly trivial for hackers to fake a “from” address in emails. The program should delete the emails it finds so that it doesn’t repeat instructions every time it checks the email account. As an extra feature, have the program email or text you a confirmation every time it executes a command. Since you won’t be sitting in front of the computer that is running the program, it’s a good idea to use the logging functions (see Chapter 11) to write a text file log that you can check if errors come up. qBittorrent (as well as other BitTorrent applications) has a feature where it can quit automatically after the download completes. Chapter 17 explains how you can determine when a launched application has quit with the wait() method for Popen objects. The wait() method call will block until qBittorrent has stopped, and then your program can email or text you a notification that the download has completed. --- I prefer not to install qbittorent, therefore program uses requests module to download links sent via email. The file downloaded from the email link is a zip archive which is automatically extracted. """ import imapclient import pyzmail import bs4 import requests import time import ezgmail import traceback import subprocess from pathlib import Path imap_obj = imapclient.IMAPClient('imap.gmail.com', ssl=True) mypass = input('Password:') imap_obj.login('[email protected]', mypass) starttime = time.time() while True: print('Fetching Inbox...') imap_obj.select_folder('INBOX', readonly=False) UIDS = imap_obj.search(['ALL']) for UID in UIDS: # Fetch each email raw_message = imap_obj.fetch(UID, ['BODY[]']) message = pyzmail.PyzMessage.factory(raw_message[UID][b'BODY[]']) print(f'Fetching email with subject: {message.get_subject()}') # Find all emails with special subject if message.get_subject() == 're: email downloader': if message.html_part is not None: html_message = message.html_part.get_payload() email_soup = bs4.BeautifulSoup(html_message, 'html.parser') # retrieve message using bs4, check password and extract all download links if email_soup.select('div')[0].getText().find('pass: swordfish'): for tag in email_soup('a'): url = tag['href'] filename = Path(url).name # If errors arise, record them in log file try: print(f"Downloading: {url}") res = requests.get(url) res.raise_for_status() with open(filename, 'wb') as download: for chunk in res.iter_content(100000): download.write(chunk) print(f'Unzipping file: {filename}') unzip_file = subprocess.Popen(f'C:\\Program Files\\Bandizip\\Bandizip.exe x -y {filename}') unzip_file.wait() print('Sending confirmation email...') ezgmail.send('[email protected]', 'Re: email downloader', f"File Downloaded: {url}") except: print('Writing error log...') error_log = open('error_info.log', 'a+') error_log.write(traceback.format_exc()) error_log.close() imap_obj.delete_messages(UID) print('Done!') time.sleep(900.0 - ((time.time() - starttime) % 900.0)) # Program sleeps for 15 minutes and repeats
#! python3 # convert_sheets.py # Author: Michael Koundouros """ You can use Google Sheets to convert a spreadsheet file into other formats. Write a script that passes a submitted file to upload(). Once the spreadsheet has uploaded to Google Sheets, download it using downloadAsExcel(), downloadAsODS(), and other such functions to create a copy of the spreadsheet in these other formats. usage: convert_sheets.py file """ import sys import ezsheets from pathlib import Path def convert_xlsx(file): # Function converts excel spreadsheets to ods, csv, tsv & pdf formats # formats csv, tsv & pdf are applicable to the first sheet only. sheet = ezsheets.upload(str(file)) sheet.downloadAsExcel(f'{file.stem}.xlsx') sheet.downloadAsODS(f'{file.stem}.ods') sheet.downloadAsCSV(f'{file.stem}.csv') sheet.downloadAsTSV(f'{file.stem}.tsv') sheet.downloadAsPDF(f'{file.stem}.pdf') return def main(): # Make a list of command line arguments, omitting the [0] element # which is the script itself. args = sys.argv[1:] if len(args) != 1: print('usage: convert_sheets.py file') sys.exit(1) else: file = Path(args[0]) print(f'Converting file {file}') convert_xlsx(file) print('Done!') if __name__ == '__main__': main()
""" Ref: Chapter 5 - Dictionaries Ref: Automate the Boring Stuff with Python, Al Sweigart, 2nd Ed., 2019 Author: Michael Koundouros July 2020 Here is a short program that counts the number of occurrences of each letter in a string. """ import pprint message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for character in message: count.setdefault(character, 0) count[character] = count[character] + 1 pprint.pprint(count)
""" Ref: Chapter 7 - Regular Expressions Ref: Automate the Boring Stuff with Python, Al Sweigart, 2nd Ed., 2019 Author: Michael Koundouros July 2020 Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero. The regular expression doesn’t have to detect correct days for each month or for leap years; it will accept nonexistent dates like 31/02/2020 or 31/04/2021. Then store these strings into variables named month, day, and year, and write additional code that can detect if it is a valid date. April, June, September, and November have 30 days, February has 28 days, and the rest of the months have 31 days. February has 29 days in leap years. Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400. Note how this calculation makes it impossible to make a reasonably sized regular expression that can detect a valid date. """ import re def test_date(date): match = re.search(r'([0-2][1-9]|[1-3][01])/(0[1-9]|1[0-2])/([12][0-9][0-9][0-9])', date) ''' Regex to search for date in format DD/MM/YYYY groups are enclosed in (), character class in [] and | is the OR operator DD first group: [0-2][1-9]|[1-3][01]) match first digit as 0-2 AND second digit as 1-9 OR match first digit as 1-3 AND second digit as 0 or 1 / MM second group: 0[1-9]|1[0-2] match third digit a 0 and fourth digit as 1-9 OR match third digit a 1 and fourth digit as 0-2 / YYYY third group: [12][0-9][0-9][0-9] match fifth digit as 1 or 2 match sixth digit as 1-9 match seventh digit as 1-9 match eighth digit as 1-9 ''' # Assign date search match to variables if match is None: print('No date found!') else: day = int(match.group(1)) month = int(match.group(2)) year = int(match.group(3)) # Check if days in month are valid if year % 4 == 0 and (year % 400 == 0 or year % 100 != 0): leapyeardays = 29 else: leapyeardays = 28 daysinmonth = {1: 31, 2: leapyeardays, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} if day <= daysinmonth[month]: print('Valid Date') else: print('Date is not valid') return date_string = 'Test if 29/02/2000 is a valid date' # leap year because 1900 % 4 =0 AND 1900 % 400 = 0 print(date_string) test_date(date_string) date_string = 'Test if 29/02/1900 is a valid date' # not a leap year because 1900 % 400 > 0 print(date_string) test_date(date_string) date_string = 'Test if 29/02/2020 is a valid date' # leap year beacause 1900 % 4 =0 AND 1900 % 400 = 0 print(date_string) test_date(date_string)
#! python3 # xl2csv.py # Author: Michael Koundouros """ Excel can save a spreadsheet to a CSV file with a few mouse clicks, but if you had to convert hundreds of Excel files to CSVs, it would take hours of clicking. Using the openpyxl module from Chapter 12, write a program that reads all the Excel files in the current working directory and outputs them as CSV files. A single Excel file might contain multiple sheets; you’ll have to create one CSV file per sheet. The filenames of the CSV files should be <excel filename>_<sheet title>.csv, where <excel filename> is the filename of the Excel file without the file extension (for example, 'spam_data', not 'spam_data.xlsx') and <sheet title> is the string from the Worksheet object’s title variable. """ import openpyxl import csv from pathlib import Path # Convert all spreadsheets in current working directory to csv files xl_list = list(Path.cwd().glob('*.xlsx')) print('Writing files...') for xl_file in xl_list: wb = openpyxl.load_workbook(xl_file) for sheet in wb.sheetnames: ws = wb[sheet] output_csv = open(f'{xl_file.stem}_{sheet}.csv', 'w', newline='') print(f'{xl_file.stem}_{sheet}.csv') for row_num in range(1, ws.max_row + 1): row_data = [] for cell in range(0, ws.max_column): cell_data = ws[row_num][cell].value row_data.append(cell_data) output_writer = csv.writer(output_csv) output_writer.writerow(row_data) output_csv.close() print('Done!')
#! python3 # auto_unsubscriber.py # Author: Michael Koundouros """ Write a program that scans through your email account, finds all the unsubscribe links in all your emails, and automatically opens them in a browser. This program will have to log in to your email provider’s IMAP server and download all of your emails. You can use Beautiful Soup (covered in Chapter 12) to check for any instance where the word unsubscribe occurs within an HTML link tag. Once you have a list of these URLs, you can use webbrowser.open() to automatically open all of these links in a browser. """ import imapclient import pyzmail import bs4 import webbrowser imap_obj = imapclient.IMAPClient('imap.gmail.com', ssl=True) mypass = input('Password:') imap_obj.login('[email protected]', mypass) print('Fetching Inbox...') imap_obj.select_folder('INBOX', readonly=True) UIDS = imap_obj.search(['ALL']) # For each email UID, fetch the message, parse the html with bs4, select all <a> tags, then # for each <a> tag that has 'unsubscribe', open the web browser with the tag href link. for UID in UIDS: raw_message = imap_obj.fetch(UID, ['BODY[]']) message = pyzmail.PyzMessage.factory(raw_message[UID][b'BODY[]']) print(f'Fetching email with subject: {message.get_subject()}') if message.html_part != None: html_message = message.html_part.get_payload() email_soup = bs4.BeautifulSoup(html_message, 'html.parser') for tag in email_soup('a'): if tag.get_text() == 'unsubscribe': print(f"Opening unsubscribe link: {tag['href']}") webbrowser.open(tag['href'], new=2) print('Done!')
import turtle t = turtle.Pen() def draw_star(size,point): for x in range(1,point): t.forward(size) t.left(95)
#CS486 Assignment #2, Q2: TSP using Simulated Annealing #Justin Franchetto #20375706 #Purpose: Using Simulated Annealing, solve TSP for a given instance import sys, string, math, datetime, itertools from TSPObjects import * from random import * #GenerateRandomTour: Generate an initial random solution #for this problem instance. def GenerateRandomTour(cities): remainingCities = cities start = remainingCities.pop(0) tour = Tour() tour.AddCity(start) for i in range(0, len(remainingCities)): nextCity = randint(0, len(remainingCities)-1) tour.AddCity(remainingCities.pop(nextCity)) tour.AddCity(start) return tour #Accept: Accept a given move if it creates a better path with 100% probability, #otherwise accept it with a probability according to Boltzmann distribution def Accept(currentTour, newTour, temperature): delta = newTour.cost-currentTour.cost if (delta <= 0): return True else: probability = math.exp(-delta/temperature) return probability > uniform(0, 1) return False #Generate the cooling schedule, using the Fitzpatrick method def CoolingSchedule(startingTemperature, coolingRate): schedule = [] t = startingTemperature while t > 1: schedule.append(t) t = t*coolingRate return schedule #GenerateRandomSwapMoves: Generates all size k combinations of random indicies def GenerateRandomSwapMoves(tourLength, k): #This is for k vericies such that we can find their neighbour (2-opt) indicies = list(range(1, tourLength-1)) return [list(x) for x in itertools.combinations(indicies,k)] #Execute Simulated Annealing on a set of cities, using the given starting temperature and cooling rate. def SimulatedAnnealing(cities, initialTemperature, coolingRate, k): numberCities = len(cities) #Generate an initial tour, randomly currentTour = GenerateRandomTour(cities) bestTour = Tour(currentTour) print("Initial: " + '\n' + str(currentTour)) if numberCities <= 2: return bestTour #Create a cooling schedule coolingSchedule = CoolingSchedule(initialTemperature, coolingRate) temperature = initialTemperature #Generate all possible index swaps randomSwaps = GenerateRandomSwapMoves(len(currentTour.path), k) iterations = 0 for temperature in coolingSchedule: newTour = Tour(currentTour) #Random 2-swap move = randomSwaps[randint(0, len(randomSwaps)-1)] newTour.SwapCities(move) #Should we accept this move? if(Accept(currentTour, newTour, temperature)): currentTour = Tour(newTour) #Update best tour if needed if (currentTour < bestTour): bestTour = Tour(currentTour) iterations += 1 if (iterations % 50000 == 0): print(currentTour.cost) return bestTour def SetupAnnealing(cities): initialTemperature = 15000 coolingRate = 0.999985 tour = SimulatedAnnealing(cities, initialTemperature, coolingRate, 2) return tour def main(): if len(sys.argv) == 2: filename = sys.argv[1] #Compile a list of cities based on input data cities = ConstructCities(filename) starttime = datetime.datetime.now() tour = SetupAnnealing(cities) endtime = datetime.datetime.now() elapsedtime = (endtime - starttime).total_seconds() print('\n' + "Final: " + '\n' + str(tour)) print("Time: " + "{0:.4f}".format(elapsedtime) + " seconds") main()
from random import randint TITLE = "What number is missing in the progression?" def get_round(): sequence_step = randint(1, 10) sequence_start = randint(1, 50) hidden_position = randint(1, 10) return get_prog_data(sequence_start, sequence_step, hidden_position) def get_prog_data(start, step, hidden_position): next_number = start sequence = "" answer = "" sequence_count = 1 while sequence_count <= 10: if sequence_count == hidden_position: sequence += " .." answer = next_number else: sequence += f" {next_number}" next_number += step sequence_count += 1 return (sequence, str(answer))
""" Project for Week 4 of "Python Data Representations". Find differences in file contents. Be sure to read the project description page for further information about the expected behavior of the program. """ IDENTICAL = -1 def singleline_diff(line1, line2): """ Inputs: line1 - first single line string line2 - second single line string Output: Returns the index where the first difference between line1 and line2 occurs. Returns IDENTICAL if the two lines are the same. """ if len(line1)>= len(line2): len_min = len(line2) else: len_min = len(line1) for ind in range(0, len_min + 1): if line1[:ind + 1] == line2[:ind + 1]: continue else: return ind return IDENTICAL ##lin1 = "abcd" ##lin2 = "abcd" ##print(singleline_diff(lin1, lin2)) def singleline_diff_format(line1, line2, idx): """ Inputs: line1 - first single line string line2 - second single line string idx - index at which to indicate difference Output: Returns a three line formatted string showing the location of the first difference between line1 and line2. If either input line contains a newline or carriage return, then returns an empty string. If idx is not a valid index, then returns an empty string. """ if "\n" in line1 or "\r" in line1 or "\n" in line2 or "\r" in line2: return "" if idx > len(line1) or idx > len(line2) or idx < 0: return "" return str(line1 + "\n{}\n" + line2 + "\n").format("="*idx + "^") LIN1 = "abcd" LIN2 = "abcd" index = singleline_diff(LIN1, LIN2) print(singleline_diff_format(LIN1, LIN2, index)) def multiline_diff(lines1, lines2): """ Inputs: lines1 - list of single line strings lines2 - list of single line strings Output: Returns a tuple containing the line number (starting from 0) and the index in that line where the first difference between lines1 and lines2 occurs. Returns (IDENTICAL, IDENTICAL) if the two lists are the same. """ equal_lines = False if len(lines1)==len(lines2): len_min = len(lines1) equal_lines = True elif len(lines1) > len(lines2): len_min = len(lines2) else: len_min = len(lines1) for ind in range(0, len_min): #check each line diff_index = singleline_diff(lines1[ind], lines2[ind]) if diff_index == IDENTICAL: continue else: return ind, diff_index if equal_lines is True: return (IDENTICAL, IDENTICAL) else: return (len_min, 0) LISTS1 = ['here and now', 'now and then', 'up or down'] LISTS2 = ['here and now', 'now and then', 'up or down'] ##print(multiline_diff(LISTS1, LISTS2)) def get_file_lines(filename): """ Inputs: filename - name of file to read Output: Returns a list of lines from the file named filename. Each line will be a single line string with no newline ('\n') or return ('\r') characters. If the file does not exist or is not readable, then the behavior of this function is undefined. """ openfile = open(filename, "rt") lines =[] for line in openfile.readlines(): lines.append(line.strip()) ## print(lines) openfile.close() return lines def file_diff_format(filename1, filename2): """ Inputs: filename1 - name of first file filename2 - name of second file Output: Returns a four line string showing the location of the first difference between the two files named by the inputs. If the files are identical, the function instead returns the string "No differences\n". If either file does not exist or is not readable, then the behavior of this function is undefined. """ line_list1 = get_file_lines(filename1) line_list2 = get_file_lines(filename2) print(line_list1) print(line_list2) (error_line, error_idx) = multiline_diff(line_list1, line_list2) print(error_line, error_idx) if error_line == -1 and error_idx == -1: return "No differences\n" elif error_line != 0: return "Line {}\n".format(error_line) + \ singleline_diff_format\ (line_list1[error_line], line_list2[error_line], error_idx) elif error_line == 0 and line_list1 == []: return "Line {}\n".format(error_line) + \ singleline_diff_format\ ("", line_list2[error_line], error_idx) elif error_line == 0 and line_list2 == []: return "Line {}\n".format(error_line) + \ singleline_diff_format\ (line_list1[error_line], "", error_idx) else: return "Line {}\n".format(error_line) + \ singleline_diff_format\ (line_list1[error_line], line_list2[error_line], error_idx) ##filename = "file10.txt" file1 = "file1.txt" #input("Enter filename1: ") file2 = "file8.txt" #input("Enter filename2: ") print(file_diff_format(file1, file2))
import random from datetime import datetime from unit.unit import Unit class Soldier(Unit): """ Soldiers are units that have an additional property: Property | Range | Description _______________________________________________________ experience | [0-50] | Represents the soldier experience """ def __init__(self, health, name, attack_time=None, recharge=None): self.recharge = recharge self.health = health self.experience = 0 self.attack_time = attack_time self.name = name self.type = 'Soldier' def attack(self): return 0.5 * (1 + self.health/100) * random.randint(50 + self.experience, 100) / 100 def damage(self): damage = 0.05 + self.experience / 100 return damage @property def is_alive(self): return self.health > 0 @property def check_recharge(self): if self.attack_time: time_delta = self.attack_time - datetime.now() if time_delta.microseconds >= self.recharge: return True else: return False else: return True def recalculate_health(self): damage = self.damage() self.health = self.health - damage
# 1329. Sort the Matrix Diagonally class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: if not mat or not mat[0]: return mat n, m = len(mat), len(mat[0]) d = collections.defaultdict(list) for i, j in itertools.product(range(n), range(m)): d[i - j].append(mat[i][j]) for k in d: d[k].sort(reverse=True) for i, j in itertools.product(range(n), range(m)): mat[i][j] = d[i-j].pop() return mat
def frequencySort(self, s: str) -> str: c = Counter(s) s = '' for k ,v in reversed(sorted(c.items(), key=operator.itemgetter(1))): s += k*v return s
# 721. Accounts Merge from collections import defaultdict class Solution: def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: users = defaultdict(list) # Ω(N) for acc in accounts: users[acc[0]].append(set(acc[1:])) def join_rest(cur_set, set_list, seen): now_set = set(cur_set) for i, v in enumerate(set_list): if i in seen or cur_set.isdisjoint(v): continue now_set = now_set.union(v) seen.add(i) rest = join_rest(now_set, set_list, seen) now_set = now_set.union(rest) return now_set def union(set_list): seen = set() ans = [] for i in range(len(set_list)): if i in seen: continue seen.add(i) cur_set = set(set_list[i]) joined = join_rest(cur_set, set_list, seen) cur_set = cur_set.union(joined) ans.append(cur_set) return ans ans = [] for u, emails in users.items(): merged_emails = union(emails) for m_email in merged_emails: tmp = [u] + list(sorted(m_email)) ans.append(tmp) return ans
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root: TreeNode) -> bool: if not root: return True def trav(cur, minval, maxval): if not cur: return True if cur.val <= minval or cur.val >= maxval: return False return trav(cur.left, minval, cur.val) and trav(cur.right, cur.val, maxval) return trav(root, float('-inf'), float('inf'))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 285. Inorder Successor in BST class Solution: def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': def right_successor(cur): cur = cur.right while cur.left: cur = cur.left return cur def trav(cur, stk): if not cur: return None if cur.val == p.val: if cur.right: return right_successor(cur) while stk: top = stk.pop() if top.val > p.val: return top return None stk.append(cur) l = trav(cur.left, stk) if l: return l r = trav(cur.right, stk) if r: return r if stk: stk.pop() return None return trav(root, []) # [2,1,3] # 1 # [5,3,6,2,4,null,null,1] # 6
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # 141. Linked List Cycle class Solution: def hasCycle(self, head: ListNode) -> bool: walker, runner = head, head while runner: walker = walker.next if runner.next: runner = runner.next.next else: runner = None if walker and walker == runner: return True return False
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from heapq import heappush, heappop class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists: return None if not any(lists): return None heap = [] d = {} for ind, i in enumerate(lists): if not i: continue heappush(heap, (i.val, ind)) d[ind] = i head = ListNode(0) cur = head while heap: top = heappop(heap) ind = top[1] cur.next = d[ind] cur = cur.next if d[ind]: nxt = d[ind].next if nxt: heappush(heap, (nxt.val, ind)) d[ind] = nxt return head.next
# 1320. Minimum Distance to Type a Word Using Two Fingers class Solution: def minimumDistance(self, word: str) -> int: N = len(word) word = [*map(lambda x: ord(x) - ord('A'), word)] def distance(n1, n2): a, b = divmod(n1, 6) a2, b2 = divmod(n2, 6) return abs(a2-a) + abs(b2- b) @lru_cache(None) def rec(a, b, idx): if idx == N: return 0 ans = math.inf # Move first finger to cur location cost = 0 if a is not None: cost = distance(a, word[idx]) ans = min(ans, rec(word[idx], b, idx+1) + cost) cost = 0 if b is not None: cost = distance(b, word[idx]) ans = min(ans, rec(a, word[idx], idx+1) + cost) return ans return rec(None, None, 0)
class Solution: def angleClock(self, hour: int, minutes: int) -> float: minute_degree = 6 * minutes * 1.0 hour_degree = 30 * hour * 1.0 additional_hour_degree_from_minute = (minutes / 2) * 1.0 hour_degree += additional_hour_degree_from_minute return min(360 - abs(hour_degree - minute_degree), abs(hour_degree - minute_degree))
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode: n = TreeNode(val) if not root or val > root.val: n.left = root return n par = None cur = root while cur and cur.val > val: par = cur cur = cur.right child = par.right par.right = n n.left = child return root
from queue import SimpleQueue class Solution: def calculate(self, s: str) -> int: ss = '' for c in s: if c in '()+-': ss += ' ' + c + ' ' else: ss += c s = ss.split() num = [] operator = [] for c in s: if c.isnumeric(): if operator and operator[-1] in '+-': a = num.pop() b = int(c) op = operator.pop() if op == '+': num.append(a + b) else: num.append(a - b) else: num.append(int(c)) else: if c == ')': operator.pop() if operator and operator[-1] in '-+': if len(num) > 1: a = num.pop() b = num.pop() op = operator.pop() if op == '+': num.append(a + b) else: num.append(b - a) else: operator.append(c) return num[-1]
# Definition for Node. # class Node: # def __init__(self, val=0, left=None, right=None, random=None): # self.val = val # self.left = left # self.right = right # self.random = random # 1485. Clone Binary Tree With Random Pointer class Solution: def copyRandomBinaryTree(self, root: 'Node') -> 'NodeCopy': d = defaultdict(NodeCopy) d[None] = None def rec(cur): if not cur: return None c = d[cur] c.val = cur.val c.left = rec(cur.left) c.right = rec(cur.right) c.random = d[cur.random] return c return rec(root)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 979. Distribute Coins in Binary Tree class Solution: def distributeCoins(self, root: TreeNode) -> int: ans = 0 def post_order(cur): if not cur: return 0 l = post_order(cur.left) r = post_order(cur.right) nonlocal ans ans += abs(l) + abs(r) return cur.val + l + r - 1 post_order(root) return ans
# 1451. Rearrange Words in a Sentence class Solution: def arrangeWords(self, text: str) -> str: if not text: return text l = sorted([(len(w),i,w) for i, w in enumerate(text.split())]) return ' '.join([v[2] for v in l]).capitalize()
# 229. Majority Element II from collections import Counter class Solution: def majorityElement(self, nums: List[int]) -> List[int]: c = Counter() N = len(nums) for n in nums: c[n] += 1 if len(c) == 3: c -= Counter(c.keys()) return [n for n in c if nums.count(n) > N//3]
# 1472. Design Browser History class BrowserHistory: def __init__(self, homepage: str): self.arr = [homepage] self.cur = 0 def visit(self, url: str) -> None: self.arr = self.arr[:self.cur + 1] + [url] self.cur += 1 def back(self, steps: int) -> str: self.cur = max(0, self.cur - steps) return self.arr[self.cur] def forward(self, steps: int) -> str: self.cur = min(self.cur + steps, len(self.arr) - 1) return self.arr[self.cur] # Your BrowserHistory object will be instantiated and called as such: # obj = BrowserHistory(homepage) # obj.visit(url) # param_2 = obj.back(steps) # param_3 = obj.forward(steps)
""" author: Nishaoshan email:[email protected] time:2020-6-22 env:python3.6 socket,V负责界面显示 """ from socket import * class Client: def __init__(self, host="127.0.0.1", port=9999): self.host = host self.port = port self.sock = socket() self.name = "" def r(self): while True: try: name = input("请输入用户名:") if not name: print("输入有误,请重新输入--------------") continue while True: passwd1 = input("请输入密码:") if not passwd1: print("输入有误,请重新输入--------------") continue passwd2 = input("请再次确认密码:") if passwd1 != passwd2: print("两次密码输入不一致,请重新出入-----------") continue break self.sock.send(f"R {name} {passwd1}".encode()) response = self.sock.recv(1024).decode() if response == "ok": print("注册成功") self.name = name return "ok" elif response == "fail": print("注册失败,用户名有人用了,请更换") continue except KeyboardInterrupt: return "back" def l(self): while True: name = input("请输入用户名:") passwd = input("请输入密码:") if not name: print("用户名输入有误请重新输入---------") continue if not passwd: print("用户名输入有误请重新输入---------") self.sock.send(f"L {name} {passwd}".encode()) response = self.sock.recv(1024).decode() if response == "ok": print("登录成功") self.name = name return else: print("登录失败", response) def h(self): self.sock.send(f"H {self.name}".encode()) msg=self.sock.recv(1024).decode() if msg=="ok": while True: data = self.sock.recv(1024).decode() if data == "##": break print(data) else: print("没有记录,快去查询吧") def start(self): try: self.sock.connect((self.host, self.port)) except: print("请检查网络后重试!") return while True: self.func1() cmd = input("请输入指令:") if cmd == "登录": self.l() while True: self.func2() break elif cmd == "注册": msg = self.r() if msg == "ok": while True: choose = input("是否直接登录?(y/n)") if choose == "y": while True: self.func2() break break elif choose == "n": break else: print("输入有误,请重新输入-------") elif msg == "back": continue elif cmd == "退出": self.sock.send(b"E") return else: print("输入有误,请重新输入") def func1(self): print("=========== 界面1 ==============") print("***登录 注册 退出***") print("===============================") def func2(self): while True: print("=========== 界面2 =============") print("***查单词 历史记录 注销***") print("===============================") cmd = input("请输入指令:") if cmd == "查单词": self.q() elif cmd == "历史记录": self.h() elif cmd == "注销": return def q(self): while True: word = input("请输入单词:") if word == "##": break self.sock.send(f"Q {self.name} {word}".encode()) data = self.sock.recv(1024).decode() print(data) if __name__ == '__main__': Client().start()
""" 通过Pymsql操作mysql pip3 install pymysql CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8_bin NOT NULL, `password` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin AUTO_INCREMENT=1 ; """ import pymysql """ 创建mysql连接: cursorclass:定义返回结果的数据结构 """ conn = pymysql.connect(host="localhost",port=3306,user="root",password="123456",charset="utf8",db="demo",cursorclass=pymysql.cursors.DictCursor) # 插入 try: # Cursor类自动实现了__enter__ 和 __exit__方法 with conn.cursor() as cursor: sql = "insert into users(username,password) values('admin','123456')" cursor.execute(sql) conn.commit() except Exception as e: print(e) conn.rollback() finally: conn.close() # 查找 try: with conn.cursor() as cursor: sql = "select * from users" cursor.execute(sql) results = cursor.fetchall() print(results) """ [{'id': 1, 'username': 'admin', 'password': '123456'}] """ except Exception as e: print(e) finally: conn.close() # 更新 try: with conn.cursor() as cursor: sql = "update users set username='test' where id = 1" cursor.execute(sql) conn.commit() except Exception as e: print(e) conn.rollback() finally: conn.close() # 删除 try: with conn.cursor() as cursor: sql = "delete from users where username='test'" cursor.execute(sql) conn.commit() except Exception as e: print(e) conn.rollback() finally: conn.close()
print("""You enter a dark room with three doors. Do you go through door #1, door #2, or door #3?""") door = input("> ") if door == "1": print("There's a giant bear here eating pie.") print("What do you do?") print("1. Take his pie.") print("2. Try to run away without the bear chasing you.") bear = input("> ") if bear == "1": print("The bear eats your face off. Congrats.") elif bear == "2": print("The bear chases you down and eats your legs off for disturbing him. Congrats.") else: print(f"Well, doing {bear} is probably better.") print("Bear runs away.") elif door == "2": print("You stare into an endless abyss, as it pulls you in with it's force.") print("1. Walk into the abyss.") print("2. Blueberries.") print("3. Do nothing.") insanity = input("> ") if insanity == "1" or insanity == "2": print("Your body gets disintegrated by the abyss. Congrats.") else: print("The insanity rots your brain into a pool of muck. Congrats.") elif door == "3": print("You find yourself inside a log cabin.") print("What do you do?") print("1. Go outside.") print("2. Stay inside the cabin, look for food.") maple = input("> ") if maple == "1": print("The door locks behind you and you are now stranded in a forest outside the locked cabin. Congrats.") else: print("You find tons of food in the cabin, you stuff your face. Congrats.") else: print("You stumble around and fall on a knife and die. Congrats.")
# Hangman.py # The game of Hangman. You only get 6 guesses. Have fun! # Andrew Alonso # 3/12/2021 import re import random def getWord(): ''' Finds a random word from given textfile.''' word = (random.choice(open("wordsForHangman.txt","r").read().split())) word = word.lower() pregame(word) def pregame(word): ''' Gets variables needed for when the game has started. ''' chances = 6 # Number of incorrect choices allowed # How much char's are left to fill, & underscores of len(word) is result leftToFill = len(word) result = ['_'] * len(word) print(f''' ______ | | | | | ____|____ ''') # Removes commas brackets and quotes for printing res = str(result).replace(","," ").replace("["," ").replace("]","").replace("'","") print(f'{res}\n') # List of total letters used & list of incorrect letters used lettersUsed = [] incorrect = [] # Start game of Hangman start(result, word, leftToFill, lettersUsed, incorrect, chances) def start(res, word, leftToFill, charUsed, incorrect, c): ''' Starts the game of hangman. ''' userLetter = str(input(f'Enter a letter: ')) userLetter = userLetter.lower() # If incorrect input is entered. Ex: not a character, <1 input, >1 input pattern = re.compile("[a-z]+") if pattern.fullmatch(userLetter) is None: print('Type a letter that is a-z only.\n') start(res, word, leftToFill, charUsed, incorrect, c) elif len(userLetter) < 1: print('Type a letter a-z.\n') start(res, word, leftToFill, charUsed, incorrect, c) elif len(userLetter) > 1: print('Type only 1 letter at a time.\n') start(res, word, leftToFill, charUsed, incorrect, c) # Checks if character has already been used before for i in range(len(charUsed)): if userLetter == charUsed[i]: print(f'Letter already used! Pick a different letter.\n') start(res, word, leftToFill, charUsed, incorrect, c) counter = 0 # Counter used to check if letter was in the word for i in range(len(word)): # if user's letter is in the word if userLetter == word[i]: res[i] = word[i] counter += 1 leftToFill -= 1 # Add letter to list of chars used charUsed.append(userLetter) # print word outline result = str(res).replace(","," ").replace("["," ").replace("]","").replace("'","") print(f'{result}\n') # if letter not correct decrease chances if counter < 1: incorrect += userLetter c -= 1 # Draws hangman on each stage of where you're at in the game drawMan(c) # Incorrect letters shown after 1st incorrect attempt if len(incorrect) > 0: # Takes list turns to string to remove square brackets and quotes inc = str(incorrect).replace("[","").replace("]"," ").replace("'","") print(f'Incorrect letters: {inc}\n') # If game is won if leftToFill == 0: print(f'Congrats you won! You guessed the right word: {word}!\n') answer = str(input(f'Play again? y/yes OR n/no \n')) answer = answer.lower() retry(answer) # Else if game is lost elif c == 0: print(f'You lose! The correct word was: {word}\n') answer = str(input(f'Retry game? y/yes OR n/no \n')) answer = answer.lower() retry(answer) start(res, word, leftToFill, charUsed, incorrect, c) def drawMan(c): ''' Draws the hangman in text format during various stages of the game. ''' if c == 6: print(f''' ______ | | | | | ____|____ ''') elif c == 5: print(f''' ______ | | ( ) | | | ____|____ ''') elif c == 4: print(f''' ______ | | ( ) | | | | ____|____ ''') elif c == 3: print(f''' ______ | | ( ) | | | / | ____|____ ''') elif c == 2: print(f''' ______ | | ( ) | | | / \ | ____|____ ''') elif c == 1: print(f''' ______ | | ( ) | /| | / \ | ____|____ ''') else: print(f''' ______ | | ( ) | /|\ | / \ | ____|____ ''') def retry(answer): ''' Allows player to play another game if won or lost. ''' if answer == 'y' or answer == 'yes': print('') main() elif answer == 'n' or answer == 'no': raise SystemExit else: answer = str(input('\nIncorrect input. Type either: y, yes, or n, no.\n')) answer = answer.lower() retry(answer) def main(): ''' Prints welcome message and begins game of Hangman. ''' print("Welcome to Hangman!\nTry to guess the word!") getWord() main()
def iso_triangle(sy,blank_spc=5,draw=1): """ Objective : to draw a isosceles triangle Input parameters : sy -> symbol to be used to draw the triangle Approach : using recursion """ print(' '*blank_spc + sy*draw) if(blank_spc>0): iso_triangle(sy,blank_spc-1,draw+2) def main(): """ Objective : to draw a isosceles triangle Input parameters : sy -> symbol to be used to draw the triangle Approach : calling iso_triangle function """ sy = input("Enter the symbol to be used for drawing triangle : ") iso_triangle(sy) if __name__=="__main__": main() print("End program")
''' PYTHON VERSION 2.7.10 AUTHOR: YAN SHI UPDATED: October 9, 2016 PROMPT: Write a function or a program which returns or prints the nth Fibonacci number. Fn = Fn-1 + Fn-2 F0 = 0 and F1 = 1 ''' def fibonacci_numbers(number): f0, f1 = 0, 1 for i in range(number): f0, f1 = f1, f0 + f1 return f0 print "This program prints the nth Fibonacci number." number = input("What nth Fibonacci number are you looking for? ") output = fibonacci_numbers(number) print "The Fibonacci number is " + str(output) + "."
## Can build up a dict by starting with the the empty dict {} ## and storing key/value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' ## By default, iterating over a dict iterates over its keys. ## Note that the keys are in a random order. for key in dict: print key ## prints a g o ## Exactly the same as above for key in dict.keys(): print key ## Get the .keys() list: print dict.keys() ## ['a', 'o', 'g']
# -*- coding: utf-8 -*- """ Heuristieken: AmstelHaege Name: houseclass.py Autors: Stephan Kok, Stijn Buiteman and Tamme Thijs. Last modified: 27-05-2016 house class """ class House(): ''' The main house class. Contains the functions that all houses need. ''' def __init__(self): self.posx = False self.posy = False self.extra_vrijstand = False def get_type(self): return self.type def get_color(self): return self.housecolor def get_width(self): return self.width def get_heigth(self): return self.heigth def get_vrijstand(self): return self.vrijstand def get_cost(self): return self.cost def get_gain(self): return self.gain def get_value(self): return self.value def get_xpos(self): if(self.posx == False): raise("posx is not set!") return self.posx def get_ypos(self): if(self.posy == False): raise("posy is not set!") return self.posy def get_house_type(self): return self.house_type def get_extra_vrijstand(self): return self.extra_vrijstand def change_extra_vrijstand(self, vrijstand): self.extra_vrijstand = vrijstand def change_xpos(self, xpos): self.posx = xpos def change_ypos(self, ypos): self.posy = ypos class Eengezinswoning(House): ''' Child of House class. Has all property's of Eengezinswoning ''' def __init__(self): super(self.__class__, self).__init__() self.house_type = "eengezinswoning" self.width = 16 self.heigth = 16 self.vrijstand = 4 self.cost = 285000 self.gain = 0.03 self.value = 285000 self.housecolor = 20 def copy(self): """ Return a copy of hisself """ new = Eengezinswoning() new.change_extra_vrijstand(self.extra_vrijstand) new.change_xpos(self.posx) new.change_ypos(self.posy) return new class Bungalow(House): ''' Child of House class. Has all property's of Bungalow ''' def __init__(self): super(self.__class__, self).__init__() self.house_type = "bungalow" self.sort = 2 self.width = 16 self.heigth = 20 self.vrijstand = 6 self.cost = 399000 self.gain = 0.04 self.value = 399000 self.posx = False self.posy = False self.houseid = False self.housecolor = 15 def copy(self): """ Return a copy of hisself """ new = Bungalow() new.change_extra_vrijstand(self.extra_vrijstand) new.change_xpos(self.posx) new.change_ypos(self.posy) return new class Maison(House): ''' Child of House class. Has all property's of Maison ''' def __init__(self): super(self.__class__, self).__init__() self.house_type = "maison" self.sort = 3 self.width = 22 self.heigth = 21 self.vrijstand = 12 self.cost = 610000 self.gain = 0.06 self.value = 610000 self.housecolor = 10 def copy(self): """ Return a copy of hisself """ new = Maison() new.change_extra_vrijstand(self.extra_vrijstand) new.change_xpos(self.posx) new.change_ypos(self.posy) return new
# Project Euler Problem 47 # by Connor Halleck-Dube import time t0 = time.clock() from math import sqrt from primesmodule import isPrimeMR ## Solution 1: Generate primes alongside test # Number of prime factors of a number (distinct ones) def pfactors(num): count = 0 n = num for p in primes: if n%p == 0: count += 1 n //= p return count # Tests the x consecutive integers property, beginning with n def consecTest(n, x): for i in range(x): if (pfactors(n+i) < x): return False return True # iterate until you find one n = 1 primes = set() while True: if isPrimeMR(n): primes.add(n) if consecTest(n, 4): break n += 1 print(n) ## End Solution 1 t1 = time.clock() print("Solution 1 took:", round(t1-t0, 4), "seconds.")
import os def selectionSort(array): size = len(array) for i in range(0,size): aux = array[i] aux2 = i aux3 = array[i] for j in range(i+1,size): if(array[j] < aux ): aux = array[j] aux2 = j aux3 = array[i] array[i] = aux array[aux2] = aux3 return array def insertionSort(array): size = len(array) subarray= [] for i in range(0,size): subarray.append(array[i]) sizesub= len(subarray) for j in range(sizesub-1,0,-1): if(subarray[j] < subarray[j-1]): aux = subarray[j-1] subarray[j-1] = subarray[j] subarray[j] = aux else: break return subarray def readFile(fileName): f= open(fileName,"r+") contents = f.readlines() contents.pop(0) return contents for r,d,f in os.walk("instancias-num"): for file in f: array = readFile(os.path.join(r,file).replace("\\\\","\\")) for f in range(0,len(array)): array[f] = int(array[f].replace("\\n","")) array2 = array.copy() array3 = array.copy() array2.sort() array = selectionSort(array) assert array2 == array print(file + " selectionsorted") f = open(file + " selectionsorted","w+") for n in array: f.write(str(n) + "\n") f.close() array3 = insertionSort(array3) assert array2 == array3 print(file + " insertionsorted") f = open(file + " insertionsorted","w+") for n in array: f.write(str(n) + "\n") f.close()
import numpy as np import scipy as sc # My objective in writing this is to figure out how it works. def find_max_crossing_subarray(A, low, mid, high): left_sum = -10e5 summ = 0 max_left = 0 for i in range(mid,low-1,-1): summ += A[i] if summ > left_sum: left_sum = summ; max_left = i; print('lsum: %d, sum: %d, A[i]: %d, max_left: %d' % (left_sum, summ, A[i], max_left)) input('') right_sum = -10e5 summ = 0 max_right = 0 for j in range(mid+1, high): summ = summ + A[j] if (summ > right_sum): right_sum = summ max_right = j print('rsum: %d, sum: %d, A[i]: %d, max_left: %d' % (right_sum, summ, A[j], max_right)) input('') return max_left, max_right, left_sum + right_sum A = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7] ml, mr, s = find_max_crossing_subarray(A, 0, 7, len(A)-1)
#5. Write a program whose input is a list ListStr of strings, all strings being #of the same length m. Let n = len(ListStr) Write a program that works #as follows. #(a) Explores all i from 0 to m − 1. #(b) For each i, the program creates a string ColStr consisting of the i-th #symbols of the elements of ListStr. Formally, ColStr = ListStr[0][i]+ #ListStr[1][i] + . . . + ListStr[n − 1][i]. For instance, if ListStr = #[”abc”, ”ced”, ”beg”, ”ofg”] and i = 1 then ColStr should be ”beef”. #Then the program prints resulting string ColStr. def main(): ListStr=['abc', 'ced', 'beg', 'ofg'] mySolution = createString(ListStr,1) print(mySolution) def createString(A,n): newString = '' for i in range (len(A)): newString = newString + A[i][n] return newString main()
#Read two country data files, worldpop.txt and worldarea.txt. These files can be found on #Write a file world_pop_density.txt that contains country names and population densities with the #country names aligned left and the numbers aligned right. popData =open ( 'worldpop.txt','r') areaData =open ( 'worldarea.txt','r') popLines= popData.readlines() areaLines = areaData.readlines() worldPopDen = open ( 'worldPopDensity.txt','w') for i in range(len(popLines)): country= (''.join(list(filter(str.isidentifier, popLines[i])))) population=int(''.join(list(filter(str.isdigit, popLines[i])))) area=int(''.join(list(filter(str.isdigit, areaLines[i])))) if(area>0): popDen= population/area worldPopDen. write( country + ' ' + str(popDen)) else: popDen= 0 worldPopDen. write( country + ' ' + str(popDen))
# UZXVK undergraduate modules are classified by # their level and the number of credits. # In particular, there may be modules of levels 4,5,6 and modules # having 15 or 30 credits. # The *weight* of a module is computed as follows. # -The weight of any level 4 module is 0. # -The weight of a level 5 module worth 15 credits is 1. # -The weight of a level 5 module worth 30 credits is 2. # -The weihgt of a level 6 module worth 15 credits is 2. # -The weight of a level 6 module worth 30 credits is 4. # Suppose the mark of a student for a module is X. # Then the weighted mark for the module is X multiplied by the module weight. # a) Write a function whose arguments are: module mark, the number of credit for the module, # and module level. The function should return the module weight and the weighted mark. # (Note that the specified function returns two values) # b) Write a program whose input are three lists Marks,Levels, and Credits, all of the same length. # They represent marks, level, and credits for modules numbered 0,...,len(Marks)-1. # (The names of the modules are not important for this exercise). # In particular, Marks[i], Levels[i], and Credits[i] are respective marks, level, and credit for # module number i. # Please feel free to assume that the data in the list is valid i.e. that all the elements in the Marks # list are between 0 and 100, all the elements in the Levels list are 4,5, or 6, and all the elements in # the Credits list are 15 or 30. Moreover, you can create these lists fixed in the program instead # of asking the user to enter them. # Your program should do the following. # i) Calculate the total number of credits for the modules whose marks are 40 or more # (40 is the lowest passing mark for our undergraduate students). # ii) Calculate the total number of credits for the modules whose marks are 40 or more # and whose level is 6. # iii) If the result of i) is at least 360 *and* the result of ii) is at least 120 then # Compute the sum SW of all module weights and the sum SM of all weighted marks for modules as per i) # Obtain the weighted average mark AV=SM/SW. # Print "The student graduates with average", AV. # Otherwise (if the condition in the beginning of this item is not true), # print: "The students is not ready to graduate". # You should use the function in 3a) for this program. def main(): myweightedMark = calC_weightedMark(67, 15,6) print(myweightedMark) def calC_weightedMark(module_Mark, no_Of_Credit,module_Level): if(module_Level == 4): weight = 0 if(module_Level == 5 and no_Of_Credit ==15): weight = 1 if(module_Level == 5 and no_Of_Credit ==30): weight = 2 if(module_Level == 6 and no_Of_Credit ==15): weight = 2 if(module_Level == 6 and no_Of_Credit ==30): weight = 2 weighted_Mark= weight * module_Mark return ('The module weight is '+ str(weight) + ' and the weighted mark is '+ str(weighted_Mark) ) main()
#Please write a program that will produce a report where modules are classifed according #to the class of the received marks. In particular, the program should first print the lines #for modules whose mark is first class (>=70) then modules with a 2:1 mark (60-69) then modules #with a 2:2 mark (50-59), and then failed modules (mark<50). For instance, for the lists as above, #the printout should something like the following. Modules=["Calculus1","Calculus2","Calculus3","Programming1","Programming2","Programming3"] Marks=[50,80,35,70,62,15] #Modules with first class marks #Calculus2 80 #Programming1 70 #Modules with 2:1 marks #Programming2 62 #Modules with 2:2 marks #Calculus1 50 #Failed modules #Calculus3 35 #Programming3 15 for i in range (len(Modules)): if (Marks[i] > 69): print('Modules with first class marks:') print(Modules[i] + ' '+ str (Marks[i])) if (Marks[i] >59 and Marks[i] < 70): print('Modules with 2:1 marks:') print(Modules[i] + ' '+ str (Marks[i])) if (Marks[i] >49 and Marks[i] < 60): print('Modules with 2:2 marks:') print(Modules[i] + ' '+ str (Marks[i])) if (Marks[i] < 50 ): print('Failed modules:') print(Modules[i] + ' '+ str (Marks[i]))
#Write a program whose input is a table with integer elements. The program #should print “YES” if in each row the elements are all different and “NO” #otherwise. #Hint: Write a function whose argument is a list and which returns 1 if the #elements of this list are all different and 0 otherwise. Then apply this function #to each row of the input table def main(): A= [ [1,3,3,4], [22,15,33,45], [0,0,1,1], [1,1,2,2] ] result = checkElements(A) def checkElements(A): found=0 count = 0 for i in range(len(A)): for j in range(len(A[i])): if(A[i].count(A[i][j]) > 1 ): found=1 if(found ==1 ): print('No') else: print('Yes') main()
def main(): mynumber = int(input('Enter a number')) check = checkNum (mynumber) print(check) myListT= [4,15,12,7,9,18,11] checkMyList = checkList(myListT) print(checkMyList) #write a function that returns 1 if a number is between 10 and 20 and 0 otherwise. def checkNum (number): if(10 < number and number < 20): return 1 else: return 0 #Write a program whose input is a list and that uses the above function to count the number of #elements between 10 and 20 in the list. def checkList(myList): countNum=0 for i in range(len(myList)): if(checkNum (myList[i])==1 ): countNum = countNum + 1 return countNum main()
from math import exp def activate(weights, inputs): activation = weights[-1] for i in range(len(weights) - 1): activation += weights[i] * inputs[i] return activation def transfer(activation): return 1.0 / (1.0 + exp(-activation)) def forward_propagate(network, row): inputs = row for layer in network: new_inputs = [] print('layer: ', layer) for neuron in layer: print('checking neuron', neuron) activation = activate(neuron['weights'], inputs) neuron['output'] = transfer(activation) new_inputs.append(neuron['output']) inputs = new_inputs return inputs def transfer_derivative(output): return output * (1.0 - output) # Backpopagate error and store in neurons def backward_propagate_error(network, expected): for i in reversed(range(len(network))): layer = network[i] errors = list() if i != len(network) - 1: for j in range(len(layer)): error = 0.0 for neuron in network[i + 1]: error += (neuron['weights'][j] * neuron['delta']) errors.append(error) else: for j in range(len(layer)): neuron = layer[j] errors.append(expected[j] - neuron['output']) for j in range(len(layer)): neuron = layer[j] neuron['delta'] = errors[j] * transfer_derivative(neuron['output']) def main(): # Forward prop example network = [[{'weights': [0.13436424411240122, 0.8474337369372327, 0.763774618976614]}], [{'weights': [0.2550690257394217, 0.49543508709194095]}, {'weights': [0.4494910647887381, 0.651592972722763]}]] row = [1, 0, None] output = forward_propagate(network, row) # test backpropagation of error network = [ [{'output': 0.7105668883115941, 'weights': [0.13436424411240122, 0.8474337369372327, 0.763774618976614]}], [{'output': 0.6213859615555266, 'weights': [0.2550690257394217, 0.49543508709194095]}, {'output': 0.6573693455986976, 'weights': [0.4494910647887381, 0.651592972722763]}]] expected = [0, 1] backward_propagate_error(network, expected) print('Finished backpropagating errors') for layer in network: print(layer) if __name__ == '__main__': main()
"""Data utils module""" import numpy as np def split_data(X, t, w=[0.7, 0.15, 0.15]): """Takes and array of N x D (N: amount of data points, D: dimension) and returns three arrays containing Training, validation and test sets """ # normalize train/val/test weights vector w = np.array(w) w = w/np.sum(w) # train/val/test indices train_i, val_i, test_i = split_data_indices(X.shape[0], w) return X[train_i,], t[train_i], X[val_i,], t[val_i], X[test_i,], t[test_i,] def split_data_indices(N, w=[0.7, 0.15, 0.15]): """Splits the indices [1, .., N] into train, test and validation subsets """ # normalize train/val/test weights vector w = np.array(w) w = w/np.sum(w) # train/val/test indices indices = np.random.multinomial(n=1, pvals=w, size=N)==1 return indices[:,0], indices[:,1], indices[:,2] def random_batch(X, batch_size): batch_indices = np.random.choice(X.shape[0], batch_size, False) return X[batch_indices,]
# generate db table name def table_name(title_data) -> str: if type(title_data) == list: return ( '"' + title_data[0].replace(" ", "-") + "_" + title_data[1].replace(" ", "-") + '"' ) else: return '"' + title_data.replace(" ", "-") + '"' # turn list into tuples def tuplify(data: list) -> list: return [(d,) for d in data]
def mensaje(): print("Primer acercamiento a funciones en Python") mensaje() def suma(num1, num2): resultado=num1+num2 return resultado res1 = suma(5,7) print(res1) res2 = suma(7,7) print(res2) res3=suma(9,7) print(res3) #arrays firstList=["Carlos","Jaime","Indira","Juan"] firstList.append("Marco") firstList.insert(2,"Juancho") firstList.extend(["Jorge","Ana","Lucia"]) firstList.extend([1, 21.0, True, False]) print(firstList[:]) firstList.pop() print(firstList[:]) print(firstList[1:2]) print(firstList[2:]) print(firstList.index("Carlos"))
country = input('Where are you from?') age = input('How old are you?') age = int(age) if country == 'Taiwan': if age >= 18: print('you can get the driver licence') else: print('you can not get the licence') elif country == 'USA': if age >= 16: print('you can get the driver licence') else: print('you can not get the licence') else: print('only entry Taiwan or USA')
#Homework 1.1: The mood checker mood = input("What mood are you in (happy,nervous,sad,excited,relaxed,other)?:") if mood == "happy": print("It is great to see you happy!") elif mood == "nervous": print("Take a deep breath 3 times!") elif mood == "sad": print("Maybe one smile will help you!") elif mood == "excited": print("Please, share with us your excitement!") elif mood == "relaxed": print("Enjoy this moment!") else: print("I don't recognize this mood!")
#Given a signed 32-bit integer x, return x with its digits reversed. #If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ z = "" if x >= 0 : s = "" else: s = "-" x*=-1 x = str(x) for i in range(len(x)-1,-1,-1): s += x[i] if int(s) < -2**31 or int(s) > (2**31)-1: return 0 return int(s)
# Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10. # После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран. # Например, пользователь вводит число 123, вы сообщаете ему, что число не верное, # и сообщаете об диапазоне допустимых. И просите ввести заного. # Допустим пользователь ввел 2, оно подходит, возводим в степень 2, и выводим 4 # начинаем бесконечный цикл while 1: # получаем данные пользователя dig = float(input('Введите число: ')) # проверяем данные пользователя if 0 < dig < 10: # возводим в квадрат dig = dig ** 2 # выводим результат на экран print('Квадрат введеного числа равен ', dig) # завершаем бесконечный цикл break else: # информируем пользователя о диапазоне допустимых значений print('Число не верное!') print('Диапазон допустимых значений: больше 0 и меньше 10')
# Задача-1: # Напишите скрипт, создающий директории dir_1 - dir_9 в папке, # из которой запущен данный скрипт. # И второй скрипт, удаляющий эти папки. from os import mkdir, rmdir, listdir, path def create_dir(dir_name): try: mkdir(dir_name) except FileExistsError: print('Папка уже существует:', dir_name) except Exception as e: print(e.__class__) def remove_dir(dir_name): try: rmdir(dir_name) except FileNotFoundError: print('Папки не существует:', dir_name) except Exception as e: print(e.__class__) if __name__ == '__main__': for i in range(1, 10): create_dir('dir_' + str(i)) for i in range(1, 10): remove_dir('dir_' + str(i)) # Задача-2: # Напишите скрипт, отображающий папки текущей директории. if __name__ == '__main__': for name in listdir(): if path.isdir(name): print(name) # Задача-3: # Напишите скрипт, создающий копию файла, из которого запущен данный скрипт. if __name__ == '__main__': from shutil import copyfile a3_name = (__file__) a3_copy = a3_name + '_bkp' copyfile(a3_name, a3_copy)
def caught_speeding(speed, is_birthday): if not is_birthday and speed <=60: return 0 elif not is_birthday and (speed >60 and speed <=80): return 1 elif not is_birthday and speed >80: return 2 elif is_birthday and speed <=65: return 0 elif is_birthday and (speed >60 and speed <=85): return 1 elif is_birthday and speed >85: return 2
def strings(str1, str2): if (len(str1) < len(str2)) and (str2.remove[1]==str1): return strings print(strings("dragon", "dragoon"))
print("hello world") first_name= "misbah" last_name= "mehmood" print("hello " + first_name + last_name) number1 = float(input("Please eneter the first number: ")) number2 = float(input("Please enter the second number: ")) answer = number1 + number2 print(number1, "+", number2, "=", answer) word1 = "Time" word2 = "to" word3 = "eat" number = 5 sentence = word1 + " " + word2 + " " + word3, number print(sentence)
# Tutorial: https://pygame-zero.readthedocs.io/en/stable/introduction.html import pgzrun WIDTH = 500 HEIGHT = 400 yellow = (245,245,66) ball_x_speed = 1 ball_y_speed = 1 ball = Actor("ball") paddle = Actor("paddle") paddle.left = 0 paddle.bottom = HEIGHT def draw(): screen.fill(yellow) ball.draw() paddle.draw() def update(): move_ball() def on_mouse_move(pos) : print(pos) print(ball.bottom) def move_ball(): ball.x += ball_x_speed ball.y += ball_y_speed check_boundaries() def check_boundaries(): global ball_x_speed, ball_y_speed if ball.bottom > HEIGHT or ball.top < 0 : ball_y_speed *= -1 elif ball.left < 0 or ball.right > WIDTH : ball_x_speed *=-1 pgzrun.go()
##inciso 1 n=0 ##utilizo un if para ir creando los numeros del 1 al 9 y otra variable para irlos sumando ##se usa la misma funcion por lo que es recursiva def prob1(x,n): if x<9: x=x+1 n = n+x if n==45: print(n) return prob1(x,n) prob1(0,0)
class Bass(object): def __init__(self): self.datos = [0,0,0,0,0,0,0,0,0,0] self.Front = 0 self.Rear = 0 def pushFront(self,item): if self.Front == 5: print("Limite de 5") else: self.Front += 1 self.datos[self.Front] = item def pushRear(self,item): if self.Rear == -5: print("Limite de 5") else: self.Rear -= 1 self.datos[self.Rear] = item def Menu(self): while True: print("1 Push Rear") print("2 Push Front") print("4 Salir") o = int(input()) if o == 1: x=int(input("Ingresa dato")) print("") self.pushRear(x) elif o == 2: x=int(input("Ingresa dato")) print("") self.pushFront(x) elif o==9: exit() else : print("?") up = Bass() up.Menu()
def factorialR(num): if num==1: return 1 else: return num*factorialR(num-1) print ("Factorial Recursivo") num=int(input("Ingresa un numero: ")) print(factorialR(num)) print ("----------------------------------------------------------------------") def factorialI(num): factorial = 1 while num > 1: factorial = factorial * num num = num - 1 return factorial print ("Factorial Iterativo") num=int(input("Ingresa un numero: ")) print (factorialI(num))
import re from cs50 import get_int # gets every other number starting from the second to last or last depending on the option chosen def get_numbers(option, cardnumber): if(option == 1): start = 1 end = 2 amountofincrements = int(len(str(cardnumber)) / 2) elif(option == 2): start = 0 end = 1 # in case its even, this section could do with some work however if((len(str(cardnumber)) % 2) == 0): amountofincrements = int(len(str(cardnumber)) / 2) else: amountofincrements = int(len(str(cardnumber)) / 2) + 1 step = 2 y = [] # incrementing through number for i in range(amountofincrements): x = slice(start, end, step) y.append(cardnumber[x]) start = start + 2 end = end + 2 return(y) def main(): while (True): cardNo = get_int("Number: ") checkNumeric = re.findall("/W", str(cardNo)) if (checkNumeric != True): break # returns two lists of the alternate numbers firstset = get_numbers(1, str(cardNo)) secondset = get_numbers(2, str(cardNo)) secondsetdigits = [] firstsetdigits = [] # breaks down the list into individual digits and converts them to ints. Checking len as there is an issue in my get_numbers function # around odd numbers if(len(str(cardNo)) == 15): for i in firstset: digit = int(i) * 2 if(digit > 9): firstdigit = (get_numbers(2, str(digit))) seconddigit = (get_numbers(1, str(digit))) secondsetdigits.append(int(firstdigit[0])) secondsetdigits.append(int(seconddigit[0])) else: secondsetdigits.append(digit) for i in secondset: firstsetdigits.append(int(i)) else: for i in secondset: digit = int(i) * 2 if(digit > 9): firstdigit = (get_numbers(2, str(digit))) seconddigit = (get_numbers(1, str(digit))) secondsetdigits.append(int(firstdigit[0])) secondsetdigits.append(int(seconddigit[0])) else: secondsetdigits.append(digit) for i in firstset: firstsetdigits.append(int(i)) # adding lists of int digits togher sumofdigits = sum(firstsetdigits) + sum(secondsetdigits) # if multiple of ten then it must be valid if(sumofdigits % 10 == 0): valid = True else: valid = False # converting cardNo into string so I can slice the first two digits out cardNoasstring = str(cardNo) firstdigit = cardNoasstring[slice(0, 1, 1)] seconddigit = cardNoasstring[slice(1, 2, 1)] # deciding which type of card is it based on the first digits and if it has passed its tests if (valid == True and len(str(cardNo)) > 12): if (firstdigit == "3" and (seconddigit == "4" or seconddigit == "7")): print("AMEX") elif (firstdigit == "5" and (seconddigit == "1" or seconddigit == "2" or seconddigit == "3" or seconddigit == "4" or seconddigit == "5")): print("MASTERCARD") elif (firstdigit == "4"): print("VISA") else: print("INVALID") main()
import unittest from path_finding import find_path, BOMB, TRENCH class TestMethod(unittest.TestCase): def test_path_2x2(self): field = [[TRENCH, TRENCH], [0, BOMB]] solution = find_path(field) expected_list = [(0, 0), (0, 1), (1, 1)] print(solution.path) print(expected_list) self.assertListEqual(solution.path, expected_list) if __name__ == "__main__": unittest.main()
def main(): print(igualLista(input("Escriba una lista separada por comas: ").split(","), input("Escriba una lista separada por comas: ").split(","))) def igualLista(uno, dos): if uno == dos: return True else: return False main()
#Adicionar lista lista = [] def add_lista(): new_list = (dados1,dados2) lista.append(new_list) #Exibir lista def show_lista(): for data_list in show_lista: print (data_list) opcao = 0 while opcao != 3: print (''' (1) Adicionar uma lista (2) Exibir a lista (3) Sair''') opcao = int(input("Escolha sua Opção: ")) if opcao == 1: dados1 = input ("Informe 1 palava: ") dados2 = input ("Informe 2 palava: ") add_lista() elif opcao == 2: show_lista() elif opcao == 3: print("Obrigado e volte sempre!") print ("___"*10) print ("Fim da Trivia! Obrigado por jogar!")
from potential_gene import is_potential_gene class Genome: def __init__(self, sequence): if len(sequence) % 3 != 0: raise Exception('DNA sequence must have a length that is multiple of 3') self._sequence = sequence def __iadd__(self, codons): if len(codons) % 3 != 0: raise Exception('codon length must have a length that is multiple of 3') self._sequence += codons return self def __str__(self): return self._sequence def __getitem__(self, index): if isinstance(index, int): return self._sequence[index: index+3] def __iter__(self): for i in range(0, len(self._sequence)//3): yield self[i] def base_at(self, index): return self._sequence[index] def is_potential_gene(self): return is_potential_gene(self._sequence) if __name__ == "__main__": a = 'ATGCGCCTGCGTCTGTACTAG' g = Genome(a) print(g, g.base_at(3), g.is_potential_gene(), g[0]) print(tuple(g))
import argparse import sys import random def gambler_ruin_single_trial(amount_risked, goal, prob_winning, max_bets): bets = 0 amount = amount_risked while 0 < amount < goal and bets <= max_bets: amount += 1 if random.random() <= prob_winning else 0 bets += 1 return (amount, bets) def gambler_ruin(amount_risked, goal, prob_winning, max_bets, nb_trials): wins = 0 total_bets = 0 gains = 0 for i in range(nb_trials): amount, bets = gambler_ruin_single_trial(amount_risked, goal, prob_winning, max_bets) if amount >= goal: wins += 1 total_bets += bets gains += amount return (gains, wins, total_bets,nb_trials, wins/nb_trials) def probability(p): prob = float(p) if not 0<=prob<=1: msg = "probability must be between 0 and 1" raise argparse.ArgumentTypeError(msg) return prob if __name__ == "__main__": parser = argparse.ArgumentParser(description='Simulation for a gambler') parser.add_argument('initial', type=int, help='initial amount gambled') parser.add_argument('goal', type=int, help='goal amount at which gambling is stopped') parser.add_argument('prob', type=probability, help='prob of winning') parser.add_argument('max_bets', type=int, help='maximum number of bets placed') parser.add_argument('trials', type=int, help='number of times the experiment should be carried on') args = parser.parse_args() initial = args.initial goal = args.goal trials = args.trials prob = args.prob max_bets = args.max_bets print(gambler_ruin(initial, goal, prob, max_bets, trials))
import sys import math n = int(sys.argv[1]) prod = 1 for i in range(1, n+1): prod *= i print(prod) print(math.factorial(n))
import sys n = int(sys.argv[1]) n_ = n checksum = 0 for i in range(9,0,-1): digit = int(n // 10**(i-1)) checksum += (11-i)*digit n -= digit * 10**(i-1) print(checksum%11,n_,sep='')
import argparse def are_triangular(a,b,c): a_, b_, c_ = sorted((a,b,c)) return c_ < a_ + b_ parser = argparse.ArgumentParser(description='Say if the three lengths can make a triangle') parser.add_argument('a', type=float, help='length of a triangle') parser.add_argument('b', type=float, help='length of a triangle') parser.add_argument('c', type=float, help='length of a triangle') args = parser.parse_args() a = args.a b = args.b c = args.c print(are_triangular(a,b,c))
import random def binary_search(array, elem, start=None, end=None): if start is None: start = 0 if end is None: end = len(array) m = (start + end) // 2 if start > end: return -1 if array[m] == elem: return m if elem < array[m]: return binary_search(array, elem, start, m - 1) return binary_search(array, elem, m + 1, end) def binary_search_iter(array, elem): start = 0 end = len(array) while start <= end: m = (start + end) // 2 if array[m] == elem: return m if elem < array[m]: end = m - 1 else: start = m + 1 return -1 def binary_search_min_index(array, elem, start=None, end=None): if start is None: start = 0 if end is None: end = len(array) m = (start + end) // 2 if start > end: return -1 if array[m] == elem: for j in reversed(range(m+1)): print(j, array[j], elem) if array[j] == elem: m_ = j return m_ if elem < array[m]: return binary_search(array, elem, start, m - 1) return binary_search(array, elem, m + 1, end) def main(): a = sorted([random.randrange(10) for i in range(10)]) print(a) i = random.randrange(len(a)) print(i, a[i]) print(binary_search(a, a[i])) print(binary_search_iter(a, a[i])) print(binary_search_min_index(a, a[i])) if __name__ == "__main__": main()
import datetime class Time: def __init__(self, hours, minutes, seconds): self._hours = hours self._minutes = minutes self._seconds = seconds def __iter__(self): yield from (self._hours, self._minutes, self._seconds) def __str__(self): return '%s:%s:%s' % tuple(self) def now(): dt = datetime.datetime.now().time() return dt.hour, dt.minute, dt.second if __name__ == "__main__": h = Time(4, 10, 23) print(h, tuple(h), Time.now())
import math import sys n = int(sys.argv[1]) def sieveEratoshenes(n): "calculate the sieve of Eratoshtenes for primatlity" sieve = [True] * (n+1) sieve[1] = False maxiter = int(math.sqrt(n)) for i in range(2, maxiter+1, 1): for j in range(i*2, n+1, i): sieve[j] = False return sieve[1:] def nbPrimes(n): sieve = sieveEratoshenes(n) return sieve.count(True) # print(sieveEratoshenes(n)) print(nbPrimes(n))
a = [[1,1,1], [2,2,2], [3,3,3]] b = [[0,0,0], [0,0,0], [0,0,0]] n = len(a) for i in range(n): for j in range(n): b[i][j] = a[i][j] print(b) c = [[1,1,1], [2,2]] d = [[0,0,0], [0,0]] for i in range(len(c)): for j in range(len(c[i])): d[i][j] = c[i][j] print(d) d = [[0,0,0], [0,0]] d=[] for row in c: r=[] for v in row: r+= [v] d+=[r] print(d)
import argparse from Queue import Queue def josephus(nb_people, nth_kill): who_to_kill = Queue() def kill(queue, n): person = queue.dequeue() if n == 1: who_to_kill.enqueue(person) return else: queue.enqueue(person) kill(queue, n - 1) q = Queue() for i in range(nb_people): q.enqueue(i) while q: kill(q, nth_kill) return who_to_kill def main(): parser = argparse.ArgumentParser(description='Solve the Josephus problem') parser.add_argument('nb_people', type=int, help='number of people') parser.add_argument('nth', type=int, help='nth person to kill') args = parser.parse_args() nb_people = args.nb_people nth = args.nth print(josephus(nb_people, nth)) if __name__ == '__main__': main()
import sys import random import re from strutils import words def quick_sort_(array): n = len(array) if n <= 1: return array left = [] right = [] pivot_list = [] pivot = array[0] for elem in array: if elem < pivot: left += [elem] elif elem > pivot: right += [elem] else: pivot_list += [elem] left = quick_sort_(left) right = quick_sort_(right) return left +pivot_list + right def quick_sort(array): n = len(array) if n <= 1: return array pivot = array[0] # left = quick_sort([e for e in array if e < pivot]) # right = quick_sort([e for e in array if e > pivot]) lt, gt = lambda x: x < pivot, lambda x: x > pivot left = quick_sort(list(filter(lt, array))) right = quick_sort(list(filter(gt, array))) repeat = n - (len(left) + len(right)) return left + [pivot] * repeat + right if __name__ == "__main__": a = [random.randrange(10) for i in range(1000)] print(a) print(quick_sort(a)) filename = sys.argv[1] with open(filename) as lines: wordslist = [word for line in lines for word in words(line)] print(quick_sort_(wordslist))
import sys n = int(sys.argv[1]) # for i in range(1,n+1): # for j in range(1,n+1): # if(j%i==0 or i%j==0): # print('*',end='') # else: # print(' ',end='') # print(i) def gcd(a, b): "Calculates the greatest common divisor of a number" a, b = abs(a), abs(b) a, b = max(a, b), min(a, b) if a % b == 0: return b return gcd(b, a % b) i = 1 while i <= n: j = 1 while j <= n: if gcd(i, j) == 1: print('*', end='') else: print(' ', end='') j += 1 print(i) i += 1
import sys import random import re from math import radians, sin, cos, acos, degrees class Location: def __init__(self, lat, lon): self._lat = radians(lat) self._lon = radians(lon) def distance(self, other): x1, y1 = self._lat, self._lon x2, y2 = other._lat, other._lon angle1 = acos(sin(x1)*sin(x2)+cos(x1)*cos(x2)*cos(y1-y2)) return degrees(angle1) * 60 #nautical miles def random(): lt = random.randint(-90, 91) ln = random.randint(-180, 180) return Location(lt, ln) def __str__(self): return str((degrees(self._lat), degrees(self._lon))) def from_str(string): lst = re.split('[^0-9.NW ]+', string) lat, lon = lst lat_ = float(re.sub('[^0-9.]+', '', lat)) lon_ = float(re.sub('[^0-9.]+', '', lon)) if 'S' in lat: lat_ = -lat_ if 'W' in lon: lon_ = -lon_ return Location(lat_, lon_) if __name__ == "__main__": lat1 = float(sys.argv[1]) lon1 = float(sys.argv[2]) lat2 = float(sys.argv[3]) lon2 = float(sys.argv[4]) location1 = Location(lat1, lon1) location2 = Location(lat2, lon2) print(location2.distance(location1)) print(location1.distance(location2)) print(Location.random()) print(Location.from_str('25.344 N, 63.5532W'))
import argparse from math import cos, sin, asin, radians,sqrt, degrees def haversine(d1,a1, d2,a2): def haver(angle): return sin(angle/2)**2 d = d2 - d1 a = a2 - a1 h = haver(d) + cos(d1)*cos(d2)*haver(a) return 2*asin(sqrt(h)) parser = argparse.ArgumentParser(description='calculate the angle between two stars using the haversine formula') parser.add_argument('d1', type=float, help='declination of the first star') parser.add_argument('a1', type=float, help='right ascension for the first star') parser.add_argument('d2', type=float, help='declination of the second star') parser.add_argument('a2', type=float, help='right ascension for the second star') args = parser.parse_args() d1 = radians(args.d1) a1 = radians(args.a1) d2 = radians(args.d2) a2 = radians(args.a2) print(degrees(haversine(d1,a1, d2,a2)))
import argparse from permutations import combinations_of_length def flip(bit): return {'0':'1','1':'0'}[bit] def flip_bits(string, lst): new_string = "" for i, bit in enumerate(string): if i in lst: new_string += flip(string[i]) else: new_string += string[i] return new_string def within_hamming_dist(string, dist): n = len(string) change_bits = combinations_of_length(list(range(n)), dist) res = [] for change in change_bits: res += [flip_bits(string, change)] return res if __name__ == "__main__": parser = argparse.ArgumentParser(description='Strings having a hamming distance lesser thant he string given') parser.add_argument('string', help='bit string') parser.add_argument('dist', type=int, help='hamming distance from the given string') args = parser.parse_args() string = args.string dist = args.dist res =within_hamming_dist(string, dist) print(*res,sep='\n')
import matplotlib.image as mpimg import numpy as np import argparse def to_255(color01): "Converts a color defined in 0-1 to 0-255" return tuple(int(x*255) for x in color01) def to_stdout(filename): im = mpimg.imread(filename) height,width = im.shape[0:2] print(width, height) for row in im: for pxl in row: print(to_255(pxl), end='') print('') if __name__ == "__main__": parser = argparse.ArgumentParser(description='Output an image file as triplets into stdout') parser.add_argument('filename', help='name of the image file') args = parser.parse_args() filename = args.filename to_stdout(filename)
class Time: def __init__(self, hours, minutes, seconds): self._seconds_elapsed = hours * 3600 + minutes * \ 60 + seconds # seconds elapsed since midnight @property def hour(self): return self._seconds_elapsed // 3600 @property def minute(self): h = self.hour return (self._seconds_elapsed - (h * 3600)) // 60 @property def second(self): h, m = self.hour, self.minute return self._seconds_elapsed - (h * 3600) - (m * 60) def __iter__(self): yield from (self.hour, self.minute, self.second) def __str__(self): return '%s:%s:%s' % tuple(self) def main(): h = Time(4, 10, 23) print(h.hour, h.minute, h.second) print(h, tuple(h)) if __name__ == "__main__": main()
import math import sys def taylor_series(x, init, step): total = init prev = init n=1 while True: # print(n, prev) curr = step(prev, x, n) if total == total + curr: return total prev = curr total += curr n+=1 def taylor_series_coeffs(init, n, step): res = [init] for i in range(1,n): res += [step(res[i-1],1,i)] # we choose 1 as we merely want the coefficients return res def stepExp(prev,x, n): return prev *x /n def stepSinus(prev, x, n): # sign = 1 if n % 2 == 0 else -1 sign = -1 return prev *x*x/((n*2)*(n*2+1)) *sign def stepCosinus(prev, x, n): sign = -1 return prev *x*x/((n*2)*(n*2-1)) *sign def step_phi(prev, x, n): return prev * x * x /(2*n + 1) if __name__ == "__main__": x = float(sys.argv[1]) print( taylor_series(x, x, stepSinus) ) print( taylor_series(x, 1, stepCosinus) ) print( taylor_series(x, 1, stepExp) ) print( taylor_series(x, x, step_phi) ) print( taylor_series_coeffs( 1, 5, stepExp))
def isPowerOfFive(n): return int(n**(1/5))**5==n max_range =250 def powers(): for a in range(1,max_range+1): for b in range(a,max_range+1): for c in range(b,max_range+1): for d in range(c,max_range+1): # print(a,b,c,d) if isPowerOfFive(a**5 + b**5 +c**5+d**5): return (a, b,c,d) continue print(powers())
import numpy as np def square(x): return x * x def integrate(f, a, b, n=1000): dx = (b - a) / n xs = np.linspace(a + dx / 2, b + dx / 2, n + 1)[0:n] return sum(dx * f(x) for x in xs) def integrate_(f, a, b, n=1000): dx = 1.0 * (b - a) / n series = (dx * f(a + (i + 0.5) * dx) for i in range(n)) return sum(series) if __name__ == "__main__": print(integrate(square, 2, 3, 1000)) print(integrate_(square, 2, 3, 1000))
import os # 【输入str,str】:生成的文件名,需要写入文档的文本数据 # 【功能】:创建一个文档 def text_create(savepath, filename, msg, filesuffix='.txt'): isExisted = os.path.exists(savepath) if not isExisted: print(savepath) print('上面列出的目录或文件不存在,请设置正确路径!') return else: print('目录[' + savepath + ']存在,正在创建文件[' + filename + filesuffix + ']...') fullpath = savepath + filename + filesuffix # 创建写入的文档 file = open(fullpath, 'w') file.write(msg) file.close() print('文件[' + filename + filesuffix + ']创建完成!') class ReadData(object): def __init__(self, path_read=None): self.path_read = path_read def read_weld_coordinate(self, i_file): coordfile = open(self.path_read + str(i_file) + "_1.lis", 'rt') txt = coordfile.read() list_temp = txt.split("C") for i, temp in enumerate(list_temp): text_create(path_write, str(i_file) + "_" + str(i + 1), temp) if __name__ == "__main__": path_read = r"C:\Users\asus\Desktop\weld_data\\" path_write = r"C:\Users\asus\Desktop\\" read_data = ReadData(path_read=path_read) read_data.read_weld_coordinate(1) # text_create(path_write, "1", read_data.surfaceCoord_To_List(1))
def replaceStr(value, t01, t02) : keywords = list(value) for idx, keyword in enumerate(keywords) : if keyword == t01 : keywords[idx] = t02 result = ''.join(keywords) return result if __name__ == '__main__' : replaceStr('te@xt', '@', '')
# 二叉树的叶子结点 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class BinaryTree: def __init__(self, root=None): self.root = root def is_empty(self): """ 判断二叉树是否为空 :return: """ if self.root is None: return True return False # def create(root): # a = input('enter a key:'); # if a is '#': # root = None # else: # root = TreeNode(a) # root.left = create(root.left) # root.right = create(root.right) # return root def create(self, node): temp = input('enter a value:') if temp is '#': node = None else: node = TreeNode(temp) node.left = self.create(node.left) node.right = self.create(node.right) return node # return node # treenode = TreeNode(temp) # if self.root is 0: # self.root = treenode # # treenode.left = self.create() # treenode.right = self.create() def pre_order(self, tree_node): """ 前序遍历 :param tree_node: tree_nodeNode :return: """ if tree_node is None: return print(tree_node.val, end=' ') self.pre_order(tree_node.left) self.pre_order(tree_node.right) def mid_order(self, tree_node): """ 中序遍历 :param tree_node: tree_nodeNode :return: """ if tree_node is None: return self.pre_order(tree_node.left) print(tree_node.val, end=' ') self.pre_order(tree_node.right) def later_order(self, tree_node): """ 后序遍历 :param tree_node: tree_nodeNode :return: """ if tree_node is None: return self.pre_order(tree_node.left) self.pre_order(tree_node.right) print(tree_node.val, end=' ') # def preorder(root): # 前序遍历 # if root is None: # return # else: # print(root.val) # preorder(root.left) # preorder(root.right) if __name__ == '__main__': # root = create(None) # preorder(root) tree = BinaryTree() tree.root = tree.create(tree.root) tree.pre_order(tree.root) tree.mid_order(tree.root) tree.later_order(tree.root)
# Given an array of integers that is already sorted in ascending order, # find two numbers such that they add up to a specific target number. # # The function twoSum should return indices of the two numbers such that they add up to the target, # where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. # # You may assume that each input would have exactly one solution and you may not use the same element twice. # # Input: numbers={2, 7, 11, 15}, target=9 # Output: index1=1, index2=2 class Solution: def twoSum(self, numbers, target): """ 计算整形列表中是否有两个值的和与目标值相等 :param numbers: list[int] :param target: int :return: list[int] """ # 使用一个字典存储已经遍历过的元素 dic = {} # 循环遍历 for i in range(len(numbers)): # 如果目标值减去遍历的元素的值在字典中 if target - numbers[i] in dic: # 即返回保存在字典中元素的下标 # 并且要求索引从1开始 所以需要+1 return [dic[target - numbers[i]] + 1, i + 1] # 将遍历过的值和下标存入字典中 dic[numbers[i]] = i if __name__ == '__main__': solution = Solution() print(solution.twoSum([2, 7, 11, 15],9))
# 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。 # n<=39 class Solution: def Fibonacci(self, n): """ 斐波那契数列数列 :param n: :return: """ num0 = 0 num1 = 1 num_n = 0 if n == 0: return 0 if n == 1: return 1 for i in range(2, n + 1): num_n = num0 + num1 num0 = num1 num1 = num_n return num_n if __name__ == '__main__': solution = Solution() print(solution.Fibonacci(6))
# Given a binary tree, check whether it is a mirror of itself # (ie, symmetric around its center). # # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: # 判断一颗树是否是镜像的, class Solution: def isSymmetric(self, root): """ 判断一颗树是否是镜像树 :param root: TreeNode :return: bool """ return self.isMirror(root, root) def isMirror(self, tree_node1, tree_node2): """ 判断两棵树是否镜像 :param tree_node1: TreeNode :param tree_node2: TreeNode :return: bool """ # 如果两个叶子结点均为空 if not tree_node1 and not tree_node2: return True # 如果只有一个叶子结点为空 if not tree_node1 or not tree_node2: return False # 当前叶子结点的值相等,并且一颗树的左子树等于另一颗树的右子树 return (tree_node1.val == tree_node2.val) \ and self.isMirror(tree_node1.right, tree_node2.left) \ and self.isMirror(tree_node1.left, tree_node2.right) if __name__ == '__main__': solution = Solution() # print(solution.isSymmetric()