text
stringlengths
37
1.41M
#!/usr/bin/env python # coding: utf-8 # ### Tuples # - t1 parenthesis() li square brackets[] # - difference between list and tuples # - list are mutable - can be changed / modified # - used to access modify,add,delete data # - tuples are immutable - vcannot be changed # - used to access data only # In[18]: t1 = (1,2,3,4,5,6) t1 type(t1) # # Data Structures # # ### Dictionaries # - it works on the concept of set unique data # - each key is separated from its value with colon(:) # - keys,values are the unique identifiers for a value # - each key and value are separated by comma(,) # - dictionaries enclosed with curly braces({}) # # In[4]: d1={"name":"gitam","emailid":"gitam@gmail.com","address":"hyderabad"} print(d1) # In[6]: d1["name"] # In[8]: d1['emailid'] = 'gitam-python@gmail.com' # In[10]: d1['emailid'] # In[12]: del d1['emailid'] # In[13]: d1 # In[14]: d1.keys() # In[15]: d1.values() # In[16]: d1.items() # # Contact Application # - add contact # - search the contact # - list all contacts # - name1:phone1 # - name2:phone2 # - modify the contact # - remove the contact # - import the contact # In[20]: # add contact contacts = {} # creating a dict object def addcontact(name,phone): if name not in contacts: contacts[name] = phone print("conact is details are added") else: print("contact details are already exists") return addcontact('Surya','123456789') addcontact('Pandu','987654321') addcontact('Jai','7418529633') # In[22]: # search for contact details def searchcontact(name): if name in contacts: print(name,":",contacts[name]) else: print("%s does not exists" % name) return searchcontact('Surya') searchcontact('Pandu') searchcontact('Jai') # In[23]: # import some contacts # merge the contact with existing one def importcontact(newcontacts): contacts.update(newcontacts) print(len(newcontacts.keys()),"contacts added successfully") return newcontacts={'rishi':4546789123,'chichu':654987321} importcontact(newcontacts) # In[24]: # delete a contact def deletecontact(name): if name in contacts: del contacts[name] print(name,"delete successfully") else: print(name,"not exists") return deletecontact('chichu') # In[25]: contacts # In[26]: # update the contact details def deletecontact(name,phone): if name in contacts: contacts[name]=phone print(name,"update successfully") else: print(name,"not exists") return deletecontact('Jai',7418529633) deletecontact('chichu',654987321) # ### Sring Functions # - upper()--will convert the string into upper function # - lower()--will convert the string into lower function # In[28]: s1='gitam' print(s1.upper()) print(s1.lower()) # ### Boolean Function(true and false) # - islower()--true if the string is lower case / false if not lower case # - isupper()--true if string is in upper / false if not upper case # In[29]: s1='GITAM' print(s1.islower()) print(s1.isupper()) # In[30]: s2="Python Programming" s3="python Programming" print(s2.istitle()) print(s3.istitle()) # In[31]: s2="Application1889" s3="PythonProgramming" print(s2.isalpha()) print(s3.isalpha()) # In[32]: s1="1234" s2="Application1234" print(s1.isnumeric()) print(s2.isnumeric()) # In[33]: s1=" " s2="Py th on" print(s1.isspace()) print(s2.isspace()) # # String Methods # - join()-- Method will concatinates the two strings # - split()-- split() returns the a list of strings separted by whitespace(no parameters are given) # - join()-- Method will concatinates the two strings # - replace()-- replaces the specific word/character with new word/character # In[34]: s1='Python' print(" ".join(s1)) # In[35]: s2="Python Programming Easy to learn" print(",".join(s2)) # In[36]: li =['Python','Programming','Learn'] print(",".join(li)) # In[37]: s2="Python Programming Easy to learn" print(s2.split()) # In[38]: s2="Python Programming Easy to learn" li=s2.split() print(li) print(len(li)) # # Packing and Modules # ## Packages: # - A collection of Modules(Single Python file.py) and Subpackages # -Module # - A Single python file containing set functions # - Packages-->Sub Packages-->Modules-->Function-->Statements # In[39]: #Import the externals packages to Python File import math math.floor(123.45) # In[40]: from math import factorial as fact fact(5) # In[41]: #Function to generate N random numbers in given range import random def randomNumbers(n,lb,ub): for i in range(0,n): print(random.randint(lb,ub),end=" ") return randomNumbers(10,0,100) # In[ ]: # In[ ]:
# Import Counter from collections import Counter # Collect the count of each generation gen_counts = Counter(generations) # Improve for loop by moving one calculation above the loop total_count = len(generations) for gen,count in gen_counts.items(): gen_percent = round(count / total_count * 100, 2) print('generation {}: count = {:3} percentage = {}' .format(gen, count, gen_percent))
# Collect the count of primary types type_count = Counter(primary_types) print(type_count, '\n') # Collect the count of generations gen_count = Counter(generations) print(gen_count, '\n') # Use list comprehension to get each Pokémon's starting letter starting_letters = [name[0] for name in names] # Collect the count of Pokémon for each starting_letter starting_letters_count = Counter(starting_letters) print(starting_letters_count)
import random def selectFromFile(path): with open(path) as f: dataList = list(f) if dataList[0].find(":") != -1: # if there is a colon in the first line of the file weightedDict = dictionaryCreator(dataList) # assume it is a raffle dictionary return weightedSample(weightedDict) else: return random.choice(dataList).strip() # otherwise return a randomly chosen line def dictionaryCreator(formattedList): dictionary = dict() for line in formattedList: key, value = line.split(":") key = key.strip() value = int(value.strip()) dictionary[key] = value #takes each line and enters it into the dictionary return dictionary def weightedSample(weightedDictionary): # works like a raffle numberOfEntries = 0 for item in weightedDictionary: #takes each key from dictionary and adds it to a list value number of times numberOfEntries += weightedDictionary[item] roll = random.randint(1,numberOfEntries) selected = "Default" for item in weightedDictionary: roll -= weightedDictionary[item] if roll <= 1: selected = item break return selected
""" 用for循环实现1~100求和 Version: 0.1 Author: 骆昊 Date: 2018-03-01 """ sum = 0 for x in range(1, 101): sum += x print(sum) ''' a = 2020 print(a) b = int(input('b = ')) print(a+b) ''' for x in range(11): print(x)
for _ in range(10): total = int(input()) difference = int(input()) klaudia = (total + difference) // 2 natalia = klaudia - difference print(klaudia) print(natalia)
while True: n = int(input()) if n == 0: break pi = 3.1415926536 print("{0:.2f}".format(n*n/(2*pi)))
import itertools from collections import Counter def count_totals(s, n): """ Given the number of sides (s), and number of dice (n), count the totals for all possible dice comibnations, and return a dictionary mapping the total to the number of occurrences. """ return Counter(sum(r) for r in itertools.product(range(1, s+1), repeat=n)) # In the following player 1 is Peter with his 9 four-sided dice, # ans player 2 is Colin with his 6 six-sided dice. res = 0 for t1, c1 in count_totals(4, 9).items(): for t2, c2 in count_totals(6, 6).items(): if t1 > t2: # player 1 wins res += c1 * c2 res /= pow(4, 9) * pow(6, 6) print('%.7f' % res)
import urllib2 import re from binaryTree import tree #this is the binary search tree that will index the words that need to be ignored while indexing the search strings stopWordsTree = tree() #this is the binary search tree that will index the search strings searchStringsTree = tree() print 'Starting Indexing' #open the file containing the list of urls and load them in the memory urlFile = open('./reviewUrls.txt') urls = urlFile.readlines() counter = 0; #this function hashes the words that need to be ignored while indexing search words. #this function reads every word present in the stopWords.txt file and hashes them in the hash table defined above def addStopWords(): stopWordFile = open('./stopWords.txt') stopWords = stopWordFile.readlines(); for stopWord in stopWords: stopWordsTree.addNode(stopWord.lower().strip()); addStopWords(); print 'Finished Hashing Stop Words'; #this function does the processing for a single url def consumeAURL(urlToFetch): #try opening the url try: global counter; urlFile = urllib2.urlopen(urlToFetch) counter = counter + 1; print 'Started Indexing url number ' + str(counter) #if the url cannot be opened, catch the exception and print an error message and ignore this url except: #global counter; print ' Did not get the url ' + str(counter) + ' because of HTTP Error or URL Error' return; #read the contents of the file specified by the url fileData = urlFile.readlines() #extract the shoebrand and the model from the first line of the contents of the review file shoeBrand = fileData[0]; shoeBrand = shoeBrand.lower().strip() #store the reviews in this file fileData = fileData[1:] #parse the reviews for line in fileData: #stores the words that would be hashed into the hash table selectedWords = [] #split the lines into words by using non-alphanumberic characters as delimitters reviewWords = re.split('\W+',line) #convert the words into lower case so that it is easier for comparison reviewWords = [word.lower() for word in reviewWords] #for every word in each review for word in reviewWords: # if the word is not in the tree that indexes the words that need to be ignored if stopWordsTree.search(word) == False: # if the word has already not been selected for indexing. This is done to remove duplicacy for a word that is present multiple # times in a same review if word not in selectedWords: selectedWords.append(word) #print 'The original words were ' + str(reviewWords); #print 'Selected Words are ' + str(selectedWords); for word in selectedWords: #index each word in the list of selected Words. This funciton built by me takes care by itself if the word has been already indexed or if a word indexed in the tree exists in the review for a current shoe brand searchStringsTree.addIndex(word,shoeBrand); #start processing all the urls one by one for url in urls: consumeAURL(url.strip()); userInput ='' #taking input from the user to enter a search string #unless the user enters a search string 'exit', the program asks the user to enter a search string while userInput.lower() != 'exit': userInput = raw_input('Enter a search string to search for reviews : ') userInput = userInput.lower() #search for user input and output the result. The function built by me automatically takes care of a search that is present in the index tree and which are not present in the index tree. searchStringsTree.searchAndPrintReviews(userInput);
a = int(input('Введіть число: ')) b = int(input('Введіть число: ')) print(a+b) print(a-b) print(a/b) print(a*b) print() print(abs(a+b)) print()
''' Text based single deck blackjack game One player vs an automated dealer For 1 player, shuffle deck after 5 hands Blackjack pays 3:2 Win pays 1:1 Dealer is dealt two cards, one face up and one face down Player is dealt two cards face up Dealer hits on 16 or less and soft 17; stands on hard 17 or greater Ties go to the dealer Player can stand or hit All players have their turn before the dealer, unless dealer has blackjack Player can pick their betting amount Keep track of players total money Alert the player of wins, losses, busts, etc. ''' class Card: ''' This class represents one playing card for blackjack The suit should be a string = 'spade','club','heart', or 'diamond The rank should be an integer value of 2 thru 10 or a srting value of 'ace','king','queen' or 'jack' Face cards are aasinged a value of 10; aces = 11 and other cards their number value If face = 'up' the card is dealt face up; if 'down' then card will be dealt face down ''' def __init__(self,suit,rank,face = 'up'): self.suit = suit self.rank = rank self.face = face self.val1 = 0 self.val2 = 0 if self.rank == 'ace': self.val1 = 1 self.val2 = 11 elif self.rank == 'king' or self.rank == 'queen' or self.rank == 'jack': self.val1 = 10 self.val2 = 10 else: self.val1 = self.rank self.val2 = self.rank class Deck: ''' This class represents a deck of Card objects The class constructor takes a list of Card objects ''' def __init__(self,cards): self.cards = cards # cards is an array of Card ojjects def show_deck(self): for num in range(len(self.cards)): print (f'{self.cards[num].rank} of {self.cards[num].suit} value= {self.cards[num].val1}, {self.cards[num].val2}') def num_cards(self): # returns the number of cards in the deck return len(self.cards) def deal_card(self): # deals out one card that is returned as a Card object return self.cards.pop() def shuffle_cards(self): import random random.shuffle(self.cards) class Player(): ''' Represents the player in a blackjack game. Keeps track of how much cash the player has and how much has bet and won. ''' def __init__(self, cash = 1000): # Player starts with self.cash = cash self.bet_amt = 0 def show_cash(self): print (self.cash) def bet(self): betting = True while betting: print (f'You have ${self.cash}') self.bet_amt = int(input('how much do you want to bet?: ')) if self.bet_amt <= self.cash: self.cash = self.cash - self.bet_amt print (f'You bet ${self.bet_amt}') print (f'You have ${self.cash} left') return self.bet_amt else: print("you dont' have enough money") continue class Hand(): def __init__(self, name): self.name = name self.cards = [] self.point_total1 = 0 self.point_total2 = 0 def add_card(self, card): self.cards.append(card) def show_hand(self): print(f'{self.name} hand is: ') for num in range(len(self.cards)): if self.cards[num].face == 'up': print(self.cards[num].rank, self.cards[num].suit,self.cards[num].face) else: print('Face Down') def num_cards(self): return len(self.cards) def point_totals(self): self.point_total1 = 0 self.point_total2 = 0 for num in range(len(self.cards)): self.point_total1 = self.point_total1 + self.cards[num].val1 self.point_total2 = self.point_total2 + self.cards[num].val2 print (f'Point total: {self.point_total1} or {self.point_total2}') def newdeck(): ''' This function creates a new deck of 52 cards The function returns a list of 52 Card objects sorted in new deck order with all suits together and ranks in order for 2 thru ace ''' cards = [] suits = ['spade', 'club', 'heart', 'diamond'] ranks = [2,3,4,5,6,7,8,9,10,'jack','queen','king','ace'] for suit in suits: for rank in ranks: cards.append(Card(suit, rank)) return cards def check_hand(hand): # check a hand for a 21 or a bust if hand.point_total1 == 21 or hand.point_total2 == 21: return '21' elif hand.point_total1 > 21 and hand.point_total2 > 21: return 'bust' # set up the game player1 = Player() deck1 = Deck(newdeck()) # get a new unshuffled deck deck1.shuffle_cards() # shuffle the deck player1_hand = Hand('player1') dealer_hand = Hand('dealer') # start the hand game_playing = True print ('\n' * 20) while game_playing: player1_hand.cards = [] dealer_hand.cards = [] player1.bet_amt = 0 print ('\n' * 20) # ask the player for their bet player1.bet() # first card to player1 input('press enter to continue') player1_hand.add_card(deck1.deal_card()) print ('\n' * 100) print ('First card dealt to player1:') player1_hand.show_hand() player1_hand.point_totals() # first card to dealer input('press enter to continue') dealer_hand.add_card(deck1.deal_card()) dealer_hand.cards[0].face = 'down' # deal first card to dealer face down print ('\n' * 100) print ('First card dealt to dealer') dealer_hand.show_hand() dealer_hand.point_totals() #second cards to player1 input('press enter to continue') player1_hand.add_card(deck1.deal_card()) print ('\n' * 100) print ('Second card dealt to player1: ') player1_hand.show_hand() player1_hand.point_totals() # second card to dealer input('press enter to continue') print ('\n' * 100) dealer_hand.add_card(deck1.deal_card()) print ('Second card dealt to dealer: ') dealer_hand.show_hand() dealer_hand.point_totals() # show all hands input('press enter to continue') print ('\n' * 100) dealer_hand.show_hand() print('') player1_hand.show_hand() print('') # check to see if the dealer or the player has a blackjack if check_hand(dealer_hand) == '21': print ('Dealer has blackjack. You lose') print(f'you lost {player1.bet_amt}') print(f'You have ${player1.cash}') elif check_hand(player1_hand) == '21': print ('Player1 has blackjack. Player1 wins hand') print(f'you won {2 * player1.bet_amt}') player1.cash = player1.cash + (player1.bet_amt + 2 * player1.bet_amt) #blackjack pays double print(f'You have ${player1.cash}') else: player1_turn = True while player1_turn: action = input('Do you want to hit or stand? (H or S)') if action.lower() == 's': player1_turn = False dealer_turn = True elif action.lower() == 'h': print ('\n'*100) player1_hand.add_card(deck1.deal_card()) dealer_hand.show_hand() print('') player1_hand.show_hand() player1_hand.point_totals() print('') if check_hand(player1_hand) == '21': print ('player1 wins') print(f'you won {player1.bet_amt}') player1.cash = player1.cash + 2 * player1.bet_amt print(f'You have ${player1.cash}') player1_turn = False dealer_turn = False elif check_hand(player1_hand) == 'bust': print ('player1 busted') print(f'you lost {player1.bet_amt}') print(f'You have ${player1.cash}') player1_turn = False dealer_turn = False else: continue while dealer_turn: print('dealer turn') dealer_hand.cards[0].face = 'up' # turn over the dealer hole card dealer_hand.show_hand() dealer_hitting = True while dealer_hitting: if dealer_hand.point_total1 < 17: print ('dealer hits ') dealer_hand.add_card(deck1.deal_card()) dealer_hand.show_hand() dealer_hand.point_totals() elif dealer_hand.point_total1 < 17 and dealer_hand.point_total2 == 17: #soft 17 print ('dealer hits on soft 17') dealer_hand.cardsadd_card(deck1.deal_card()) dealer_hand.show_hand() dealer_hand.point_totals() else: print('Dealer Stands') break if check_hand(dealer_hand) == 'bust': print ('dealer busted...you win ') print(f'you won {player1.bet_amt}') player1.cash = player1.cash + 2 * player1.bet_amt print(f'You have ${player1.cash}') break elif check_hand(dealer_hand) == '21': print ('dealer has 21') print(f'you lost {player1.bet_amt}') print(f'You have ${player1.cash}') break elif dealer_hand.point_total2 > player1_hand.point_total2: print ('dealer wins') print(f'you lost {player1.bet_amt}') print(f'You have ${player1.cash}') break elif dealer_hand.point_total2 < player1_hand.point_total2: print ('player1 wins') print(f'you won {player1.bet_amt}') player1.cash = player1.cash + 2 * player1.bet_amt print(f'You have ${player1.cash}') break else: print ('PUSH nobody wins') print(f'you get your ${player1.bet_amt} bet back') player1.cash = player1.cash + player1.bet_amt print(f'You have ${player1.cash}') break question = input('Play another hand? Y or N: ') if question.lower() == 'y': continue else: break
from bs4 import BeautifulSoup as soup from urllib.request import urlopen import csv # Function will scrape the data for each teams allowed yard per game def get_teams_OYG(team1, team2): opp_ypg_url = 'https://www.teamrankings.com/nfl/stat/opponent-yards-per-game' opp_ypg_data = urlopen(opp_ypg_url) opp_ypg_html = opp_ypg_data.read() opp_ypg_data.close() page_soup = soup(opp_ypg_html, 'html.parser') # List of all opponents' yards per game opp_ypg = page_soup.findAll('td', {'class' : 'text-right'}) # List of teams temp = page_soup.findAll('td', {'class' : 'text-left nowrap'}) _teams = [] for line in temp: _teams.append(line.text) # Create list of Opponents yards per game in 2020 opp_ypg_TT = [] i=0 for line in opp_ypg: if i % 6 == 0: opp_ypg_TT.append(float(line.text)) i+=1 # Change abbreviated team names teams_text = [] for team in _teams: temp = team if "LA" in temp: if "Rams" in temp: temp = "Los Angeles Rams" if "Chargers" in temp: temp = "Los Angeles Chargers" if "NY" in temp: if "Giants" in temp: temp = "New York Giants" if "Jets" in temp: temp = "New York Jets" teams_text.append(temp) # Create dictionary for opponents yards per game opp_ypg_dict = {teams_text[i]: opp_ypg_TT[i] for i in range(len(teams_text))} # Get both team stats given from user stats1 = opp_ypg_dict[team1] stats2 = opp_ypg_dict[team2] # Return whichever team has the least amount of yards allowed per game if(stats1 < stats2): return team1 else: return team2
from room import Room from character import Enemy from item import Item backpack = [] kitchen = Room('Kitchen') kitchen.set_description('a place to cook food') dining_hall = Room('Dining Hall') dining_hall.set_description('a place where people eat') ball_room = Room('Ballroom') ball_room.set_description('a place where people dance') kitchen.link_room(dining_hall, 'south') dining_hall.link_room(kitchen, 'north') dining_hall.link_room(ball_room, 'west') ball_room.link_room(dining_hall, 'east') cheese = Item('cheese') dave = Enemy("dave", "a smelly zombie") dave.set_conversation('ill eat your brains!') dave.set_weakness('cheese') dining_hall.set_character(dave) dining_hall.set_item(cheese) cheese.set_description('a big smelly block of cheese') current_room = kitchen dead = False while dead == False: print("\n") current_room.get_details() inhabitant = current_room.get_character() if inhabitant is not None: inhabitant.describe() item = current_room.get_item() if item is not None: item.describe() command = input("> ") if command in ['north', 'east', 'south', 'west']: current_room = current_room.move(command) elif command == 'talk': inhabitant.talk() elif command == 'fight': print('what combat item will you use?') combat_item = input("> ") if combat_item in backpack: if inhabitant.fight(combat_item) == True: current_room.character = None else: dead = True else: print('you do not have that combat item, please choose another') elif command == 'take': backpack.append(current_room.get_item().name) current_room.item = None
print("请输入一个数:") a = input() b = pow(eval(a), 3) print("{0:-^20}".format(b))
# 备注的使用 # coding=utf-8 # !@Author : YaoLei # TempConvert.py # 温度转换实例 TempStr = input('请输入带有符号的温度值,如82F或18C:') if TempStr[-1] in ['F', 'f']: C = (eval(TempStr[0:-1])-32)/1.8 print("转换后的温度是{:.2f}C".format(C)) elif TempStr[-1] in ['C', 'c']: F = 1.8*eval(TempStr[0:-1])+32 print("转换后的温度是{:.2f}F".format(F)) else: print('输入格式错误') def data_read(file_path): # 读取文本文件内容并打印 f = open(file_path, 'r', encoding='UTF-8-sig') lis = [] for line in f: line = line.replace('\n', '') lis.append(line.split(',')) f.close() print(lis) return data_read('成绩.测试文本')
# 学习文件的打开 # 文件操作的步骤:打开-操作-关闭 def read_txt1(): # 遍历全文本,方法一 fo = open('文件操作.测试文本', 'r', encoding='UTF-8') # 文件路径需要为反斜杠\或//,如'd:\45\3.tet', # 'r' 只读 'w' 覆盖写模式 'x' 创建写模式 'a'追加写模式 't' 文件以文本文件打开,'b' 文件以二进制打开 # '+' 与r/w/x/a一同使用,增加同时读写功能 txt = fo.read() # 读人全部内容,一次读入,全文处理 fo.close() # 文件的关闭 return print(txt) def read_txt2(): # 遍历全文本,方法二 fo = open('文件操作.测试文本', 'r', encoding='UTF-8') txt = fo.read(2) while txt != "": txt = fo.read(2) # 按数量读入,逐步处理 fo.close() return print(txt) def read_txt3(): # 逐行遍历文件,方法一 fo = open('文件操作.测试文本', 'r', encoding='UTF-8') for line in fo.readlines(): print(line) fo.close() def read_txt4(): # 逐行遍历文件,方法二 fo = open('文件操作.测试文本', 'r', encoding='UTF-8') for line in fo: print(line) fo.close() # read_txt4() def write_txt1(): fo = open('文件写入.测试文本', 'w+', encoding='UTF-8') fo.write("我爱中国") # 向文件中写入字符串 ls = ['china', 'jeep', 'jap'] fo.writelines(ls) # 将一个元素全为字符串的列表写入文件 fo.seek(0) # 0 文件开头 1 当前位置 2 文件结尾 ,如无此行,则无法输出 for line in fo: print(line) fo.close() write_txt1()
abc = {'A' : 'Z', 'a' : 'z', 'B' : 'Y', 'b' : 'y', 'C' : 'X', 'c' : 'x', 'D' : 'W', 'd' : 'w', 'E' : 'V', 'e' : 'v', 'F' : 'U', 'f' : 'u', 'G' : 'T', 'g' : 't', 'H' : 'S', 'h' : 's', 'I' : 'R', 'i' : 'r', 'J' : 'Q', 'j' : 'q', 'K' : 'P', 'k' : 'p', 'L' : 'O', 'l' : 'o', 'M' : 'N', 'm' : 'n', 'N' : 'M', 'n' : 'm', 'O' : 'L', 'o' : 'l', 'P' : 'K', 'p' : 'k', 'Q' : 'J', 'q' : 'j', 'R' : 'I', 'r' : 'i', 'S' : 'H', 's' : 'h', 'T' : 'G', 't' : 'g', 'U' : 'F', 'u' : 'f', 'V' : 'E', 'v' : 'e', 'W' : 'D', 'w' : 'd', 'X' : 'C', 'x' : 'c', 'Y' : 'B', 'y' : 'b', 'Z' : 'A', 'z' : 'a'} def encryptDecrypt(message): newMessage = '' for letter in message: # checks for space if(letter != ' '): #adds the corresponding letter from the lookup_table newMessage += abc[letter] else: # adds space newMessage += ' ' return newMessage
def calc(val): if (val % 2 == 0): val = val**2 else: val = 1/val*1000 return val print(calc(22), type(calc(22))) #print(calc("x"))
# Importing modules import os, csv # Assigning a variable to the file getting read path = os.path.join("Resources", "election_data.csv") #Defining variables/lists total_votes = 0 votes = [] candidate = 0 candidates = [] vote_percentage = [] winner = 0 # Opening the variable storing the file with open(path) as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") # Skiping headers if csv.Sniffer().has_header: next(csv_reader) for row in csv_reader: total_votes += 1 candidate = row[2] # Adding votes to candidates if candidate in candidates: candidate_a = candidates.index(candidate) votes[candidate_a] = votes[candidate_a] + 1 # If candidate doesn't exist, add it to candidate list else: candidates.append(candidate) votes.append(1) # Calculate vote % and determine winner winner_votes = votes[0] for i in range(len(candidates)): percentage = round((votes[i]/total_votes)*100, 2) vote_percentage.append(percentage) if votes[i] > winner_votes: winner_votes = votes[i] elected = candidates[winner] # Printing Results print("Election Results") print("-------------------------") print(f"Total Votes: {(total_votes)}") print("-------------------------") for i in range(len(candidates)): print(f"{candidates[i]}: {vote_percentage[i]}% ({votes[i]})") print("-------------------------") print(f"Winner: {elected}") print("-------------------------") # Creating/opening a .txt file results_file = open("PyPoll_Results.txt", mode = "w") # Printing Results within the .txt file results_file.write("Election Results\n") results_file.write("-------------------------\n") results_file.write(f"Total Votes: {(total_votes)}\n") results_file.write("-------------------------\n") for i in range (len(candidates)): results_file.write(f"{candidates[i]}: {vote_percentage[i]}% ({votes[i]})\n") results_file.write("-------------------------\n") results_file.write(f"Winner: {elected}\n") results_file.write("-------------------------\n") # Finishing results printing results_file.close() # Moving .txt file to correct directory import shutil shutil.move ("PyPoll_Results.txt", "Analysis")
from abc import abstractmethod from typing import List, Dict import pandas as pd class AbstractDataSource: @abstractmethod def read_data(self, *args, **kwargs) -> List[Dict]: """ :return: list of dicts with the same keys """ pass class CSV(AbstractDataSource): def __init__(self, path): self._path = path def read_data(self, to_dict=True, **read_csv_kwargs) -> (List[Dict], pd.DataFrame): res = pd.read_csv(self._path, **read_csv_kwargs) return res.to_dict('records') if to_dict else res
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] queue = deque() queue.append(root) ans = [] while queue: temp = [] for _ in range(len(queue)): cur = queue.popleft() temp.append(cur.val) for child in cur.children: queue.append(child) ans.append(temp) return ans
class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: n = len(board) m = len(board[0]) x, y = click[0], click[1] directions = [-1, 0, 1] def dfs(x, y): if board[x][y] == "M": board[x][y] = "X" return if board[x][y] == "E": # check surrounding num of mine count = 0 for x_dir in directions: for y_dir in directions: if not (x_dir, y_dir) == (0, 0): nex_x, nex_y = x + x_dir, y + y_dir if 0 <= nex_x < n and 0 <= nex_y < m: if board[nex_x][nex_y] == "M": count += 1 if count > 0: board[x][y] = str(count) # we must return in this step!!! Otherwise we gona hit the Mine! return else: board[x][y] = "B" # dfs for the neighbours for x_dir in directions: for y_dir in directions: if not (x_dir, y_dir) == (0, 0): nex_x, nex_y = x + x_dir, y + y_dir if 0 <= nex_x < n and 0 <= nex_y < m: dfs(nex_x, nex_y) else: return dfs(x, y) return board
#!/usr/bin/python ''' takes contents of delimited file and transposes columns and rows outputs to txt file ''' import re def detect_delimiter(row): pattern = re.compile(r'[a-zA-Z0-9"\']') return pattern.sub('', row)[0] def transpose(i, o=None, d=','): f = open (i, 'r') file_contents = f.readlines () f.close () out_data = map((lambda x: d.join([y for y in x])), zip(* [x.strip().split(d) for x in file_contents if x])) if o: f = open (o,'w') # here we map a lambda, that joins the first element of a column, the # header, to the rest of the members joined by a comma and a space. # the lambda is mapped against a zipped comprehension on the # original lines of the csv file. This groups members vertically # down the columns into rows. f.write ('\n'.join (out_data)) f.close () return out_data
# 小飞机 # 来源:https://www.nowcoder.com/practice/5cd9598f28f74521805d2069ce4a108a?tpId=107&tqId=33282&rp=1&ru=%2Fta%2Fbeginner-programmers&qru=%2Fta%2Fbeginner-programmers%2Fquestion-ranking # 描述:按格式输出*的飞机 # 矩阵:6*12 for i in range(6): for j in range(12): if i==0 or i==1: if j==5 or j==6: print("*",end="") else: print(" ",end="") if i == 2 or i == 3: print("*", end="") if i==4 or i==5: if j==4 or j==7: print("*",end="") else: print(" ",end="") print() # 换行
import random print("HELLO AND WELCOME TO THE UNBIASED DICE :") print("DO YOU WISH TO ROLL THE DICE?[y/n]") b = input() if b == 'y': a = random.randint(1,6) print("YOU GOT A ",a) if b == 'n': print("OKAY THEN ......")
print('hello world') print(3+1) # 将我们的数据输出到文件当中 # a表示如果有文件就追加,如果没有文件就新建文件 fp = open('D:/helloPython.txt', 'a+') print('hahahaha', file=fp) #换行输出 # 关闭文件 #fp.close() # 不进行换行操作的输出 print('hello','world','python') print('hello','world','python',file=fp) fp.close() #ret = input('请输入数据') #print(ret) ''' money = 1000 s = int(input('请输入取款金额:')) if money >= s: money = money - s print('取款成功,余额为:',money) else: print('取款失败!余额为',money) ''' # 计算1~100之间的偶数和 ret = 0 a = 0 while a <= 100: if a%2 == 0: ret += a a += 1 print('和为 :', ret) #水仙花数 for item in range(100,1000): ge = item % 10 shi = item//10%10 bai = item//100 if ge**3 + shi**3 + bai **3 == item: print(item) # 输入两个数,计算一下这两个数的和 a = input("请输入第一个数:") b = input("请输入第二个数:") # 下面这样智能完成字符串的拼接 print((a+b), type(a+b)) # 应该为 a = int(a) b = int(b) print((a+b), type(a+b))
# given a list of random numbers, chose a series of numbers from this list, making the sum largest # every twos numbers that we chose from original list are not adjacent. import numpy as np def max_sum(arr, i): if i == 0: return arr[0] elif i == 1: return max(arr[0], arr[1]) else: return max(max_sum(arr, i-2)+arr[i], max_sum(arr, i-1)) def dp_max_sum(arr): opt = np.zeros(len(arr)) opt[0] = arr[0] opt[1] = arr[1] for i in range(2, len(arr)): A = opt[i-2]+arr[i] B = opt[i-1] opt[i] = max(A, B) return opt[len(arr)-1] if __name__ == "__main__": arr = [1, 2, 4, 1, 7, 8, 3] print(max_sum(arr, 6)) print(dp_max_sum(arr))
# coding: utf-8 # from bottom to top, every point has two base point # 1. select the larger one and plus it as the max sum for current point. def dp_max_sum(triangle): result = triangle for x in range(len(triangle)-2, -1, -1): for y in range(0, len(triangle[x])): # get two children point and select the larger one bases_list = get_base(x, y) left_base = triangle[bases_list[0][0]][bases_list[0][1]] right_base = triangle[bases_list[1][0]][bases_list[1][1]] result[x][y] = result[x][y] + max(left_base, right_base) print(result) def get_base(x, y): left = [x + 1, y] right = [x + 1, y + 1] bases_list = [left, right] return bases_list if __name__ == "__main__": triangle = [[2], [5, 4], [1, 4, 7], [8, 6, 9, 6] ] dp_max_sum(triangle)
# 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. # Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. with open('../practical5/task5.txt', 'w', encoding='utf-8') as f: numbers = input('введите числа через пробел: ') f.write(numbers + '\n') numbers = map(int, numbers.split()) sum_numbers = sum(numbers) line = f'Сумма чисел: {sum_numbers}' print(line) f.write(line + '\n') f.close() # образец решения # with open('../practical5/task5.txt', 'w') as f: # nums = input('Введите целые числа через пробел: ') # f.write('Введенные числа: ' + nums + '\n') # nums = map(int, nums.split()) # without list # sum_nums = sum(nums) # f.write('Сумма чисел: ' + str(sum_nums)) # print('Сумма введенных чисел:', sum_nums) # print('Все записано в файл') # на заметку: # без указания кодировки при создании, получаю криивую кодировку кирилицы при записи # почитал про менеджер контекста, отдельно закрывать файл похоже не требуется
# 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: # имя, фамилия, год рождения, город проживания, email, телефон. # Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. data = { 'name': 'имя', 'surname': 'фамилия', 'year_birth': 'год рождения', 'city': 'город проживания', 'email': 'email', 'phone': 'телефон' } def opros(): text = {} count = 0 for key, items in data.items(): count += 1 answer = input(f'Введите "{items}": ') while (answer == '' and count == 1) or (answer == '' and count == 2): answer = input(f'Введите обязательное значение "{items}": ') break while answer: text[key] = answer break return otvet(name=text.get('name'), year_birth=text.get('year_birth'), city=text.get('city'), email=text.get('email'), phone=text.get('phone'), surname=text.get('surname')) def otvet(name, surname, year_birth='None', city='None', email='None', phone='None'): text = f'Здравствуйте {surname} {name}! ' \ f'Проверьте введенные данные: ' \ f'День рождения: {year_birth}; Город: {city}; E-mail: {email}; Телефон: {phone}' return text ask = input(opros()) print(ask)
# 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. # Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. print('3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn') x = str(input('Введите число "X": ')) x = int(x) + int(x + x) + int(x + x + x) print(f'x + xx + xxx = {x}')
#-*- coding:utf-8 -*- #定制类 class Student(object): def __init__(self,name): self.name=name def __str__(self): return 'Student object (name:%s)' % self.name __repr__=__str__ print(Student('Michael')) class Fib(object): def __init__(self): self.a,self.b=0,1 def __iter__(self): return self def __next__(self): self.a,self.b=self.b,self.a+self.b if self.a>100: raise StopIteration(); return self.a for n in Fib(): print(n) class Fib(object): def __getitem__(self,n): a,b = 1,1 for x in range(n): a,b=b,a+b return a f = Fib() print('f[10]:',f[10]) class Fib(object): def __getitem__(self,n): if isinstance(n,int): a,b = 1,1 for x in range(n): a,b = b,a+b return a if isinstance(n,slice): start = n.start stop = n.stop if start is None: start = 0 a,b=1,1 L = [] for x in range(stop): if x >=start: L.append(a) a,b = b,a+b return L f = Fib() print(f[0:5]) print(f[:10:3]) class Student(object): def __init__(self): self.name='Mic' def __getattr__(self,attr): if attr=='score': return 99 s = Student() print(s.name) print(s.score) class Student(object): def __getattr__(self,attr): if attr=='age': return lambda:25 # raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr) s=Student() print(s.age()) print(s.attr) class Chain(object): def __init__(self,path=''): self._path = path def __getattr__(self,path): return Chain('%s/%s' % (self._path,path)) def __str__(self): return self._path __repr__=__str__ print(Chain().status.user.timeline.list) class Student(object): def __init__(self,name): self.name = name def __call__(self): print('My name is %s' % self.name) s = Student('Mic') print(s()) class Chain(object): def __init__(self,path='GET'): self._path = path def __getattr__(self,path): return Chain('%s/%s' % (self._path,path)) def __call__(self,path): return Chain('%s/%s' % (self._path,path)) def __str__(self): return self._path __repr__=__str__ print(Chain().users('michael').repos) class FunctionalList: def __init__(self,values=None): if values is None: self.values=[] else: self.values=values def __len__(self): return len(self.values) def __getitm__(self,key): self.values[key] def __setitem__(self,key,value): self.values[key]=value def __delitem__(self,key): del self.values[key] def __iter__(self): return iter(self.values) def __reversed__(self): return reversed(self.values) def append(Self,value): self.values.append(value) def head(self): return self.values[0] def tail(self): return self.values[1:] def init(self): return self.values[:-1] class Entity: def __init__(self,size,x,y): self.x,self.y=x,y self.size=size def __call__(self,x,y): self.x,self.y=y,x
from polygon import Polygon class Rectangle(Polygon): def __init__(self, side1, side2): self.side1 = side1 self.side2 = side2 def draw(self): print("Rectangle with width and height") def getAria(self): return self.side1 * self.side2
# ##########for문을 이용해서 구구단 출력하기 ############### # for i in range(2,10): #2~9까지의 범위만큼 i가 반복합니다. # for j in range(2,10): #i가 2일때 j는 2,3,4,5,6,7,8,9 i가 3일때 j는 2,3,4,5,6,7,8,9 이런식으로 반복합니다. # print(i,"X",j,"=",i*j) #,로 구분해서 for문이 돌때마다 변하는 i와 j그리고 그 곱하기 기호와 = 기호로 이어줍니다. # ##########한번만 답할수있는 구구단 게임 ################## # import random #python에서 제공해주는random함수입니다. # # random.randrange(2,10) <- 이렇게 2~9까지의 랜덤한 숫자를 보여줍니다. # a = random.randrange(2,10) # b = random.randrange(2,10) # answer = a * b #실제 정답 값을 answer에다가 넣어서 비교해주려 하고 있습니다. # input_value = int(input( str(a) + " X " + str(b) + " = ")) # 입력 받은 값을 int로 바꿔서 정답과 비교합니다 # #그런데 이때 input의 도움말을 보여줄껀데 a와 b는 현재 int이므로 문자열과 + 로 연결해줄수 없습니다. # #따라서 int인 a와 b을 str()로 둘러싼다음 string으로 형변환을 해주고 +로 문자와 연결해 도움말을 보여 주도록합시다. # if (answer == input_value): #실제 곱한 값이랑 사용자가 입력한 input_value랑 같으면 정답을 print해줍니다. # print("정답입니다") # else: # print("오답입니다.") ############# 함수를 이용한 여러번 대답하는 구구단게임 ############### import random def gugudan(): #반복적으로 사용할 예정이므로 함수화 시켜주었습니다. a = random.randrange(2,10) b = random.randrange(2,10) answer = a * b #실제 정답 값을 answer에다가 넣어서 비교해주려 하고 있습니다. input_value = int(input( str(a) + " X " + str(b) + " = ")) # 입력 받은 값을 int로 바꿔서 정답과 비교합니다 #그런데 이때 input의 도움말을 보여줄껀데 a와 b는 현재 int이므로 문자열과 + 로 연결해줄수 없습니다. #따라서 int인 a와 b을 str()로 둘러싼다음 string으로 형변환을 해주고 +로 문자와 연결해 도움말을 보여 주도록합시다. if (answer == input_value): print("정답입니다") return True#함수가 실행되면 print() 동작 뿐만아니라 return으로 True, False를 반환하여 반복문을 컨트롤 해줍니다. else: print("오답입니다") return False while True: #항상 반복문이 돌아가도록 True로 설정해놓습니다. gogo = gugudan() #gugudan 함수를 실행하고 return 되는 True값 혹은 False값을 gogo 라는 변수에 담아놓습니다. if gogo == False: #gugudan이 실행되고 만약 오답을 입력하면 return값이 False이므로 gogo에는 False값이 담길 것이고 #그렇게 되면 break로 가장 가까운 반복문인 while문을 탈출하게되고 구구단을 끝내게 됩니다. break
import copy import random from typing import List # ------------------------------------- State = List[List[str]] class TicTacToeGame(object): smarter = True # If smarter is True, the computer will do some extra thinking - it'll be harder for the user. triplets = [[(0, 0), (0, 1), (0, 2)], # Row 1 [(1, 0), (1, 1), (1, 2)], # Row 2 [(2, 0), (2, 1), (2, 2)], # Row 3 [(0, 0), (1, 0), (2, 0)], # Column 1 [(0, 1), (1, 1), (2, 1)], # Column 2 [(0, 2), (1, 2), (2, 2)], # Column 3 [(0, 0), (1, 1), (2, 2)], # Diagonal 1 [(0, 2), (1, 1), (2, 0)] # Diagonal 2 ] initial_board = [["_", "_", "_"], ["_", "_", "_"], ["_", "_", "_"]] def __init__(self, board=None): if board is not None: self.board = board else: self.board = copy.deepcopy(self.initial_board) def get_state(self) -> State: return self.board def is_new_game(self) -> bool: return self.board == self.initial_board def display_row(self, row): ''' Takes the row passed in as a list and returns it as a string. ''' row_string = " ".join([e.strip() for e in row]) return("[ {} ]\n".format(row_string)) def display_board(self, board): ''' Takes the board as a nested list and returns a nice version for the user. ''' return "".join([self.display_row(r) for r in board]) def get_value(self, board, position): return board[position[0]][position[1]] def board_is_full(self, board): ''' Determines if the board is full or not. ''' for row in board: for element in row: if element == "_": return False return True def contains_winning_move(self, board): # Used for current board & trial computer board ''' Returns true if all coordinates in a triplet have the same value in them (x or o) and no coordinates in the triplet are blank. ''' for triplet in self.triplets: if (self.get_value(board, triplet[0]) == self.get_value(board, triplet[1]) == self.get_value(board, triplet[2]) != "_"): return True return False def get_locations_of_char(self, board, char): ''' Gets the locations of the board that have char in them. ''' locations = [] for row in range(3): for col in range(3): if board[row][col] == char: locations.append([row, col]) return locations def two_blanks(self, triplet, board): ''' Determines which rows/columns/diagonals have two blank spaces and an 'o' already in them. It's more advantageous for the computer to move there. This is used when the computer makes its move. ''' o_found = False for position in triplet: if self.get_value(board, position) == "o": o_found = True break blanks_list = [] if o_found: for position in triplet: if self.get_value(board, position) == "_": blanks_list.append(position) if len(blanks_list) == 2: return blanks_list def computer_move(self, board): ''' The computer's logic for making its move. ''' my_board = copy.deepcopy(board) # First the board is copied; used later on blank_locations = self.get_locations_of_char(my_board, "_") x_locations = self.get_locations_of_char(board, "x") # Gets the locations that already have x's corner_locations = [[0, 0], [0, 2], [2, 0], [2, 2]] # List of the coordinates of the corners of the board edge_locations = [[1, 0], [0, 1], [1, 2], [2, 1]] # List of the coordinates of the edge spaces of the board if blank_locations == []: # If no empty spaces are left, the computer can't move anyway, so it just returns the board. return board if len(x_locations) == 1: # This is special logic only used on the first move. # If the user played first in the corner or edge, the computer should move in the center. if x_locations[0] in corner_locations or x_locations[0] in edge_locations: board[1][1] = "o" # If user played first in the center, the computer should move in the corner. It doesn't matter which corner. else: location = random.choice(corner_locations) row = location[0] col = location[1] board[row][col] = "o" return board # This logic is used on all other moves. # First I'll check if the computer can win in the next move. If so, that's where the computer will play. # The check is done by replacing the blank locations with o's and seeing if the computer would win in each case. for row, col in blank_locations: my_board[row][col] = "o" if self.contains_winning_move(my_board): board[row][col] = "o" return board else: my_board[row][col] = "_" # Revert if not winning # If the computer can't immediately win, it wants to make sure the user can't win in their next move, so it # checks to see if the user needs to be blocked. # The check is done by replacing the blank locations with x's and seeing if the user would win in each case. for row, col in blank_locations: my_board[row][col] = "x" if self.contains_winning_move(my_board): board[row][col] = "o" return board else: my_board[row][col] = "_" # Revert if not winning # Assuming nobody will win in their next move, now I'll find the best place for the computer to win. for row, col in blank_locations: if ('x' not in my_board[row] and my_board[0][col] != 'x' and my_board[1][col] != 'x' and my_board[2][col] != 'x'): board[row][col] = 'o' return board # If no move has been made, choose a random blank location. If smarter is True, the computer will choose a # random blank location from a set of better locations to play. These locations are determined by seeing if # there are two blanks and an 'o' in each row, column, and diagonal (done in two_blanks). # If smarter is False, all blank locations can be chosen. if self.smarter: blanks = [] for triplet in self.triplets: result = self.two_blanks(triplet, board) if result: blanks = blanks + result blank_set = set(blanks) blank_list = list(blank_set) if blank_list == []: location = random.choice(blank_locations) else: location = random.choice(blank_list) row = location[0] col = location[1] board[row][col] = 'o' return board else: location = random.choice(blank_locations) row = location[0] col = location[1] board[row][col] = 'o' return board def is_valid_move(self, move): ''' Checks the validity of the coordinate input passed in to make sure it's not out-of-bounds (ex. 5, 5) ''' try: split_move = move.split(",") row = split_move[0].strip() col = split_move[1].strip() valid = False if row in ("1", "2", "3") and col in ("1", "2", "3"): valid = True except IndexError: valid = False return valid def tictactoe(self, move): board = self.board printed_boards = dict(after_player = "", after_computer = "") # Subtraction must be done to convert to the right indices, since computers start numbering at 0. row = (int(move[0])) - 1 column = (int(move[-1])) - 1 if board[row][column] != "_": return ("filled", printed_boards) else: board[row][column] = "x" printed_boards['after_player'] = self.display_board(board) # Check to see if the user won/drew after they made their move. If not, it's the computer's turn. if self.contains_winning_move(board): return ("player_win", printed_boards) if self.board_is_full(board): return ("draw", printed_boards) self.computer_move(board) printed_boards['after_computer'] = self.display_board(board) # Checks to see if the computer won after it makes its move. (The computer can't draw, so there's no point # in checking.) If the computer didn't win, the user gets another turn. if self.contains_winning_move(board): return ("computer_win", printed_boards) return ("next_turn", printed_boards) # ------------------------------------- long_help_text = ("*Help for Tic-Tac-Toe bot* \n" "The bot responds to messages starting with @mention-bot.\n" "**@mention-bot new** will start a new game (but not if you're " "already in the middle of a game). You must type this first to start playing!\n" "**@mention-bot help** will return this help function.\n" "**@mention-bot quit** will quit from the current game.\n" "**@mention-bot <coordinate>** will make a move at the given coordinate.\n" "Coordinates are entered in a (row, column) format. Numbering is from " "top to bottom and left to right. \n" "Here are the coordinates of each position. (Parentheses and spaces are optional). \n" "(1, 1) (1, 2) (1, 3) \n(2, 1) (2, 2) (2, 3) \n(3, 1) (3, 2) (3, 3) \n") short_help_text = "Type **@tictactoe help** or **@ttt help** to see valid inputs." new_game_text = ("Welcome to tic-tac-toe! You'll be x's and I'll be o's." " Your move first!\n" "Coordinates are entered in a (row, column) format. " "Numbering is from top to bottom and left to right.\n" "Here are the coordinates of each position. (Parentheses and spaces are optional.) \n" "(1, 1) (1, 2) (1, 3) \n(2, 1) (2, 2) (2, 3) \n(3, 1) (3, 2) (3, 3) \n " "Your move would be one of these. To make a move, type @mention-bot " "followed by a space and the coordinate.") quit_game_text = "You've successfully quit the game." unknown_message_text = "Hmm, I didn't understand your input." already_playing_text = "You're already playing a game!" mid_move_text = "My turn:" end_of_move_text = { "filled": "That space is already filled, sorry!", "next_turn": "Your turn! Enter a coordinate or type help.", "computer_win": "Game over! I've won!", "player_win": "Game over! You've won!", "draw": "It's a draw! Neither of us was able to win.", } # ------------------------------------- class ticTacToeHandler(object): ''' You can play tic-tac-toe in a private message with tic-tac-toe bot! Make sure your message starts with "@mention-bot". ''' META = { 'name': 'TicTacToe', 'description': 'Lets you play Tic-tac-toe against a computer.', } def usage(self): return ''' You can play tic-tac-toe with the computer now! Make sure your message starts with @mention-bot. ''' def handle_message(self, message, bot_handler): command = message['content'] original_sender = message['sender_email'] storage = bot_handler.storage if not storage.contains(original_sender): storage.put(original_sender, None) state = storage.get(original_sender) user_game = TicTacToeGame(state) if state else None move = None if command == 'new': if not user_game: user_game = TicTacToeGame() move = "new" if not user_game.is_new_game(): response = " ".join([already_playing_text, short_help_text]) else: response = new_game_text elif command == 'help': response = long_help_text elif (user_game) and user_game.is_valid_move(coords_from_command(command)): move, printed_boards = user_game.tictactoe(coords_from_command(command)) mid_text = mid_move_text+"\n" if printed_boards['after_computer'] else "" response = "".join([printed_boards['after_player'], mid_text, printed_boards['after_computer'], end_of_move_text[move]]) elif (user_game) and command == 'quit': move = "quit" response = quit_game_text else: response = " ".join([unknown_message_text, short_help_text]) if move is not None: if any(reset_text in move for reset_text in ("win", "draw", "quit")): storage.put(original_sender, None) elif any(keep_text == move for keep_text in ("new", "next_turn")): storage.put(original_sender, user_game.get_state()) else: # "filled" => no change, state remains the same pass bot_handler.send_message(dict( type = 'private', to = original_sender, subject = message['sender_email'], content = response, )) def coords_from_command(cmd): # This function translates the input command into a TicTacToeGame move. # It should return two indices, each one of (1,2,3), separated by a comma, eg. "3,2" ''' As there are various ways to input a coordinate (with/without parentheses, with/without spaces, etc.) the input is stripped to just the numbers before being used in the program. ''' cmd = cmd.replace("(", "") cmd = cmd.replace(")", "") cmd = cmd.replace(" ", "") cmd = cmd.strip() return cmd handler_class = ticTacToeHandler
from sense_hat import SenseHat import time from math import cos, sin, radians, degrees, sqrt, atan2 """ Sense HAT Sensors Display ! Select Temperature, Pressure, or Humidity with the Joystick to visualize the current sensor values on the LED. Note: Requires sense_hat 2.2.0 or later """ sense = SenseHat() green = (0, 255, 0) red = (255, 0, 0) blue = (0, 0, 255) white = (255, 255, 255) inCal = (-4,2,43.5,71,93.5,114,137,162,186,214,242.5,269,311,356,360) outCal = (0,0,30,60,90,120,150,180,210,240,270,300,360,360) calData = ( (0, -4), \ (0, 2), \ (30, 43.5), \ (60, 71), \ (90, 93.5), \ (120, 114), \ (150, 137), \ (180, 162), \ (210, 186), \ (240, 214), \ (270, 242.5), \ (300, 269), \ (330, 311), \ (360, 356), \ (360, 360) ) sense.clear() sense.set_pixel(0,0,green) sense.set_pixel(7,0,blue) sense.set_pixel(0,7,white) sense.set_pixel(7,7,red) time.sleep(5) def show_t(): sense.show_letter("T", back_colour = red) time.sleep(.5) def show_p(): sense.show_letter("P", back_colour = green) time.sleep(.5) def show_h(): sense.show_letter("H", back_colour = blue) time.sleep(.5) def update_screen(angle, show_letter = False): yorig = 3 xorig = 3 ca = cos(radians(angle)) sa = sin(radians(angle)) sense.clear() for l in range(-10,0): x = int(ca*float(l)/2 + xorig) y = int(sa*float(l)/2 + yorig) if x >= 0 and x <= 7 and y >= 0 and y <= 7: sense.set_pixel(x,y,white) for l in range(0,10): x = int(ca*float(l)/2 + xorig) y = int(sa*float(l)/2 + yorig) if x >= 0 and x <= 7 and y >= 0 and y <= 7: sense.set_pixel(x,y,red) sense.set_pixel(xorig,yorig,green) #### # Intro Animation #### show_t() show_p() show_h() # update_screen("temp") index = 0 sensors = ["temp", "pressure", "humidity"] startTime = time.time() logFile=open("/home/pi/Projects/VMS/orientation_raw.csv","w+") #### # Main game loop #### sense.clear() while True: # selection = False # events = sense.stick.get_events() # for event in events: # # Skip releases # if event.action != "released": # if event.direction == "left": # index -= 1 # selection = True # elif event.direction == "right": # index += 1 # selection = True # if selection: # current_mode = sensors[index % 3] # update_screen(current_mode, show_letter = True) # # if not selection: # current_mode = sensors[index % 3] # update_screen(current_mode) elapsedTime = time.time() - startTime gyroRaw = sense.get_gyroscope_raw() accelRaw = sense.get_accelerometer_raw() magRaw = sense.get_compass_raw() orientation = sense.get_orientation_degrees() # print("0,{0},{x},{y},{z}".format(elapsedTime,**gyroRaw)) # rad/sec # print("1,{0},{x},{y},{z}".format(elapsedTime,**accelRaw)) # Gs # print("2,{0},{x},{y},{z}".format(elapsedTime,**magRaw)) # logFile.write("0,{0},{x},{y},{z}\r\n".format(elapsedTime,**gyroRaw)) # rad/sec # logFile.write("1,{0},{x},{y},{z}\r\n".format(elapsedTime,**accelRaw)) # Gs logFile.write("2,{0},{x},{y},{z}\r\n".format(elapsedTime,**magRaw)) # microT orientation = sense.get_orientation_degrees() if(orientation["pitch"] > 180): orientation["pitch"] = orientation["pitch"] - 360 if(orientation["roll"] > 180): orientation["roll"] = orientation["roll"] - 360 print("3,{0},{pitch},{roll},{yaw}".format(elapsedTime,**orientation)) # yawRaw = orientation["yaw"] # for idx in range(len(inCal)): # if yawRaw < inCal[idx]: # break # print(idx) # delta = (yawRaw - inCal[idx-1])/(inCal[idx]-inCal[idx-1]) # print(delta) # calYaw = outCal[idx-1] + delta * (outCal[idx] - outCal[idx-1]) # orientation["yaw"] = calYaw # print("ot 3,{0},{1},{2},{3}".format(elapsedTime,orientation["pitch"],orientation["roll"],calYaw)) logFile.write("3,{0},{pitch},{roll},{yaw}".format(elapsedTime,**orientation)) # # xTiltComp = -1*accelRaw["x"] # yTiltComp = accelRaw["y"] # xyTiltMag = sqrt(xTiltComp**2 + yTiltComp**2) # xyTilt = degrees(atan2(xTiltComp/xyTiltMag,yTiltComp/xyTiltMag)) # print(xyTilt) # update_screen(float(-1*orientation["yaw"])) # update_screen(float(-1*orientation["pitch"])) # update_screen(float(xyTilt)-90.0) # time.sleep(0.1) # #north = sense.get_compass() # north = 0 # print("{0},{1},{2},{3},{4}".format(elapsedTime,orientation["pitch"],orientation["roll"],orientation["yaw"], north)) # time.sleep(10)
from robots import Robot class Fleet: def __init__(self): self.robots = [] # stores robot objects def create_fleet(self): for i in range(3): name = "Robot" + str(i + 1) self.robots.append(Robot(name))
# --- class --- import calendar from tkinter import * class TkinterCalendar(calendar.Calendar): def formatmonth(self, master, year, month): dates = self.monthdatescalendar(year, month) frame = Frame(master) self.labels = [] for i,j in enumerate(["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]): ter = Label(frame, text=j) ter.grid(row=0, column=i+1, padx=7, pady=7) #สร้างหัวตาราง จ-อา for r, week in enumerate(dates): labels_row = [] for c, date in enumerate(week): label = Button(frame, text=date.strftime('%d')) #สร้างตารางในแต่ละวัน label.grid(row=r+1, column=c+1, pady=7) if date.month != month: label['bg'] = 'Yellow' #เดือนอื่นที่ไม่ได้อยู่ในหน้านั้น if c == 6: label['fg'] = 'Black' #Sunday HighLight labels_row.append(label) self.labels.append(labels_row) return frame root = Tk() root.option_add("*Font", "Impact 30") #ขนาดและFont tkcalendar = TkinterCalendar() #เรียกใช้Function TkinterCalender frames = Frame(root) frames.pack() bottom = Frame(root) bottom.pack() back_but = Button(frames, text="back") back_but.pack(side="left") date_label = Label(frames, text = "2020/12") #ปุ่มNext Back เวลา Searchเดือนและปี date_label.pack(side="left") next_but = Button(frames, text="Next") next_but.pack(side="left") gets_but = Button(bottom, text="Search") gets_but.pack() for year, month in [(2020, 12)]: frame = tkcalendar.formatmonth(root, year, month) #เอาค่าวันในเดือนและปีนั้นๆมา (เรียนใช้Function) frame.pack() root.mainloop() #Credit: https://stackoverflow.com/questions/47954439/make-a-calendar-view-for-events-in-python-tkinter
class Ordenamiento(): def __init__(self): pass # Retorna la Lista Invertida @staticmethod def insertsort(lista): for i in range(1,len(lista)): pos = i while pos > 0 and lista[pos-1] > lista[i]: pos -= 1 lista = lista[:pos] + [lista[i]] + lista[pos:i] + lista[i+1:] return lista[::-1] #Retorna La lista Normal @staticmethod def qsaux(lista): if len(lista) == 1 or len(lista)==0: return lista else: pivote = lista[-1] menores = [x for x in lista[:-1] if x < pivote] mayores = [x for x in lista[:-1] if x >= pivote] return Ordenamiento.qsaux (menores) + [pivote] + Ordenamiento.qsaux (mayores)
""" program: average_scores.py Author: Ondrea Last date modfied: 06/07/20 The purpose of this program is to read in one person's names, first and last, their age and three scores out of 100. The program wants to take the three scores and find the average, storing into a variable. """ def average(score1, score2, score3): # Get input for scores # declare variables, use score1, score2, score3 in calculation average_score = (score1 + score2 + score3)/3 print ("the average score is: ", average_score) return average_score #declare variables, use score1, score2, score3 in calculation if __name__ == '__main__': score1 = int(input("What is score1?")) score2 = int(input("What is score2?")) score3 = int(input("What is score3?")) #calculate average scores average_score = average(score1, score2, score3) #user will input last name and first name last_name = input("last name:") first_name = input("first name:") #user will input age here age = input("age:") #Print output #lastname, firstname, age, average grade with .2 precision print(f'{last_name}, {first_name} age:{age:} average grade: {average_score}') #Example output: Rodriguez, Linda age: 21 average grade: 92.50 #Program output: Li, Ondrea age:17 average grade:95.33
# Read an integer: a = int(input()) next = True if a%100 == 0: next = False if a < 1000: amnt = 10 else: amnt = 100 while a > amnt: a = int(a/10) if next == True: print (a+1) else: print(a)
class stack(): def __init__(self): self.q1 = [] self.q2 = [] return def push(self, x): if len(self.q1) == 0: self.q1.append(x) else: self.q2.append(x) while len(self.q1) >0: self.q2.insert(0, self.q1.pop()) self.q1 = self.q2.copy() self.q2 = [] print(self.q1) return def pop(self): if len(self.q1) == 0: return("Stack is empty") else: return self.q1.pop() stak = stack() stak.push(4) stak.pop() #return 4 stak.push(5) stak.push(6) stak.push(7) stak.push(8) print(stak.pop()) print(stak.pop()) print(stak.pop()) print(stak.pop()) print(stak.pop())
def height_rows(student_heights): arr = [[student_heights[0]]] row = 0 for x in student_heights: if arr[row][-1] >= x: arr[row].append(x) else: arr.append([x]) return (len(arr)) test1 = [5, 4, 8, 1] #2 test2 = [8, 6, 9,12, 14, 5] #4 print(height_rows(test1)) print(height_rows(test2))
''' Given a string that may contain a letter f. Print the index of the first and last occurrence of f. If the letter f occurs only once, then output its index once. If the letter f does not occur, print -1. ''' s = input() ind1 = ind2 = -1 for x in range(len(s)): if s[x] == 'f': if ind1 == -1: ind1 = x ind2 = x else: ind2 = x if ind1 == ind2: print(ind1) else: print(ind1, ind2)
def flip(arr, k): for i in range(k//2): arr[i], arr[k-i-1] = arr[k-i-1], arr[i] print (k) print(arr) return k def is_sorted(arr): for x in range(len(arr)-1): if arr[x] > arr[x+1]: return False return True def pancake_sort(nums): k_vals = [] unsorted = len(nums) while(unsorted > 0): max_ind = 0 for x in range(unsorted): if nums[x] > nums[max_ind]: max_ind = x if max_ind != 0: k_vals.append(flip(nums, max_ind+1)) k_vals.append(flip(nums, unsorted)) unsorted-=1 max_ind =0 if is_sorted(nums): return k_vals return k_vals test = [5, 2, 3, 4, 1] print(pancake_sort(test))
def first_missing_positive_integer(integers): integers.sort() count = 1 for y in integers: if y == count: count += 1 return count
# Read an integer: a = int(input()) b = int(input()) c = int(input()) # Print a value: a *= c b *= c if b >= 100: a += b//100 b%= 100 print(str(a) + " " + str(b))
# Read the numbers like this: students = int(input()) apples = int(input()) # Print the result with print() print(apples // students) print(apples % students) # Example of division, integer division and remainder: """ print(63 / 5) print(63 // 5) print(63 % 5) """
def binarySearch(nums, find_num, start, stop): if start > stop: return -1 else: mid = start+((stop-start)//2) print(mid) if nums[mid] == find_num: return mid elif find_num < nums[mid]: return binarySearch(nums, find_num, start, mid-1) else: return binarySearch(nums, find_num, mid+1, stop) nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] print(binarySearch(nums, 1, 0, len(nums)-1))
# Given two integers A and B (A ≤ B). Print all numbers from A to B inclusively. a = int(input()) b = int(input()) s = "" for x in range(a, b+1): s += str(x) + " " print (s)
def nlp_calculator(statement): statement = statement.split() a = word_to_num([statement[1]]) b = word_to_num([statement[-1]]) nums_ans = translator[statement[0]](a,b) return num_to_word(nums_ans) def word_to_num(words): words = "".join(words) if words in word_dict: return word_dict[words] words = words.split("-") num = 0 for word in words: if word in word_dict: num += word_dict[word] return num def num_to_word(num): ans = "" if str(num)[0] == '-': ans+="negative " num *= -1 temp = num while num: if temp in num_dict: ans += num_dict[temp] num -= temp else: remainder = num%10 temp = num - remainder ans += num_dict[temp] + "-" num = temp = remainder return ans def add(a,b): return a + b def subtract(a,b): return b - a def multiply(a,b): return a * b def divide(a, b): return round(a/b) translator = { "add": add, "subtract":subtract, "multiply": multiply, "divide":divide, } word_dict = { "zero":0, "one": 1, "two":2, "three":3, "four":4, "five":5, "six":6, "seven":7, "eight":8, "nine":9, "ten":10, "eleven":11, "twelve":12, "thirteen":13, "fourteen":14, "fifteen":15, "sixteen":16, "seventeen":17, "eighteen":18, "nineteen":19, "twenty":20, "thirty":30, "fourty":40, "fifty":50, "sixty":60, "seventy":70, "eighty":80, "ninety":90, "one-hundred":100 } num_dict = { 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen", 17:"seventeen", 18:"eighteen", 19:"nineteen", 20:"twenty", 30:"thirty", 40:"fourty", 50:"fifty", 60:"sixty", 70:"seventy", 80:"eighty", 90:"ninety", } test1 ="subtract thirty-four from seventy" print(nlp_calculator(test1))
class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Tree: def __init__(self): self.root = None def print_bfs(self): if not self.root: return queue = [self.root] while len(queue) > 0: current_node = queue.pop(0) print(current_node.data) if current_node.left: queue.append(current_node.left) if current_node.right: queue.append(current_node.right) def in_order_traversal(self): nodes = [] def dfs(node): if node: dfs(node.left) nodes.append(node.data) dfs(node.right) dfs(self.root) return nodes ### ALL CODE BELOW IS MINE, REST WAS PROVIDED ### def add(self,node): if not self.root: self.root = node return curr = self.root def add_to_tree(self, curr): if node.data < curr.data: if curr.left == None: curr.left = node return add_to_tree(self, curr.left) if node.data > curr.data: if curr.right == None: curr.right = node return add_to_tree(self, curr.right) add_to_tree(self, curr) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] tree = Tree() tree.add(Node(55)) tree.add(Node(20)) tree.add(Node(30)) tree.add(Node(100)) tree.add(Node(15)) tree.add(Node(200)) tree.add(Node(60)) print(tree.in_order_traversal())
import time # ԂvNX class ProcessingTimer(object): def __init__(self, label = "processing time"): self.start_time = 0 # Jn self._label = label def __enter__(self): self.start_time = time.time() def __exit__(self, exc_type, exc_val, exc_tb): print( '{} : {:.3f} [s]'.format(self._label, time.time() - self.start_time))
import threading import Queue class IndexQueue: "Thread-safe dictionary-like (used for register file reading)." def __init__(self): self.data = {} self.data_lock = threading.Lock() def put(self, key, value): with self.data_lock: if not key in self.data: self.data[key] = Queue.Queue() self.data[key].put(value) def get(self, key, timeout=None): with self.data_lock: if not key in self.data: self.data[key] = Queue.Queue() try: value = self.data[key].get(timeout=timeout) except Queue.Empty: raise IOError("could not read %X" % key) return value def clear(self, key): if not key in self.data: return while not self.data[key].empty(): self.data[key].get() class InfiniteSemaphore: "Fake a threading.Semaphore with infinite capacity." def acquire(self, blocking=None): if blocking is None: pass else: return True def release(self): pass
import time from binary_search_tree import BSTNode start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() duplicates = [] # Return the list of duplicates in this data structure # Replace the nested for loops below with your improvements # for name_1 in names_1: # for name_2 in names_2: # if name_1 == name_2: # duplicates.append(name_1) # BST sped up search from 6+ seconds to .16 seconds bst = BSTNode("") for name in names_1: bst.insert(name) for name in names_2: if bst.contains(name): duplicates.append(name) end_time = time.time() print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n") print(f"runtime: {end_time - start_time} seconds") # ---------- Stretch Goal ----------- # Python has built-in tools that allow for a very efficient approach to this problem # What's the best time you can accomplish? Thare are no restrictions on techniques or data # structures, but you may not import any additional libraries that you did not write yourself. # list comprehension performed search in 1.5 seconds duplicates = [name for name in names_1 if name in names_2] # Using sets finished search in 0.0229 seconds which was the fastest overall # & sign between two sets works the same as set(list1).intersection(list2) duplicates = set(names_1) & set(names_2)
""" pessoa e o modulo onde esta criada a classe Pessoa. Pessoa maisculo e a classe q estou herdando. Quando eu faço uma herança eu herdei os metodos da classe em questao, neste exemplo agora eu tenho os metodos andar e chorar da clase Pessoa e mais o metodo bicicleta q fiz na classe BB. """ # Realizando a importaçao da classe Pessoa from pessoa import Pessoa #Herdamos da classe Pessoa class BB (Pessoa): def __init__(self, nome, mae): print("Método construtor da sub classe") super().__init__(nome, mae) #Acessa o metodo construtor da super classe Pessoa q estou herdando. self.nome = nome self.mae = mae # Especializacao da classe def bicicleta (self): print("Agora aprendendo a pedalar...")
class CalculoReal(object): def __init__(self,cotacao,valorReal): self.valorReal = valorReal self.cotacao = cotacao if self.cotacao <= 0: raise ("Cotacao Invalida") print("chegou aqui...") def converter(self): print (self.valorReal / self.cotacao) if __name__ == "__main__": cotacao = 0.00 p = CalculoReal (cotacao,120.00) p.converter()
""" This is our main python file for Trump as a Movie for January monthly Hack """ import requests movie = input("Enter movie name: ") movie_title_bit = movie.replace(' ', '+') r = requests.get("http://www.omdbapi.com/?t="+movie_title_bit+"&y=&plot=short&r=json") data = r.json() movie_rating = float(data["imdbRating"])*10 print(movie + "'s Movie rating is " + str(movie_rating) + "%") print('pls w8...') r = requests.get("http://elections.huffingtonpost.com/pollster/donald-trump-favorable-rating.json") polls = r.json()['polls'] trump_rating = float(polls[len(polls) - 1]['choices']['Favorable']) print("And Trump's Approval rating is " + str(trump_rating) + '%') if movie_rating > trump_rating: print('That means ' + movie + '\'s rating is ' + str(movie_rating - trump_rating) + '% better than Trump! :D') else: print('That means Trump is ' + str(trump_rating - movie_rating) + '% better than ' + movie + '! D:')
#Modify the constructor for the fraction class so that it checks to make sure that the numerator and denominator are both integers. If either is not an integer the constructor should raise an exception. def inputNumber(message): while True: try: userInput = int(input(message)) except ValueError: print("Please input an integer!") continue else: return userInput break n = int(inputNumber("input numerator")) d = int(inputNumber("input denominator")) class Fraction: def __init__(self,top,bottom): self.num = top self.den = bottom def __str__(self): return str(self.num) + "/" + str(self.den) def getNum(self): return self.num def getDen(self): return self.den myfraction = Fraction(n,d) print(myfraction)
from os import walk def create_dict(folder): f, dict_here = [], [] for (dirpath, dirnames, filenames) in walk(folder): f.extend(filenames) break for i in range(len(f)): dictl='music/{}/{}'.format(folder,f[i]) dict_here.append(dictl) with open("{}.txt".format(folder),"w") as f: for i in range(0,len(dict_here)): f.writelines("{}|music/songbg.jpg\n".format(dict_here[i])) return dict_here print(create_dict('disgust'))
import matplotlib.pyplot as plt import numpy as np from ReadingData import * ''' Creates bar graphs for first and second questions using matplotlib ''' #format long labels by splitting words onto new lines def format_labels(dict): for key in dict: if ' ' in key: new_key = '\n'.join(key.split(' ')) dict[new_key] = dict[key] del dict[key] def first_graph(): q1 = first_question() format_labels(q1) fig, ax = plt.subplots() graph = plt.bar(np.arange(len(q1.keys())), q1.values(), align='center', alpha=0.5) plt.xticks(np.arange(len(q1.keys())), q1.keys()) plt.xlabel('Language Group') plt.ylabel('Number of People Who Speak at Home') ax.set_yscale('log') #set to log scale plt.title('Languages Spoken at Home in the US, 2009-2013') plt.show() def second_graph(): q2 = second_question() format_labels(q2) #convert from "less than very well" to "very well" by subtracting from 100% english = [] for value in q2.values(): english.append(100-value) fig, ax = plt.subplots() graph = plt.bar(np.arange(len(q2.keys())), english, align='center', alpha=0.5) plt.xticks(np.arange(len(q2.keys())), q2.keys()) plt.xlabel('Language Group') plt.ylabel('Percentage of People Who Speak English "Very Well"') plt.ylim(ymax=100) #set max of y axis to 100% plt.title('English Ability by Language, 2009-2013') plt.show()
# -------------- #Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Reading the file data=pd.read_csv(path) #Code starts here # Step 1 #Reading the file #Creating a new variable to store the value counts loan_status= data['Loan_Status'].value_counts() #Plotting bar plot loan_status.plot(kind = 'bar') # Step 2 #Plotting an unstacked bar plot property_and_loan = data.groupby(['Property_Area','Loan_Status']).size().unstack() #Changing the x-axis label plt.xlabel('Property Area') #Changing the y-axis label plt.ylabel('Loan Status') #Rotating the ticks of X-axis plt.xticks(rotation = 45) # Step 3 #Plotting a stacked bar plot education_and_loan = data.groupby(['Education','Loan_Status']).size().unstack() #Plotting a stacked bar plot to compare education status and Loan status education_and_loan.plot(kind= 'bar', stacked = False) #Changing the x-axis label plt.xlabel('Education Status') #Changing the y-axis label plt.ylabel('Loan Status') #Rotating the ticks of X-axis plt.xticks(rotation = 45) # Step 4 #Subsetting the dataframe based on 'Education' column graduate = data[data['Education'] == 'Graduate'] graduate.head(10) #Subsetting the dataframe based on 'Education' column not_graduate = data[data['Education'] == 'Not Graduate'] not_graduate.head(10) #Plotting density plot for 'Graduate' graduate['LoanAmount'].plot(kind = 'density', label = 'Graduate') #Plotting density plot for 'Graduate' not_graduate['LoanAmount'].plot(kind = 'density', label = 'Not Graduate') #For automatic legend display plt.legend() # Step 5 #Setting up the subplots fig , (ax_1, ax_2, ax_3) = plt.subplots(nrows = 3, ncols = 1, figsize = (10,12)) #Plotting scatter plot ax_1.scatter(data['ApplicantIncome'],data['LoanAmount']) #Setting the subplot axis title ax_1.set(title = 'Applicant Income') #Plotting scatter plot ax_2.scatter(data['CoapplicantIncome'],data['LoanAmount']) #Setting the subplot axis title ax_2.set(title = 'Coapplicant Income') #Creating a new column 'TotalIncome' data['TotalIncome'] = data['ApplicantIncome'] + data['CoapplicantIncome'] #Plotting scatter plot ax_3.scatter(data['TotalIncome'],data['LoanAmount']) #Setting the subplot axis title ax_3.set(title = 'Total Income')
num = int(input("Enter number: ")) STR = input("Enter string: ")
def Perfect(): a = int(input("Enter a number: ")) sum = 0 for x in range(1,a): if(a % x == 0): sum += x if(sum == a): print("The number is perfect") else: print("The number is imperfect") menu() def Armstrong(): a = int(input("Enter a number: ")) b = len(str(a)) sum = 0 c = a while (a > 0): r = a % 10 sum += r ** b a //= 10 if(sum == c): print("The number is Armstrong") else: print("The number is not Armstrong") menu() def Palindrome(): a = input("Enter a number: ") b = a[::-1] print(b) if (a == b): print("The number is palindrome") else: print("The number is not palindrome") menu() def menu(): s = input("Enter the option\n1:Perfect Numbern\n2:Armstrong Number\n3:Palindrome\n4:Exit\n") if s == '1': Perfect() elif s == '2': Armstrong() elif s == '3': Palindrome() elif s == '4': exit() else: print("Something went wrong") menu()
from itertools import combinations def is_sigma_algebra(Omega, E): # check if Omega is in E if Omega not in E: return False # check if E is closed under complement for item in E: if Omega - item not in E: return False # check if E is closed under union for i in range(2, len(E) + 1): combs = list(combinations(E, i)) for comb in combs: union_res = set() for s in comb: union_res = union_res.union(s) if union_res not in E: return False return True if __name__ == '__main__': # Example Omega = set([1, 2, 3, 4]) E = [set(), Omega, set([1, 2]), set([3, 4])] print(is_sigma_algebra(Omega, E)) # Example Omega = set([1, 2, 3, 4]) E = [set(), Omega, set([1, 2]), set([3]), set([4])] print(is_sigma_algebra(Omega, E)) # Example Omega = set([1, 2, 3]) E = [set(), Omega, set([1]), set([2]), set([3]), set([1, 2]), set([1, 3]), set([2, 3])] print(is_sigma_algebra(Omega, E))
# Functions are defined with the keyword def. def add(a, b): """This method adds two numbers""" # The above string is called as docstring that can be used # to demonstrate how the use the function and what it does. return a + b print add(2, 3) # Python functions can return multiple values. def get_details(city): # We will be using nested dictionaries here. database = {"san jose" : {'state' : 'CA', 'population' : 40000}, "detroit" : {'state' : 'MI', 'population' : 85000}} requested_city = city city_details = database[city] requested_city_state = city_details['state'] requested_city_population = city_details['population'] # Returning all three parameters. return requested_city, requested_city_state, requested_city_population city, state, population = get_details("san jose") print city print state print population # Functions allow you to define default values in case one or more of the values are not provided by user. def bake_pizza(crust='wheat', toppings = ('pepperoni', 'bacon')): print 'Baking a pizza with ' + crust + ' crust and ' + str(toppings) + ' toppings.' bake_pizza('italian bread', ('tomato', 'spinach', 'mushrooms')) # all the inputs bake_pizza() # no inputs bake_pizza('whole wheat') # partial inputs
# While loops are as easy as they are powerful. all_numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21) length = len(all_numbers) # len() function lets you find the length of a data structure i = 0 while i < length: print all_numbers[i] i += 1 # Compound increment operator # An infinite loop can be operated using boolean True i = 0 while True: if i > 20: # Without this condition, this loop will run forever break # break gets us out of the loop print i i += 1
import numpy as np from math import * from Common.state import Point import matplotlib.pyplot as plt #from help_functions import * class Agent(object): def __init__(self, in_index, start_pos, goal_pos, in_poi, radius, start_vel = np.zeros(2)): self.pos = start_pos.xy self.goal = goal_pos self.vel = start_vel self.v_des = np.zeros(2) self.r = radius self.index = in_index self.poi = in_poi self.pos_hist = [] # keep track of all positions for later visualization self.is_moving = True self.poi.append(self.goal) def distance_to(self, point): """Returns the euclidian distance from the agent to a point""" return np.linalg.norm(self.pos - point) def vel_ang_ok(self, right_ang, left_ang, vel_ang): """ Checks if the velocity is allowed given right and left boundaries """ if right_ang < 0: right_ang += (2*np.pi) if left_ang < 0: left_ang += (2*np.pi) if vel_ang < 0: vel_ang += (2*np.pi) if right_ang > left_ang: # The velocity need to be larger than left and smaller than right return left_ang < vel_ang < right_ang # If/else to prevent from false negative when right_ang < left_ang < vel_ang if right_ang <= vel_ang <= left_ang: return False else: return True def get_bound_ang(self, agent_b): """ Returns the left and right boundaries given agent a traveling and agent b being and obstacle. """ rad_exp = self.r/10 # How close to each other the agents travel # The line between self and agent b vec_ab = agent_b.pos - self.pos rad_ab = self.r + agent_b.r + rad_exp dist = np.linalg.norm(vec_ab) if dist <= rad_ab: dist = rad_ab theta = atan2(vec_ab[1], vec_ab[0]) # The angle from the x-axis to vec_ab alpha = tan(rad_ab/dist) # The angle from vec_ab to the boundaries # Angles from the x-axis to the boundaries ang_right = theta - alpha ang_left = theta + alpha return [ang_right, ang_left] def vel_ang_ok_neigh(self, test_vel, neighbors, bound_angs): """ Returns if the tested velocity is valid given all the neighbors bounding angles""" for i in range(len(neighbors)): trans_b_a = self.pos + 0.5 *(neighbors[i].vel + self.vel) # <----------- change this to change model diff_vel = test_vel + self.pos - trans_b_a #diff_vel = test_vel - neighbors[i].vel if not self.vel_ang_ok(bound_angs[i][0], bound_angs[i][1], atan2(diff_vel[1], diff_vel[0])): return False return True def get_avoidance_vels(self, neighbors, the_map): """ Returns the velocities for all neighbors that avoids collitions""" v_max = the_map.vehicle_v_max dt = the_map.vehicle_dt # Parameters to control the amount of tested velocities rad_step = v_max/5 ang_step = np.pi/8 # Search limit for the angle lim_ang = 2 * np.pi # Maximum 2π lim_rad = v_max # The angle from the x-axis to the desired velocity (to get to the goal) ang_des = atan2(self.v_des[1], self.v_des[0]) bound_angs = [] # Pairs of angles where velocities between them is not allowed # Calculates the bounds for each neighbor for neighbor in neighbors: bound_angs.append(self.get_bound_ang(neighbor)) if self.vel_ang_ok_neigh(self.v_des, neighbors, bound_angs): if the_map.valid_point(self.pos + (self.v_des * dt )): return [self.v_des] # Finds all the possible velocities pos_vels = [] for ang in np.arange(ang_des-lim_ang/2, ang_des+lim_ang/2, ang_step): for rad in np.arange(0, (lim_rad + rad_step), rad_step): test_vel = np.array([rad * cos(ang), rad * sin(ang)]) if self.vel_ang_ok_neigh(test_vel, neighbors, bound_angs): if the_map.valid_point(self.pos + (test_vel * dt)): pos_vels.append(test_vel) return pos_vels def save_pos(self): self.pos_hist.append(np.copy(self.pos)) def find_best_vel(self, agents, neighbor_limit, the_map): """ Returns the best velocity given the neighbors and goal vel""" neighbors = self.get_neighbors(agents, neighbor_limit) self.update_des_vel(the_map) pos_vels = self.get_avoidance_vels(neighbors, the_map) min_vel_distance = float("infinity") best_vel = np.zeros(2) for pos_vel in pos_vels: vel_distance = np.linalg.norm(self.v_des - pos_vel) if vel_distance < min_vel_distance: best_vel = pos_vel min_vel_distance = vel_distance return best_vel def update_des_vel(self, the_map): """ Updates the desired velocity to get to the next poi""" v_max = the_map.vehicle_v_max dt = the_map.vehicle_dt new_point = self.is_obs_on_path(the_map) while new_point is not None: self.poi.insert(0, Point(new_point, -1)) new_point = self.is_obs_on_path(the_map) vel_needed = self.poi[0].xy - self.pos #if np.linalg.norm(vel_needed) > v_max: vel_needed = vel_needed / np.linalg.norm(vel_needed) vel_needed *= v_max self.v_des = vel_needed def get_neighbors(self, agent_list, limit): """ :param agent: The agent to whom the neighbors will be returned :param agent_list: list of all agents :param limit: The maximum distance which are considered neighborhood :return: list of all the neighbors to agent """ neighbors = [] for agent in agent_list: if agent.index == self.index: continue if np.linalg.norm(agent.pos - self.pos) < limit: neighbors.append(agent) return neighbors def check_route_status(self, limit): if np.linalg.norm(self.poi[0].xy - self.pos) < limit: print("Found point! ind: ", self.index) self.poi.pop(0) if len(self.poi) == 0: self.is_moving = False def is_obs_on_path(self, the_map): """ Returns the closest obstacle on the straight path to the first poi, None if the path is clear """ intersec_point = [] intersec_vert_ind = [] intersec_obstacles = [] path_line = np.array([self.pos, self.poi[0].xy]) for obstacle in the_map.obstacles: for i in range(len(obstacle.vertices)): if obstacle.lines_intersect(obstacle.vertices[i], obstacle.vertices[i - 1], self.pos, self.poi[0].xy): obs_edge = np.array([obstacle.vertices[i], obstacle.vertices[i - 1]]) # Find the intersecting point and save it, save the edge intersec_point.append(self.find_intersecting_point(path_line, obs_edge)) intersec_vert_ind.append(i) intersec_obstacles.append(obstacle) # Finds the edge closest to the current position if len(intersec_obstacles) == 0: return None min_distance = float("infinity") close_edge_vert_index = -1 for point_index, point in enumerate(intersec_point): distance = np.linalg.norm(point-self.pos) if distance < min_distance: min_distance = distance close_edge_vert_index = point_index # Finds the corner of the edge closest to the poi-point col_obstacle = intersec_obstacles[close_edge_vert_index] point_on_col_edge_index = intersec_vert_ind[close_edge_vert_index] close_point = col_obstacle.vertices[point_on_col_edge_index] col_vert = col_obstacle.vertices[point_on_col_edge_index-1] other_vert = col_obstacle.vertices[(point_on_col_edge_index+1)%len(col_obstacle.vertices)] close_point2 = col_obstacle.vertices[point_on_col_edge_index-1] col_vert2 = col_obstacle.vertices[point_on_col_edge_index] other_vert2 = col_obstacle.vertices[point_on_col_edge_index - 2] proj_point = (col_vert - close_point) + other_vert new_point = close_point + ((close_point - proj_point)/np.linalg.norm(close_point - proj_point)) * self.r proj_point2 = (col_vert2 - close_point2) + other_vert2 new_point2 = close_point2 + ((close_point2 - proj_point2)/np.linalg.norm(close_point2 - proj_point2)) * self.r if np.linalg.norm(col_obstacle.vertices[point_on_col_edge_index] - self.poi[0].xy) < np.linalg.norm(col_obstacle.vertices[point_on_col_edge_index-1] - self.poi[0].xy): if the_map.valid_point(new_point): return new_point else: return new_point2 else: if the_map.valid_point(new_point2): return new_point2 else: return new_point def find_intersecting_point(self, path_line, obs_edge): """ Finds the point where the lines cross""" x_mat_line1, x_mat_line2, y_mat_line1, y_mat_line2 = np.ones(path_line.shape), np.ones(path_line.shape),\ np.ones(path_line.shape), np.ones(path_line.shape) x_mat_line1[:, 0] = path_line[:, 0] x_mat_line2[:, 0] = obs_edge[:, 0] y_mat_line1[:, 0] = path_line[:, 1] y_mat_line2[:, 0] = obs_edge[:, 1] div_det = np.linalg.det( np.array([[np.linalg.det(x_mat_line1), np.linalg.det(y_mat_line1)], [np.linalg.det(x_mat_line2), np.linalg.det(y_mat_line2)]])) x_det = np.linalg.det( np.array([[np.linalg.det(path_line), np.linalg.det(x_mat_line1)], [np.linalg.det(obs_edge), np.linalg.det(x_mat_line2)]])) y_det = np.linalg.det( np.array([[np.linalg.det(path_line), np.linalg.det(y_mat_line1)], [np.linalg.det(obs_edge), np.linalg.det(y_mat_line2)]])) return np.array([x_det/div_det, y_det/div_det])
''' Exercicio para descobrir o tamanho de nome do usuario usando strings e len() para calcular o tamanho ''' nome = str(input("\nOlá.\nPor favor, digite seu nome:\n")) if(len(nome) <= 5): print(f"Nome curto, ein {nome}?") elif(len(nome) > 6 and len(nome) <= 8): print(f"Nome na média, {nome}") else: print(f"Que nome longo o seu, {nome}!")
""" Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? """ def swap(matrix, row1, col1, row2, col2): temp = matrix[row1][col1] matrix[row1][col1] = matrix[row2][col2] matrix[row2][col2] = temp # rotates a matrix clockwise by 90 degrees def rotateclockwise(matrix): n = len(matrix) for i in range(n): for j in range(i, n): if j != i: swap(matrix, i, j, j, i) for row in range(n): l = 0 r = n - 1 while r > l: swap(matrix, row, l, row, r) l += 1 r -= 1 return matrix # test case matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rotated = rotateclockwise(matrix) for row in range(len(rotated)): print(rotated[row])
"""Module de gestion des arbres de la briandais. BriandaisTree est la classe associee, et des fonctions de gestion existe afin de manipuler l'arbre de maniere non POO.""" import string import os EXEMPLE = "A quel genial professeur de dactylographie sommes-nous redevables de \ la superbe phrase ci-dessous, un modele du genre, que toute dactylo connait par \ coeur puisque elle fait appel a chacune des touches du clavier de la machine a ecrire ?" def only_alpha(): """Convert unicode string to ascii string without punctuations.""" rstring = "" for word in EXEMPLE: for letter in word: if (letter in string.ascii_lowercase) or \ (letter in string.ascii_uppercase) or \ (letter == ' ') or (letter == '-'): rstring += letter return rstring EXAMPLE = only_alpha() class BriandaisTree(object): """Represent a Briandais Tree, a tree to stock an entire dictionnary.""" def __init__(self, word=None, brother=None): self.key = None self.child = None self.brother = brother self.final = False if word is not None: self.add_word(word) def add_word(self, word): """Add a word to the tree.""" word = word.lower() if len(word) == 0: # Empty word. return None if self.key is None: # On the root uninitialized. self.key = word[0] # Empty tree, so add root. if len(word) == 1: # Word is over. self.final = True else: # Recursively add. self.child = BriandaisTree(word[1:]) elif word[0] == self.key: # Tree already full. if len(word) == 1: # Word is over. self.final = True else: # Recursively add. New tree if child empty. if self.child is None: self.child = BriandaisTree(word[1:]) else: self.child.add_word(word[1:]) # Insert at the right place. else: if self.brother is None: # No brother, add it. self.brother = BriandaisTree(word) elif self.brother.key > word[0]: # Next brother follow the word. thing = self.brother self.brother = BriandaisTree(word, thing) else: # Continue. self.brother.add_word(word) def is_empty(self): """Test if the tree is empty.""" if self.key is None and self.child is None and self.brother is None: return True return False def contains(self, word): """Test if tree contains the word.""" word = word.lower() if len(word) == 0: # Empty IS in the tree. But it could not be. What do you prefer ? return True if self.key is None: # On an uninitialized tree. return False if self.key == word[0]: # On the correct branch. if len(word) == 1: # Word is over. if self.final is True: # Word exists. return True else: # Word doesn't exists. return False if self.child is not None: # Word not over, continue to search. return self.child.contains(word[1:]) return False # No child. Too bad. elif self.key > word[0]: return False elif self.brother is not None: # Continue to search on branch. return self.brother.contains(word) else: return False def number_words(self): """Return the number of words.""" number = 0 if self.final is True: # On a word. Hell yeah. number += 1 if self.key is None: return number # Search if tree has child and brother. if self.child is not None: number += self.child.number_words() if self.brother is not None: number += self.brother.number_words() return number def all_words(self): """Return all the words of the tree.""" words = [] def get_all(tree, buffer=''): """Get all words of the tree.""" if tree.key is None: return None if tree.final is True: words.append(buffer + tree.key) if tree.child is not None: get_all(tree.child, buffer + tree.key) if tree.brother is not None: get_all(tree.brother, buffer) get_all(self) return words def height(self, number=0): """Return the height of the tree.""" if self.key is None: return 0 # On the node, height is 1. Search for chid's height, and compare # to brother height. If brother higher than me, return brother's height. result = 1 if self.child is not None: result += self.child.height() if self.brother is not None: temp = self.brother.height(result) if temp > result: return temp return result # return the average height of all nodes def average_height(self, number=0): """Return the average height of the tree.""" if self.key is None: return 0.0 average = 1.0 if self.child is not None: average += self.child.height() if self.brother is not None: temp = self.brother.height(average) average = round((average + temp) / 2, 2) return average # return the average height of all leaf def av_leaf_height(self): total = [0] moyenne = [0] def aux(self, height): if self.child is None: total[0] += 1 moyenne[0] += height if self.child is not None: aux(self.child, height + 1) if self.brother is not None: aux(self.brother, height) aux(self, 1) return round((moyenne[0] / total[0]), 2) def prefix(self, word): """Get all words which start by the word.""" word = word.lower() words = [] if self.key is None: return [] def get_all(tree, word, buffer=''): """Get all words which start by the word.""" if len(word) == 0: # All words remaining are prefixed by word. if tree.final is True: words.append(buffer + tree.key) if tree.child is not None: get_all(tree.child, word, buffer + tree.key) if tree.brother is not None: get_all(tree.brother, word, buffer) elif tree.key == word[0]: # Prefix isn't over. Explore. buffer += tree.key if tree.final is True and len(word) == 1: words.append(buffer) # Prefix is a word by itself. if tree.child is not None: get_all(tree.child, word[1:], buffer) else: # Explore on brother. if tree.brother is not None: get_all(tree.brother, word, buffer) get_all(self, word) return words def suppress(self, word): """Delete a word from the tree.""" word = word.lower() if len(word) == 0: # Impossible, so return False. return None if self.key == word[0]: # Correct node. if len(word) == 1: # On a leaf. if self.child is None: # Empty tree. if self.final is True: # If tree is a final word. self.final = False if self.brother is not None: # Return brother to suppress itself. return self.brother else: # Brother is None, return True to suppress itself. return True return None else: self.final = False # Suppress but keep structure. return None else: # Anywhere in the tree. if self.child is not None: suppr = self.child.suppress(word[1:]) if suppr is not None: self.child = None if self.final is False: if self.brother is not None:# Return brother to suppress itself. return self.brother else: # Brother is None, return True to suppress itself. return True return None else: # Incorrect node, explore brothers. if self.brother is not None: if self.brother is not True: suppr = self.brother.suppress(word) if suppr is not None: self.brother = suppr if self.final is False and self.child is None: return self.brother # Suppress itself. else: self.brother = None def merge(self, tree): """Add all words from the tree into itself.""" # The easy way... words = tree.all_words() for word in words: self.add_word(word) def __str__(self, buffer=''): """Add a string representation.""" string = '' string += buffer + "Cle : " + self.key + '\n' if self.child is not None: string += self.child.__str__(buffer + ' ') if self.brother is not None: string += self.brother.__str__(buffer) return string def __repr__(self): return self.__str__() def draw(self, filename): def to_dot(self, filename): nodes = ["0 [label=\"root\" color=\"black\"]"] edges = [] id_gen = [1] def aux (tree, father) : if tree.key is None: return None id = id_gen[0] id_gen[0] += 1 edges.append(str(father) + " -> " + str(id)) color = "red" if tree.final else "blue" nodes.append(str(id) + " [label=\"" + tree.key + "\" color=\"" + color + "\"]") if tree.brother is not None: aux(tree.brother, father) if tree.child is not None: aux(tree.child, id) aux(self, 0) fh = open(filename, 'w') fh.write("digraph {\n"); fh.write("\n".join(nodes)) fh.write("\n".join(edges)) fh.write("\n}\n") fh.close to_dot(self, "tmp.dot") os.system("dot -Tpdf tmp.dot -o " + filename) def merge(first, second): """Merge two trees into one.""" # The complex way... if first is None: return second if second is None: return first tree = BriandaisTree() if first.key == second.key: tree.key = first.key tree.child = merge(first.child, second.child) tree.brother = merge(first.brother, second.brother) if first.final is True or second.final is True: tree.final = True elif first.key > second.key: tree.key = second.key tree.child = second.child tree.brother = merge(first, second.brother) if second.final is True: tree.final = True else: tree.key = first.key tree.child = first.child tree.brother = merge(first.brother, second) if first.final is True: tree.final = True return tree # Functions to comply the specifications... def BriandaisTreeVide(): """Retourne un arbre de la briandais vide.""" return BriandaisTree() def NouveauBriandaisTree(word): """Retourne un arbre de la briandais initialise avec le mot word.""" return BriandaisTree(word) def Recherche(tree, word): """Recherche le mot word dans l'arbre tree et indique s'il est dans l'arbre.""" return tree.contains(word) def ComptageMot(tree): """Retourne le nombre de mots de l'arbre tree.""" return tree.number_words() def ComptageNil(tree): """Compte le nombre de pointeurs nuls de l'arbre tree.""" if tree.is_empty(): return 2 else: number = 0 if tree.child is None: number += 1 else: number += ComptageNil(tree.child) if tree.brother is None: number += 1 else: number += ComptageNil(tree.brother) return number def Hauteur(tree): """Retourne la hauteur de l'arbre tree.""" return tree.height() def ProfondeurMoyenne(tree): """Retourne la hauteur moyenne de l'arbre tree.""" return tree.av_leaf_height() def Prefixe(tree, word): """Retourne tous les mots de l'arbre tree commencant par le prefixe word.""" return tree.prefix(word) def Suppression(tree, word): """Supprime le mot word de l'arbre tree s'il existe.""" tree.suppress(word) return tree def Fusion(arbre1, arbre2): "Fusionne les deux arbres arbre1 et arbre2 et retourne un nouvel arbre." return merge(arbre1, arbre2)
# Арифметические операторы # http://pythonicway.com/python-operators # Сложение print(2 + 3) # 5 # Вычитание print(2 - 3) # -1 print(-5 - 3) # -8 # Умножение print(2 * 3) # 6 # Деление print(6 / 3) # 2.0 (FLOAT) print(3 / 2) # 1.5 (FLOAT) # Деление по модулю (получение остатка от деления) print(6 % 2) # 6 - 2 - 2 - 2 = 0 print(7 % 2) # 7 - 2 - 2 - 2 = 1 print(13.2 % 5) # 13.2 - 5 - 5 = 3.2 # Целочисленное деление (отбрасывает дробную часть) print(12 // 5) # 12 / 5 = 2 (2,4) print(7 // 2) # 7 / 2 = 3 (3,5) # Возведение в степень print(5 ** 2) # 25 print(9 ** 0.5) # 3.0 (квадратный корень -> FLOAT) # Несколько операций в одной строке print(2 + 3 * 4) # 14 (3 * 4 = 12, 12 + 2 = 14) print((2 + 3) * 4) # 20 (2 + 3 = 5, 5 * 4 = 20) # Разнотиповые операнды print(2 + 0.5) # 2.5 (FLOAT) # Точность операций print(0.1 + 0.2) # 0.30000000000000004
# Синтаксис языка Python print('Hello world!!!') # Написание кода в одну строку print('Hello world!') print('Hello world!!!') # Написание нескольких функций в одну строку print('Hello'); print('world!!') ''' Пример многострочного комментария ''' """" Еще один пример многострочного комментария """
#commenting functions def get_sum(a, b): # push Ctrl + Q """ Return sum a and b. :param a: First operand :type a: int :param b: Second operand :type b: int :return: Return sum a + b type int """ return a + b print(get_sum(1, 2)) #области видимости a = 5 #global def f(): a = 10 #local a += 1 print(a) print(a) #5 f() #11 print(a) #5 print('************') def b(): global a a += 1 print(a) print(a) #5 b() #6 print(a) #6 print('************') #func return func l = [1, '2', 3] def ff(l): return [i * 2 for i in l] print(ff(l)) #ff = f2 def f2(l): def get_mult(x): if isinstance(x, int): #isinstance проверяет операнд на принадлежность к типу return x * 2 return [get_mult(i) for i in l if get_mult(i)] #для каждого i в списке l запускаем get_mult() в том случае если это не None #return list(map(get_mult, l) print(f2(l)) def f3(l): def get_mult(x): return x * 2 return list(map(get_mult, l)) print(f3(l))
print "---Part I---" students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def names(): for dicts in students: print dicts['first_name'] + ' ' + dicts['last_name'] names() print "---Part II---" #----------------------------------------------- # Part II: users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, {'first_name' : 'Martin', 'last_name' : 'Puryear'} ] } def names_part_2(dictionary): for lists in dictionary: print lists count = 0 for people in dictionary[lists]: count +=1 temp = people['first_name'] + ' ' + people['last_name'] temp = temp + ' ' + str(len(temp)-1) print str(count) + ' - ' + temp names_part_2(users)
a=int(input()) if(a<0): print("Invalid Value!") elif(a<=50): print("cost = {:.2f}".format(a*0.53)) else: print("cost = {:.2f}".format(50*0.53+0.58*(a-50)))
# create a random letter cypher for a string import random def make_dash(string): out_string = '' for char in string: if char != ' ': out_string += '-' else: out_string += char return out_string def make_new_key(): new_alpha = [] alphabet = list('abcdefghijklmnopqrstuvwxyz') alpha_save = alphabet[:] while alphabet: pick = random.choice(alphabet) new_alpha.append(pick) index = alphabet.index(pick) alphabet.pop(index) return dict(zip(alpha_save, new_alpha)) def scramble(string, mapper): out_string = '' for char in string: if char != ' ': out_string += mapper[char] else: out_string += char return out_string sentence = "the quick brown fox jumps over the lazy dog" new_key = make_new_key() print(make_dash(sentence)) print(scramble(sentence, new_key))
# write a function (is_even(n)) that returns true or false depending on whether # a number is even or not # now write a function (filter_it) that takes a function and a list and returns # a new list of numbers that are even. def is_even(n): if n % 2 == 0: return True ''' def filter_it(func, numlist): return [ x for x in numlist if is_even(x) == True] ''' def filter_it(numlist): return [ (lambda x: x % 2 == 0)(x) for x in numlist ] print (filter_it([1,2,3,4,5,6,7,8,9]))
# ''' # In pure functional programming: # # 1. everything is a function # 2. functions are "pure" and have no side effects # 3. data structures are immutable # 4. state is preserved inside a function # 5. recursion is used instead of loops/iteration # # Advantages: # # 1. Absence of side effects makes your programs more robust # 2. Programs are more modular and have smaller building blocks # 3. Easier to test - same parameters return same results # 4. Easier to fit with parallel or concurrent programming # 5. Much less namespacing == fewer mistakes and collisions # # Disadvantages: # # 1. Solutions can look very different and are not as intuitive # 2. Not equally useful for all types of problems # 3. I/O are side effects # 4. Recursion is much more complex to understand than loops/iteration # 5. In Python recursion is slow # # Take away: # # Use the good parts! # 1. Write functions to minimize side effects # 2. Keep everything contained in a function # 3. Keep functions small and modular # 4. Write better tests # ''' # # # Pure functional programming languages can have no loops and control structure: # # Normal statement-based flow control # ''' # if <cond1>: func1() # elif <cond2>: func2() # else: func3() # ''' # # Equivalent functional expression # ''' # (<cond1> and func1()) or (<cond2> and func2()) or (func3()) # ''' # # Example: # x = 3 # # def pr(s): # return s # # # x = 5 # print(x == 1 and pr('one')) or (x == 2 and pr('two')) or (pr('other')) # # # pr = lambda s: s # namenum = lambda x: (x==1 and pr("one")) \ # or (x==2 and pr("two")) \ # or (pr("other")) # # print(namenum(2)) # # # normal iteration loop construction # ''' # for element in lst: # func(element) # ''' # # Equivalent functional expression # ''' # map(func, lst) # ''' # # Example # # def double_it(num_list): # new_out = [] # for num in num_list: # new_out.append(num *2) # return new_out # # print(double_it([1,2,3,4,5,6])) # # # def double(num): # return num * 2 # # print(map(double, list(range(1,7)))) # # # # OR # # # print(map(lambda x: x*2, list(range(1,7)))) # no way to test! # using a functional approach will flatten code: # Nested loop for finding big products def find_bm(lst1, lst2): bigmults = [] for x in lst1: for y in lst2: if x * y > 25: bigmults.append((x,y)) return bigmults xs = [1,2,3,4] ys = [10,15,3,22] print(find_bm(xs, ys))
# Given two text files containing numbers, return a list of the numbers # that they share. (Use happy.txt and primes.txt) # This requires: reading a file, converting from strings to integers # and some list manipulation a_file = open('happy.txt', encoding='utf-8') a_string = a_file.read() a_file.close() b_file = open('primes.txt', encoding='utf-8') b_string = b_file.read() b_file.close() #open primes.text #convert strings to integers # a_list = a_string.split('\n') b_list = b_string.split('\n') string_list = [] print(a_list) print(b_list) for a_num in a_list: for b_num in b_list: if a_num == b_num: string_list.append(a_num) def cleanup(x): listt = [] for char in x: if char != '': listt.append(int(char)) return listt int_list = cleanup(string_list) print(int_list)
# Given a list of ints, write a function find the highest_product you can get from three of the integers. # The input list will always have at least three integers. def product_of_three(alist): #sort the list to put the highest integers at the end alist.sort() #set a total for product total = 1 #prune the list to only give back the last three results for x in alist[:3:-1]: total *= x return total somelist = [1,4,3,20,5,3,10] print (product_of_three(somelist))
import random CELLS = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] def get_locations(): monster = random.choice(CELLS) door = random.choice(CELLS) player = random.choice(CELLS) if monster == door or door == start or start == monster: return get_locations() else: return (monster, door, start) def move_player(player, move): if move.lower() == "left": player = (player[0], player [1]-1) elif move.lower() == "right": player = (player[0], player[1]+1) elif move.lower() == "up": player = (player[0]-1, player[1]) elif move.lower() == "down": player = (player[0]+1, player[1]) return(player) #Check logic def get_moves(player): MOVES = ['LEFT', 'RIGHT', 'UP', 'DOWN'] if player[1] == 0: MOVES = ['RIGHT', 'UP', 'DOWN'] elif player[0] == 0: MOVES = ['LEFT', 'RIGHT', 'DOWN'] elif player[1] == 2: MOVES = ['LEFT','UP', 'DOWN'] elif player[0] == 2: MOVES = ['LEFT', 'RIGHT', 'UP'] return MOVES print(get_moves((1,1))) while True: print("Welcome to the dungeon!") print("You're currently in room {player}") print("You can move {MOVES}") print("Enter QUIT to quit") move = input("> ") move = move.upper() if move == 'QUIT': break # If it's a good move, change the player's position # If it's a bad move, don't change anything # If the new player position is the door, they win! # If the new player position is the monster, they lose! # Otherwise, continue
# Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b, return a string of the form # a-front + b-front + a-back + b-back
# Given two text files containing numbers, return a list of the numbers # that they share. (Use happy.txt and primes.txt) # This requires: reading a file, converting from strings to integers # and some list manipulation a_file = open('happy.txt', encoding='utf-8') a_string = a_file.read() a_file.close()
# write a function (mult) that takes two numbers and returns the result # of multiplying those two numbers together def mult(num1, num2): return num1 * num2 # now write a function(apply_it) that takes three arguments: a function, # and two arguments and returns the result of calling the function with # the two arguments def apply_it(func, arg1, arg2): return(func(arg1, arg2)) print(apply_it(mult, 5, 3))
''' In pure functional programming: 1. everything is a function 2. functions are "pure" and have no side effects 3. data structures are immutable 4. state is preserved inside a function 5. recursion is used instead of loops/iteration Advantages: 1. Absence of side effects makes your programs more robust 2. Programs are more modular and have smaller building blocks 3. Easier to test - same parameters return same results 4. Easier to fit with parallel or concurrent programming 5. Much less namespacing == fewer mistakes and collisions Disadvantages: 1. Solutions can look very different and are not as intuitive 2. Not equally useful for all types of problems 3. I/O are side effects 4. Recursion is much more complex to understand than loops/iteration 5. In Python recursion is slow Take away: Use the good parts! 1. Write functions to minimize side effects 2. Keep everything contained in a function 3. Keep functions small and modular 4. Write better tests ''' # Pure functional programming languages can have no loops and control structure: # Normal statement-based flow control ''' if <cond1>: func1() elif <cond2>: func2() else: func3() ''' # Equivalent functional expression ''' (<cond1> and func1()) or (<cond2> and func2()) or (func3()) ''' # Example: x = 3 def pr(s): return s x = 2 print(x == 1 and pr('one')) or (x == 2 and pr('two')) or (pr('other')) pr = lambda s: s namenum = lambda x: (x==1 and pr("one")) \ or (x==2 and pr("two")) \ or (pr("other")) print(namenum(2)) # normal iteration loop construction ''' for element in lst: func(element) ''' # Equivalent functional expression ''' map(func, lst) ''' # Example def double_it(num_list): new_out = [] for num in num_list: new_out.append(num *2) return new_out print(double_it([1,2,3,4,5,6])) def double(num): return num * 2 print(map(double, list(range(1,7)))) # OR print(map(lambda x: x*2, list(range(1,7)))) # no way to test! # using a functional approach will flatten code: # Nested loop for finding big products def find_bm(lst1, lst2): bigmults = [] for x in lst1: for y in lst2: if x * y > 25: bigmults.append((x,y)) return bigmults xs = [1,2,3,4] ys = [10,15,3,22] print(find_bm(xs, ys))
import random def picker(list): list_out = [] list_in = list[:] while list: pick = random.choice(list) list_out.append(pick) index = list.index(pick) list.pop(index) print(dict(zip(list_in, list_out))) list = ['a', 'b', 'c', 'd', 'e'] print(picker(list))
# write a function (is_even(n)) that returns true or false depending on whether # a number is even or not def is_even(n): if n % 2 == 0: return True else: return False # now write a function (filter_it) that takes a function and a list and returns # a new list of numbers that are even. liszt = list(range(2, 78)) def filter_it(funct, liszt): new_list = [] for i in liszt: if funct(i): new_list.append(i) return new_list print(filter_it(is_even, liszt)) # write a function (is_even(n)) that returns true or false depending on whether # a number is even or not # now write a function (filter_it) that takes a function and a list and returns # a new list of numbers that are even.
from tkinter import * from random import randrange as rnd, choice import time root = Tk() root.geometry('800x600') root.title("Catch the ball") canvas = Canvas(root, bg="White") canvas.pack(fill=BOTH,expand=1) colors = ['red', 'orange', 'yellow', 'green', 'blue', 'magenta'] def new_ball(): """ Creates a ball with random size, color at random coordinatws every 1000ms """ canvas.delete(ALL) global ball_x_cord, ball_y_cord, ball_radius ball_x_cord = rnd(100, 700) ball_y_cord = rnd(100, 500) ball_radius = rnd(30, 50) canvas.create_oval(ball_x_cord - ball_radius, ball_y_cord - ball_radius, ball_x_cord + ball_radius, ball_y_cord + ball_radius, fill=choice(colors), width=0) root.after(1000, new_ball) def click_event(event): """ Check, if a click was made in the ball, in this case sends +1 to counter, after, ball is deleted. If click was not in the ball - nothing. """ length_between_p = ((ball_x_cord - event.x) ** 2 + (ball_y_cord - event.y) ** 2) ** 0.5 if length_between_p <= ball_radius: print("попал") else: print("не попал") canvas.bind('<Button-1>', click_event) new_ball() mainloop()
# Take input from user number = int (input("Enter a number to check")) #Now check if number > 1: for i in range(2, number): if number % i == 0: print(number, 'is not a prime number') # Print the reason for not being prime print('Because', i, 'times', number//i, 'is', number) break else: print(number, 'is a prime number') else: print(number, 'is not a prime number')
# -*- coding: utf-8 -*- """ Created on Fri Mar 03 23:04:41 2017 @author: User """ #!/usr/bin/python def nextMove(posr, posc, board): n = len(board[0]) dirt = [] for i in range(n): for j in range(n): if board[i][j] == 'd': dirt.append([abs(posr-i)+abs(posc-j),i,j]) u_d = ('UP', 'DOWN') l_r = ('LEFT', 'RIGHT') dirt = sorted(dirt, key = lambda x:x[0]) target = dirt.pop(0) while target[0] != 0: distance = [posr - target[1], posc - target[2]] for r in range(abs(distance[0])): target[0] -= 1 if distance[0]>0: print u_d[0] return else: print u_d[1] return for c in range(abs(distance[1])): target[0] -= 1 if distance[1]>0: print l_r[0] return else: print l_r[1] return print 'CLEAN' return if __name__ == "__main__": pos = [int(i) for i in raw_input().strip().split()] board = [[j for j in raw_input().strip()] for i in range(5)] nextMove(pos[0], pos[1], board)
from typing import Optional class Node: """ Each Node holds a reference to its previous node as well as its next_node node in the List. """ def __init__(self, value, prev=None, next=None): self.prev = prev self.value = value self.next = next class DoublyLinkedList: """ Our doubly-linked list class. It holds references to the list's head and tail nodes. """ def __init__(self, node_list: Optional[list] = None): self.head = self.tail = None # initialize head and tail to None self.size = 0 # number of items stored in DLL # if given node_list exists if node_list is not None: # then add each value in list to tail for value in node_list: self.add_to_tail(value) def __repr__(self): """Returns a string representation of this DoublyLinkedList""" str_repr = "DLL=[" if self.size == 0: return f"{str_repr}]" current_node = self.head while current_node is not None: str_repr += f"{current_node}{']' if current_node is self.tail else ' -> '}" current_node = current_node.next return str_repr def __len__(self): return self.size def add_to_head(self, value): """ Wraps the given value in a Node and inserts it as the new head of the list. Don't forget to handle the old head node's previous pointer accordingly. """ pass def remove_head(self): """ Removes the List's current head node, making the current head's next_node node the new head of the List. Returns the value of the removed Node. """ pass def add_to_tail(self, value): """ Wraps the given value in a Node and inserts it as the new tail of the list. Don't forget to handle the old tail node's next_node pointer accordingly. """ pass def remove_tail(self): """ Removes the List's current tail node, making the current tail's previous node the new tail of the List. Returns the value of the removed Node. """ pass def move_to_front(self, node): """ Removes the input node from its current spot in the List and inserts it as the new head node of the List. """ pass def move_to_end(self, node): """ Removes the input node from its current spot in the List and inserts it as the new tail node of the List. """ pass def delete(self, node): """ Deletes the input node from the List, preserving the order of the other elements of the List. """ pass def get_max(self): """ Finds and returns the maximum value of all the nodes in the List. """ pass
''' Author@ Elijah_mikaelson Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i **Without using division** ''' def Solution(arr,n): for i in range(n):
# 변수가 가리키는 메모리의 주소 확인 a = [1, 2, 3] print(id(a)) # 2130600743432 #region 리스트를 복사 # 1. 얉은 복사 b = a # 참조에 의한 복사(주소값 복사) print(id(b)) # 2130600743432 print(a is b) # True a[1] = 4 print(a, b) # [1, 4, 3] [1, 4, 3] # 2. 깊은 복사 a = [1, 2, 3] b = a[:] a[1] = 4 print(a, b) # [1, 4, 3] [1, 2, 3] from copy import copy b = copy(a) print(a is b) # False #endregion #region 변수를 만드는 여러 가지 방법 a, b = ('python', 'life') # 튜플로 a, b에 값을 동시에 대입할 수 있다 print(a, b) # python life a, b = 'hello', 'world' # 튜플 부분에서도 언급했지만 튜플은 괄호를 생략해도 된다. print(a, b) # hello world [a,b] = ['python', 'life'] # 리스트로 변수 만들기 print(a, b) # python life a = b = 'python' # 여러 개의 변수에 같은 값 대입 print(a, b) # python python a, b = 'hello', 'world' # 위 방법으로 두 변수의 값 간단하게 바꾸기 a, b = b, a print(a, b) # world hello #endregion
# 딕셔너리 쌍 추가하기 a = {1: 'a'} a[2] = 'b' print(a) # {1: 'a', 2: 'b'} a['name'] = 'pey' print(a) # {1: 'a', 2: 'b', 'name': 'pey'} a[3] = [1,2,3] print(a) # {1: 'a', 2: 'b', 'name': 'pey', 3: [1, 2, 3]} # 딕셔너리 요소 삭제하기 del a[1] print(a) # {2: 'b', 'name': 'pey', 3: [1, 2, 3]} # 딕셔너리에서 Key 사용해 Value 얻기 a = {'a':1, 'b':2} print(a['a'], a['b']) # 1 2 #region 딕셔너리 관련 함수들 # Key 리스트 만들기(keys) # 파이썬 3.0 이후 버전에서는 이러한 메모리 낭비를 줄이기 위해 dict_keys 객체를 돌려준다. # 만약 3.0 이후 버전에서 반환 값으로 리스트가 필요한 경우에는 list(a.keys())를 사용하면 된다. a = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'} print(a.keys()) # dict_keys(['name', 'phone', 'birth']) for k in a.keys(): print(k, end=' ') # name phone birth print() print(list(a.keys())) # ['name', 'phone', 'birth'] # Value 리스트 만들기(values) print(a.values()) # dict_values(['pey', '0119993323', '1118']) # Key, Value 쌍 얻기(items) print(a.items()) # dict_items([('name', 'pey'), ('phone', '0119993323'), ('birth', '1118')] # Key: Value 쌍 모두 지우기(clear) a.clear() print(a) # {} # Key로 Value얻기(get) a = {'name':'pey', 'phone':'0119993323', 'birth': '1118'} print(a.get('name')) # pey -> a.get('name')은 a['name']을 사용했을 때와 동일한 결괏값을 돌려준다. # a['nokey']처럼 존재하지 않는 키(nokey)로 값을 가져오려고 할 경우 a['nokey']는 Key 오류를 발생시키고 a.get('nokey')는 None을 돌려준다 print(a.get('soft')) # None print(a.get('foo', 'bar')) # bar -> 딕셔너리 안에 찾으려는 Key 값이 없을 경우 미리 정해 둔 디폴트 값을 대신 가져온다. # 해당 Key가 딕셔너리 안에 있는지 조사하기(in) a = {'name':'pey', 'phone':'0119993323', 'birth': '1118'} print('name' in a) # True print('email' in a) # False #endregion
import numpy as np import os class Activation(object): def __init__(self): self.state = None def __call__(self, x): return self.forward(x) def forward(self, x): raise NotImplemented def derivative(self): raise NotImplemented class Identity(Activation): def __init__(self): super(Identity, self).__init__() def forward(self, x): self.state = x return x def derivative(self): return 1.0 class Sigmoid(Activation): def __init__(self): super(Sigmoid, self).__init__() def forward(self, x): self.inp = x self.state = 1/(1 + np.exp(-1*x)) return 1/(1 + np.exp(-1*x)) def derivative(self): # Maybe something we need later in here... self.prev = self.state #update the state value now as we have cached the previous value. (will be useful for computing grads later) self.state = self.state*(1 - self.state) return self.state class Tanh(Activation): """ Tanh non-linearity """ # This one's all you! def __init__(self): super(Tanh, self).__init__() def forward(self, x): self.input = x self.state = np.tanh(x) return self.state def derivative(self): self.prev = self.state self.state = 1 - np.power(self.state,2) return self.state class ReLU(Activation): """ ReLU non-linearity """ def __init__(self): super(ReLU, self).__init__() def forward(self, x): self.storage = x self.state = x * (x > 0) return self.state def derivative(self): self.prev = self.state self.state = 1.0 * (self.prev > 0) return self.state # Ok now things get decidedly more interesting. The following Criterion class # will be used again as the basis for a number of loss functions (which are in the # form of classes so that they can be exchanged easily (it's how PyTorch and other # ML libraries do it)) class Criterion(object): """ Interface for loss functions. """ # Nothing needs done to this class, it's used by the following Criterion classes def __init__(self): self.logits = None self.labels = None self.loss = None def __call__(self, x, y): return self.forward(x, y) def forward(self, x, y): raise NotImplemented def derivative(self): raise NotImplemented class SoftmaxCrossEntropy(Criterion): def __init__(self): super(SoftmaxCrossEntropy, self).__init__() self.sm = None def forward(self, x, y): self.logits = x self.labels = y temp = np.sum(np.exp(x), axis = 1).T self.sm = (np.exp(x).T/(temp)).T - y return -1 * np.sum(y * np.log(np.exp(x).T/(temp)).T, axis = 1) def derivative(self): return self.sm class BatchNorm(object): def __init__(self, fan_in, alpha=0.9): # You shouldn't need to edit anything in init self.alpha = alpha self.eps = 1e-8 self.x = None self.norm = None self.out = None # The following attributes will be tested self.var = np.ones((1, fan_in)) self.mean = np.zeros((1, fan_in)) self.gamma = np.ones((1, fan_in)) self.dgamma = np.zeros((1, fan_in)) self.beta = np.zeros((1, fan_in)) self.dbeta = np.zeros((1, fan_in)) # inference parameters self.running_mean = np.zeros((1, fan_in)) self.running_var = np.ones((1, fan_in)) def __call__(self, x, eval=False): return self.forward(x, eval) def forward(self, x, eval=False): # if eval: # # ??? self.x = x # self.mean = # ??? # self.var = # ??? # self.norm = # ??? # self.out = # ??? # update running batch statistics # self.running_mean = # ??? # self.running_var = # ??? # ... raise NotImplemented def backward(self, delta): raise NotImplemented # These are both easy one-liners, don't over-think them def random_normal_weight_init(d0, d1): return np.random.randn(d0,d1) def zeros_bias_init(d): return np.zeros(d) class MLP(object): """ A simple multilayer perceptron """ def __init__(self, input_size, output_size, hiddens, activations, weight_init_fn, bias_init_fn, criterion, lr, momentum=0.0, num_bn_layers=0): # Don't change this --> self.train_mode = True self.num_bn_layers = num_bn_layers self.bn = num_bn_layers > 0 self.nlayers = len(hiddens) + 1 self.input_size = input_size self.output_size = output_size self.activations = activations self.criterion = criterion self.lr = lr self.momentum = momentum # <--------------------- # Don't change the name of the following class attributes, # the autograder will check against these attributes. But you will need to change # the values in order to initialize them correctly self.W = None self.dW = None self.b = None self.db = None # HINT: self.foo = [ bar(???) for ?? in ? ] # if batch norm, add batch norm parameters if self.bn: self.bn_layers = None # Feel free to add any other attributes useful to your implementation (input, output, ...) def forward(self, x): raise NotImplemented def zero_grads(self): raise NotImplemented def step(self): raise NotImplemented def backward(self, labels): raise NotImplemented def __call__(self, x): return self.forward(x) def train(self): self.train_mode = True def eval(self): self.train_mode = False def get_training_stats(mlp, dset, nepochs, batch_size): train, val, test = dset trainx, trainy = train valx, valy = val testx, testy = test idxs = np.arange(len(trainx)) training_losses = [] training_errors = [] validation_losses = [] validation_errors = [] # Setup ... for e in range(nepochs): # Per epoch setup ... for b in range(0, len(trainx), batch_size): pass # Remove this line when you start implementing this # Train ... for b in range(0, len(valx), batch_size): pass # Remove this line when you start implementing this # Val ... # Accumulate data... # Cleanup ... for b in range(0, len(testx), batch_size): pass # Remove this line when you start implementing this # Test ... # Return results ... # return (training_losses, training_errors, validation_losses, validation_errors) raise NotImplemented
# The elevator will first process UP requests where request floor is greater than current floor and # then process Down requests where request floor is lower than current floor. # https://tedweishiwang.github.io/journal/object-oriented-design-elevator.html from enum import Enum from heapq import heappush, heappop class Direction(Enum): up = 'UP' down = 'DOWN' idle = 'IDLE' class RequestType(Enum): external = 'EXTERNAL' internal = 'INTERNAL' class Request: def __init__(self, origin, target, typeR, direction): self.target = target self.typeRequest = typeR self.origin = origin self.direction = direction class Button: def __init__(self, floor): self.floor = floor class Elevator: def __init__(self, currentFloor): self.direction = Direction.idle self.currentFloor = currentFloor self.upStops = [] self.downStops = [] def sendUpRequest(self, upRequest): if upRequest.typeRequest == RequestType.external: heappush(self.upStops, (upRequest.origin, upRequest.origin)) heappush(self.upStops, (upRequest.target, upRequest.origin)) def sendDownRequest(self, downRequest): if downRequest.typeRequest == RequestType.external: heappush(self.downStops, (-downRequest.origin, downRequest.origin)) heappush(self.downStops, (-downRequest.target, downRequest.origin)) def run(self): while self.upStops or self.downStops: self.processRequests() def processRequests(self): if self.direction in [Direction.up, Direction.idle]: self.processUpRequests() self.processDownRequests() else: self.processDownRequests() self.processUpRequests() def processUpRequests(self): while self.upStops: target, origin = heappop(self.upStops) self.currentFloor = target if target == origin: print("Stopping at floor {} to pick up people".format(target)) else: print("stopping at floor {} to let people out".format(target)) if self.downStops: self.direction = Direction.down else: self.direction = Direction.idle def processDownRequests(self): while self.downStops: target, origin = heappop(self.downStops) self.currentFloor = target if abs(target) == origin: print("Stopping at floor {} to pick up people".format(abs(target))) else: print("stopping at floor {} to let people out".format(abs(target))) if self.upStops: self.direction = Direction.up else: self.direction = Direction.idle if __name__ == "__main__": elevator = Elevator(0) upRequest1 = Request(elevator.currentFloor, 5, RequestType.internal, Direction.up) upRequest2 = Request(elevator.currentFloor, 3, RequestType.internal, Direction.up) downRequest1 = Request(elevator.currentFloor, 1, RequestType.internal, Direction.down) downRequest2 = Request(elevator.currentFloor, 2, RequestType.internal, Direction.down) upRequest3 = Request(4, 8, RequestType.external, Direction.up) downRequest3 = Request(6, 3, RequestType.external, Direction.down) elevator.sendUpRequest(upRequest1) elevator.sendUpRequest(upRequest2) elevator.sendDownRequest(downRequest1) elevator.sendDownRequest(downRequest2) elevator.sendUpRequest(upRequest3) elevator.sendDownRequest(downRequest3) elevator.run()
import tensorflow as tf import numpy as np trX = np.linspace(-1, 1, 101) trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 # create a y value which is approximately linear but with some random noise X = tf.placeholder("float") # create symbolic variables Y = tf.placeholder("float") def model(X, w): return tf.multiply(X, w) # lr is just X*w so this model line is pretty simple w = tf.Variable(0.0, name="weights") # create a shared variable (like theano.shared) for the weight matrix y_model = model(X, w) cost = tf.square(Y - y_model) # use square error for cost function train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost) # construct an optimizer to minimize cost and fit line to my data # Launch the graph in a session with tf.Session() as sess: # you need to initialize variables (in this case just variable W) tf.global_variables_initializer().run() for i in range(100): for (x, y) in zip(trX, trY): sess.run(train_op, feed_dict={X: x, Y: y}) print(sess.run(w))
# Program divides the first number by the second number a = int (input("Enter first number: ")) b = int (input("Enter second number: ")) answer = a // b remainder = a % b print(a, "divided by", b, "is", answer, "with a remainder of", remainder) print("{} divided by {} is {} with a remainder of {}" .format (a, b, answer, remainder))
import matplotlib.pyplot as plt import numpy as np # The np.linspace() function in Python returns evenly spaced numbers over # the specified interval which in this case is 40 numbers in range 0-4. # plt.plot is plotting the variables, included are colour and labels # title and x and y labels along with a legend and save file. # the plot then shows for 5 seconds and code ends x = np.linspace(0.0, 4.0, 40) g = x**2 h = x**3 plt.plot(x, x, "r.", label = "f(x) = x") plt.plot(x, g, "y*", label = "g(x) = $x^2$") plt.plot(x, h, "gx", label = "h(x) = $x^3$") plt.title("Weekly_Task_8_Plotting") plt.xlabel("x-axis") plt.ylabel("y-axis") plt.legend() plt.savefig("Weekly_task_8.png") plt.show(block=False) plt.pause(5) plt.close("all")