text
stringlengths
37
1.41M
notas_alunos = dict() def notas(*num, sit=False): """ :param num: As notas passadas para a função. :param sit: Se quer ou não quer mostrar a situação geral das notas. :return: Retorna o total de notas, o maior e menor valor, sua média e a situação geral das nota, caso for pedida. """ notas_alunos["Total"] = len(num) notas_alunos["Maior"] = max(num) notas_alunos["Menor"] = min(num) notas_alunos["Média"] = sum(num)/len(num) if sit: if notas_alunos["Média"] >= 7: notas_alunos["Situação"] = "Boa" elif notas_alunos["Média"] < 5: notas_alunos["Situação"] = "Regular" else: notas_alunos["Situação"] = "Péssima" print(notas_alunos) notas(5.8, 8.5, 6.5, 9.3, 7.4, sit=True) help(notas)
from turtle import * import random import turtle import math turtle.pu() class Ball(Turtle): def __init__(self,x,y,dx,dy,radius,color): Turtle.__init__(self) self.shape("circle") self.shapesize(radius/10) self.radius = radius self.color(color) self.goto(x,y) self.dx = dx self.dy = dy def move(self,width,height): turtle.pu() oldx = self.xcor() oldy = self.ycor() newx = oldx + self.dx newy = oldy + self.dy right_side_ball = (newx + self.radius) left_side_ball = (newx - self.radius) top_side_ball = (newy + self.radius) bottom_side_ball = (newy - self.radius) self.goto(newx,newy) if right_side_ball>width: self.dx = -self.dx if left_side_ball<-width: self.dx = -self.dx if top_side_ball>height: self.dy = -self.dy if bottom_side_ball<-height: self.dy = -self.dy ball_1 = Ball(30,30,50,30,30,"blue") ball_2 = Ball(50,14,20,40,30,"red") turtle.mainloop()
''' import turtle from turtle import Turtle import random turtle.colormode(255) class Square(Turtle): def __init__(self,size,): Turtle.__init__(self) self.shapesize(size) self.shape("square") def random_color(self): r = random.randint(0,256) g = random.randint(0,256) b = random.randint(0,256) self.color(r,g,b) square1 = Square(5) square1.random_color() turtle.mainloop() #do extras ''' from turtle import Turtle import turtle turtle.begin_poly() import turtle turtle.pu() turtle.forward(50) for i in range(6): turtle.pd() turtle.right(60) turtle.forward(50) turtle.end_poly() turtle.register_shape("potato",(turtle.get_poly())) class Hexagon(Turtle): def __init__(self,size): self.shapesize(size) self.shape(potato) turtle.mainloop() hexagon1 = Hexagon(99)
""" This module represents the Consumer. Computer Systems Architecture Course Assignment 1 March 2021 """ # Calin-Andrei Bucur # 332CB from threading import Thread import time class Consumer(Thread): """ Class that represents a consumer. """ def __init__(self, carts, marketplace, retry_wait_time, **kwargs): """ Constructor. :type carts: List :param carts: a list of add and remove actionerations :type marketplace: Marketplace :param marketplace: a reference to the marketplace :type retry_wait_time: Time :param retry_wait_time: the number of seconds that a producer must wait until the Marketplace becomes available :type kwargs: :param kwargs: other arguments that are passed to the Thread's __init__() """ # Call the thread constructor Thread.__init__(self, **kwargs) self.market = marketplace # Initialize the carts and get ids for them self.carts = {} for cart in carts: self.carts[self.market.new_cart()] = cart self.wait_time = retry_wait_time def run(self): # Go through the carts for cart_id in self.carts: # Go through each action in the cart for action in self.carts[cart_id]: # Try doing the action until we do it the necessary number of times while action["quantity"] > 0: flag = False if action["type"] == "add": flag = self.market.add_to_cart(cart_id, action["product"]) else: flag = self.market.remove_from_cart(cart_id, action["product"]) if flag: action["quantity"] -= 1 else: time.sleep(self.wait_time) # Get the final order order = self.market.place_order(cart_id) # Print the bought items for item in order: print(self.name + " bought " + str(item))
import math __author__ = 'Asher' def main(): message = 'Cenoonommstmme oo snnio. s s c' key = 8 plaintext = decryptMessage(key, message) print(plaintext+'|') def decryptMessage(key, message): numColumns = math.ceil(len(message)/key) numRows = key numShaded = (numColumns * numRows) - len(message) plaintext = [''] * numColumns col = 0 row = 0 for symbol in message: plaintext[col] += symbol col += 1 #next column #if there are no more columns or we're at shaded box go to 1st column of the next row if (col == numColumns) or (col == numColumns - 1 and row >= numRows - numShaded): col = 0 row += 1 return ''.join(plaintext) if __name__ == '__main__': main()
# Best O(nlongn) # Average O(nlogn) # Worst O(n^2) # Good for short lists def partition(myArr, low, high): pivot = myArr[low] i = low j = high print("pivot is -- " + str(pivot)) print("high element is --" + str(myArr[high])) while i < j: while True: i += 1 if (myArr[i] > pivot) or (i == len(myArr)-1): break while myArr[j] > pivot: j -= 1 if i < j: temp = myArr[i] myArr[i] = myArr[j] myArr[j] = temp temp1 = myArr[low] myArr[low] = myArr[j] myArr[j] = temp1 print( "sorting in progress ----- " + str(myArr)) return j def quick_sort(myArr, low, high): if low < high: j = partition(myArr, low, high) quick_sort(myArr, low, j) quick_sort(myArr, j+1, high) myArr = [4, 6, 3, 2, 1, 7, 5, 9, 8, 20, 34, 66, 51, 67, 55, 123, 435, 543, 666, 112, 344] #myArr=[4,6,3,2,1,7,5,9,8,20,34,66,51] print("Before sorting ----- " + str(myArr)) quick_sort(myArr, 0, len(myArr) - 1) print("After sorting ----- " + str(myArr))
import random number = random.randint(0,3) words = ["LION","JUICE","BAND","SHREW"] hint1 = ["mane","sweet","music","long nose"] hint2 = ["roar","made of fruit","group","looks kinda like a mole"] secretword = words[number] guess = "" counter = 1 while True: print("Guess the secret word!") print("Type 'hint1', 'hint2', 'first letter', or 'give up' for the answer.") guess = input().upper() if guess == secretword: print("Nice job, you won!") print("It took you " + str(counter) + " guesses.") break elif guess == "HINT1": print( hint1[number] ) elif guess == "HINT2": print( hint2[number] ) elif guess == "FIRST LETTER": print( secretword[0] ) elif guess == "GIVE UP": print( "The secret word was " + secretword ) print("You failed" + str(counter) + " times.") break else: counter += 1 print("Guess again!")
# Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. # You should return an array of all the anagrams or an empty array if there are none. def anagrams(word, words): returnedarray = [] word = sorted(word) for givenword in words: if sorted(givenword) == word: returnedarray.append(givenword) return returnedarray
# Pete likes to bake some cakes. He has some recipes and ingredients. # Unfortunately he is not good in maths. Can you help him to find out, how many cakes he could bake considering his recipes? # Write a function cakes(), which takes the recipe (object) and the available ingredients (also an object) and returns the maximum number of cakes Pete can bake (integer). # For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). # Ingredients that are not present in the objects, can be considered as 0. def cakes(recipe, available): if len(recipe) > len(available): return 0 else: ratio = [] keys = recipe.keys() for key in keys: ratio.append(int(available[key]/recipe[key])) return min(ratio)
# Your friend Bob is working as a taxi driver. After working for a month he is frustrated in the city's traffic lights. # He asks you to write a program for a new type of traffic light. It is made so it turns green for the road with the most congestion. # Example: There are 42 cars waiting on 27th ave. There are 72 cars waiting on 3rd st. # Since there are more cars on 3rd st, the light turn green for that street. # You don't need to worry about the process of detecting cars yet. class SmartTrafficLight(): def __init__(self, st1, st2): self.firststreet = st1[1] self.firststreetcars = st1[0] self.secondstreet = st2[1] self.secondstreetcars = st2[0] def turngreen(self): if (self.firststreetcars > self.secondstreetcars): self.firststreetcars = 0 return self.firststreet elif (self.secondstreetcars > self.firststreetcars): self.secondstreetcars = 0 return self.secondstreet else: return None
# John has invited some friends. His list is: # s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill"; # Could you make a program that makes this string uppercase gives it sorted in alphabetical order by last name. # When the last names are the same, sort them by first name. Last name and first name of a guest come in the result between parentheses separated by a comma. # So the result of function meeting(s) will be: "(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)" def meeting(s): returned = "" firstnames = [] lastnames = [] s = s.upper() st = s.split(";") for item in st: list = item.split(":") firstnames.append(list[1]) lastnames.append(list[0]) sortedlist = sorted(zip(firstnames, lastnames )) print(sortedlist) for name in sortedlist: returned += "(" + name[0] + ", " + name[1] + ")" return returned
# In this kata, your job is to create a class Dictionary which you can add words to and their entries. Example: class Dictionary(): def __init__(self): self.d = {} def newentry(self, word, definition): self.d[word] = definition def look(self, key): if key in self.d: return self.d[key] else: return "Can't find entry for " + key
import random def pickdice(): continueprompting = True dicetype = 0 #Errors while continueprompting: dicetype = int(input("How many sides does your dice have? ")) if not (dicetype in [4,6,8,10,12,20]): print("Invalid amount of sides, choices are 4, 6, 8, 10, 12, and 20") else: continueprompting = False #Assigns min and max numbers for dice to roll if dicetype == 4: maximum = 4 minimum = 1 if dicetype == 6: maximum = 6 minimum = 1 if dicetype == 8: maximum = 8 minimum = 1 if dicetype == 10: maximum = 10 minimum = 1 if dicetype == 12: maximum = 12 minimum = 1 if dicetype == 20: maximum = 20 minimum = 1 #Returns max and mins return maximum,minimum def rolldice(maximum, minimum): maxnum = maximum minnum = minimum print("Rolling the dice...") dicevalue = random.randint(minnum,maxnum) print("The dice rolled a",dicevalue) rollagain = input("Would you like to roll again? ") while rollagain == "Y" or rollagain == "y": print("Rolling the dice...") dicevalue = random.randint(minnum,maxnum) print("The dice rolled a",dicevalue) rollagain = input("Would you like to roll again? ") if rollagain == "N" or rollagain == "n": print("Thank you for using this program! Goodbye!") while rollagain not in ["N","n","Y","y"]: print("Invalid answer...") rollagain = input("Would you like to roll again? ") def main(): maximum, minimum = pickdice() rolldice(maximum,minimum) main()
from math import pow time_1_lenh=22*pow(10,-9) time_1_congdoan=5*pow(10,-9) def step_by_step(n): Step=n*time_1_lenh return Step def pipelining(n): pipe=5*time_1_congdoan+(n-1)*time_1_congdoan return pipe def tile(Step,pipe): tile=pipe/Step return tile
''' Created on Jul 5, 2014 @author: zrehman ''' import unittest import json from collections import OrderedDict """SymbolTable class stores a key-value pair into a table. Given a key, the corresponding value is returned. Both keys and values are stored in two separate lists. """ class SymbolTable: def __init__(self): self.table = OrderedDict() """Put key-value pair into the table (remove key from table for null value) :param key: The key :param value: The value to be stored """ def put(self, key, val): self.table[key] = val """Return value paired with key (null if key is absent) :param key: The key """ def get(self, key): if key in self.table: return self.table[key] """Remove key and it's value from the table :param key: The key """ def delete(self, key): if key in self.table: del self.table[key] """Return True if there is a value paired with key, false otherwise :param key: The key """ def contains(self, key): if key in self.table: return True else: return False """Return if the table is empty """ def is_empty(self): return len(self.table) == 0 """Return the table size(i.e. number of key-value pairs in the table) """ def size(self): return len(self.table) """Return all the keys in the table as a list """ def keys(self): return self.table.keys() """ Private Methods """ def __str__(self): out = "\n" out += "%s\n" %(json.dumps(self.table, indent=4, separators=(',',':'))) return out """ Unit Tests """ class SymbolTableUnitTest(unittest.TestCase): @classmethod def setUpClass(self): self.st = SymbolTable() def test_put(self): st = OrderedDict() keys_l = ['S', 'E', 'A', 'H', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] vals_l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(0, len(keys_l)): self.st.put(keys_l[i], vals_l[i]) def test_print(self): print self.st def test_get(self): self.assertEqual(self.st.get('A'), 6) self.assertEqual(self.st.get('ZZ'), None) def test_contains(self): self.assertEqual(self.st.contains('X'), True) self.assertEqual(self.st.contains('XX'), False) def test_delete(self): self.assertEqual(self.st.contains('E'), True) self.st.delete('E') self.assertEqual(self.st.contains('E'), False) def test_is_empty(self): self.assertEqual(self.st.is_empty(), False) def test_get_keys(self): self.assertEqual(self.st.keys(), ['S', 'A', 'H', 'X', 'M', 'P', 'L']) @classmethod def tearDownClass(self): pass """ Unit Test Runner """ def SymbolTableUnitTestRunner(): tests = ['test_put', 'test_print', 'test_get', 'test_contains', 'test_delete', 'test_is_empty', 'test_get_keys'] return unittest.TestSuite(map(SymbolTableUnitTest, tests)) if __name__ == "__main__": unittest.main(defaultTest='SymbolTableUnitTestRunner', verbosity=2)
#3 variant a = float(input('Введите 1-ое число: ')) b = float(input('Введите 2-ое число: ')) c = float(input('Введите 3-е число: ')) if b==0: print ('введите b, отличное от нуля') else: if a%b == c: print ('a даёт остаток с при делении на b') else: print ('a не даёт остаток с при делении на b') if a==0: print ('введите a, отличное от нуля') else: if c == -b/a: print ('c является решением линейного уравнения ax + b = 0') else: print ('c не является решением линейного уравнения ax + b = 0')
# -*- coding: utf-8 -*- """ Created on Fri Aug 24 02:10:11 2018 @author: Tiago Ibacache """ from threading import Thread,Semaphore import time, c class semaforos(): def __init__(self): self.S1 = Semaphore(1) self.S2 = Semaphore(1) self.S3 = Semaphore(1) def moversemaforos (S1, S2, S3): cola = c.Cola() c.crearcola(cola) while (not c.colavacia(cola)): S1 = c.insertarcola(cola) S2 = c.moveralfinal(cola) S3 = c.moveralfinal(cola) time.sleep(5) S1 = c.moveralfinal(cola) S2 = c.insertarcola(cola) S3 = c.moveralfinal(cola) time.sleep(5) S1 = c.moveralfinal(cola) S2 = c.moveralfinal(cola) S3 = c.insertarcola(cola) time.sleep(5) semaforos(); print (moversemaforos(S1, S2, S3));
""" CURSE PLAYER FUNCTION input: card -- an integer representing a card (can only curse if card == 12 or card == 13) playerNum -- an integer index of the current player PlayerList -- a list of player classes DiscardPile -- an integer list of cards that have been discarded output: PlayerList -- updated with a player cursed and a card removed from the current player's hand DiscardPile -- updated with the played card added to the discard pile @author: David A. Nash """ import numpy as np def cursePlayer(card, playerNum, PlayerList, DiscardPile): if card !=12 and card != 13: print('Error. You cannot curse with card ', card) ##for debugging else: num_players = len(PlayerList) all_cursed = [PlayerList[x].cursed for x in range(num_players) if x!=playerNum] if False in all_cursed: ##only curse other players if any aren't cursed pToCurse = playerNum while pToCurse == playerNum or PlayerList[pToCurse].cursed == True: pToCurse = np.random.randint(0,len(PlayerList)) PlayerList[pToCurse].cursed = True ##apply the curse ##only remove the card if it can actually be played PlayerList[playerNum].cards.remove(card) ##remove the card DiscardPile.append(card) ##add the card to the discard pile return PlayerList, DiscardPile
""" CHOOSE MOVE FUNCTION Select a move from the options available by seeing which maximizes the predicted probability of winning input: Xprev -- input data from the current turn [p1.pos1,p1.pos2,p2.pos1,p2.pos2,p1.turn,p2.turn] roll -- [die1, die2] for the current player parameters -- a dictionary containing parameters for each layer of the network, 'W1', 'b1', etc. Spots -- list of all locations on the board Rand -- a boolean determining whether the move chosen is random or predicted output: Xnext -- new board position based on chosen move (without new rolls generated) Note: (1) Due to the rules of Prime Climb, no pawns can leave position 101. (2) This function uses player classes and takeTurn (therefore, everything else) @author: David A. Nash """ import numpy as np from moveGenerator import simpleMove from forwardProp import forwardProp from bump import bump ##Choose the next position by selecting the maximum potential reward among all possible moves def chooseMove(Xt,roll,parameters, Spots=np.arange(0,102), Rand=False): n = Xt.shape[0]//3 ##number of players order = Xt[-n:,0] ##array of one-hots for current player idx = np.where(order==1)[0][0] ##index of current player pos1 = Xt[2*idx:2*idx+2,0] ##position of current player #possMoves = moveMapper(roll,pos1,[],False, Spots) possMoves = simpleMove(roll,pos1) ##choose the move that has the highest prediction value for the current player if Rand == False: best = 0 ##initialize best win probability bestidx = 0 ##initialize index of best move for i in range(possMoves.shape[0]): Xnext=Xt.copy() Xnext[2*idx:2*idx+2,0] = possMoves[i,0:2] Xnext = bump(Xnext) ##check for bumping ##use forwardProp predictions to rate the options AL, caches = forwardProp(Xnext,parameters) score = AL[idx][0] if score > best: best = score bestidx = i else: ##choose a random move -- for exploration during training bestidx = np.random.randint(0,possMoves.shape[0]) ##return the chosen move with player turn changed Xnext = Xt.copy() Xnext[2*idx:2*idx+2,0] = possMoves[bestidx,0:2] Xnext = bump(Xnext) ##check for bumping ##finally, change whose turn it is Xnext[2*n+idx,0] = 0 idx = (idx + 1)%n Xnext[2*n+idx,0] = 1 return Xnext
""" SEND PLAYER HOME FUNCTION input: card -- an integer representing the card (can only send home if card==10 or card==11) playerNum -- the index of the current player PlayerList -- a list of player classes DiscardPile -- a list of the cards which have been discarded output: PlayerList -- updated with any new positions and hands DiscardPile -- updated with added card played (if any) Note: (1) Due to the rules of Prime Climb, no pawns can leave position 101. @author: David A. Nash """ import numpy as np def sendPlayerHome(card, playerNum, PlayerList, DiscardPile): if card !=10 and card != 11: print('Error. You cannot bump with card ', card) ##for debugging else: ##check whether any other players are away from the start (position 0) offStart = [] ##initialize a list of tuples of the form (player_index,pawn_index) for idx, player in enumerate(PlayerList): if idx == playerNum: #sending self home is take care of during moveMapper continue else: ##cannot bump pawns on 0 or 101 if player.position[1] !=0 and player.position[1]!=101: offStart.append([idx,1]) if player.position[0] !=0: ##if pos[0]==101, then the game should be over offStart.append([idx,0]) if len(offStart)>0: ##then there are pawns to bump which aren't at the start ##choose a random player and pawn from the list of options playerChosen, pawnChosen = offStart[np.random.randint(0,len(offStart))] ##bump that pawn back to start and discard the card played PlayerList[playerChosen].position[pawnChosen]=0 PlayerList[playerChosen].position.sort() ##re-sort the position into increasing order PlayerList[playerNum].cards.remove(card) DiscardPile.append(card) else: print("No one to bump.") ##for debugging return PlayerList, DiscardPile
""" MOVE MAPPER FUNCTION input: roll -- a pair of integers from 0 to 9 (n-1) pos -- a pair of integers (a,b) representing the player's current position availCards -- a list of ints representing the player's current hand curse -- a boolean keeping track of whether the player is currently cursed Spots -- a list of all positions on the board output: finalPos -- an (?,3) array of triples containing all possible *allowable* positions the player could move to in columns 0 and 1, and an encoding of which cards need to be used to get there in column 2. Note: (1) In Prime Climb, rolling doubles gives you 4 copies of the value (not 2) (2) This function makes use of the functions cleanPositions, applyDie, applyCard @author: David A. Nash """ import numpy as np from itertools import permutations from applyCard import applyCard from applyDie import applyDie from cleanPositions import cleanPositions def moveMapper(roll, curr_pos, availCards, curse, Spots): ##initialize the array of positions with the current position iP1 = np.array(curr_pos) ##intermediate Position 1 ''' add the encoding of the cards which have been used. Note that in this encoding, digit i (1-11) corresponds to a one-hot for card i being used Thus, if card 4 has been used, we will add 10^(11-4) ''' iP1 = np.append(iP1, 100000000000) ##create all possible orderings for applying cards and dice ##first generate a scheme of all possible orders in which to apply dice and/or cards ##e.g. with no cards, we can either apply die1 then die2, or die2, then die1 if roll[0] == roll[1]: ##rolled doubles so get 4 copies scheme = np.array([str(roll[0]),str(roll[0]),str(roll[0]),str(roll[0])]) else: scheme = np.array([str(roll[0]),str(roll[1])]) ##Add all available action cards to the scheme generator for card in availCards: if 0<card<12: scheme = np.append(scheme, 'c'+str(card)) scheme = set(permutations(scheme)) ##create all permutations of the scheme list ##it only makes logical sense to move yourself home at the beginning of your turn, otherwise you waste dice ##thus, we'll remove any permutations which have card 10 or 11 played later in the turn if 10 in availCards or 11 in availCards: keepset = [] for x in scheme: if x[0]=='c10' or x[0]=='c11': keepset.append(x) if 10 in availCards and 11 in availCards: scheme = [] for x in keepset: if x[1]=='c10' or x[1]=='c11': scheme.append(x) else: scheme = keepset finalPos = np.array([]) #initialize the array of all complete moves partialFlag = 0 ##a boolean of whether player can win on a partial turn for order in scheme: impossible = False ##flag used to eliminate impossible branches iP2 = iP1.copy().reshape(1,3) ##A list of possible intermediate locations for item in order: #print(iP2.shape) if item[0] == 'c': ##if the first character is c, apply card ##ALSO Keep track of positions without using the card! iP2 = np.append(iP2, applyCard(iP2, int(item[1:]), curse, Spots), axis=0) else: iP2 = applyDie(iP2, int(item), curse, Spots) ##it is possible (although unlikely) to have no allowable moves ##if so, it should ignore these options if iP2.shape[0]==0: impossible=True break if 101 in iP2[:,0]: ##you can win on a partial turn iP2 = iP2[ np.where(iP2[:,0]==101) ] partialFlag = 1 break if not impossible: if len(finalPos)==0: finalPos = iP2.copy() else: finalPos = np.append(finalPos,iP2, axis=0) else: continue if partialFlag == 1: break num = finalPos.shape[0] ##count number of possible positions (triples) ##it is possible to have no options (say b/c of curses), if so, stay put if num==0: finalPos = iP1.copy() ##stay put else: #sort, delete repeats and unallowable positions finalPos = cleanPositions(finalPos, Spots) ##take care of *self* bumping (if pos[0]==pos[1] then one pawn goes back to start) delRow = np.array([]) ##initialize list of rows to delete for idx, pos in enumerate(finalPos): if pos[0] == pos[1] and pos[0] != 101: if pos[1] != 0 and [0, pos[1], pos[2]] in finalPos.tolist(): delRow = np.append(delRow, idx) else: pos[0]=0 ##REMOVE DUPLICATES## finalPos = np.delete(finalPos, delRow.astype('i8'), axis=0) finalPos.view('i8,i8,i8').sort(order=['f0','f1'], axis=0) return finalPos.astype('i8')
from decimal import * print '[#] The Gregory-Leibniz "infinite" series for calculating Pi!' print "[#] Though not very efficient, it will get closer and closer to pi with every iteration, accurately producing " \ "pi to five decimal places with 500,000 iterations." pi = Decimal(0) odd = Decimal(1) loop = int(0) iterats = int(raw_input("Iterations? ")) inc = int(raw_input("Increments? ")) inccheck = int(loop+inc) getcontext().prec = int(raw_input("Number of decimal places? "))+1 while loop < iterats: if loop == inccheck: print str("*Pi is " + str(pi) + " after " + str(loop) + " iterations.") inccheck += inc pi += 4 / odd odd += 2 loop += 1 if loop == inccheck: print str("*Pi is " + str(pi) + " after " + str(loop) + " iterations.") inccheck += inc pi -= 4 / odd odd += 2 loop += 1 print str("LIMIT REACHED! Pi is " + str(pi) + " after " + str(loop) + " iterations.")
import pandas as pd #any CSV file mlb = pd.read_csv(".csv") height = mlb['Height'].tolist() weight = mlb['Weight'].tolist() # Import numpy import numpy as np #Create a numpy array from the weight list with the correct units. # Multiply by 0.453592 to go from pounds to kilograms. # Store the resulting numpy array as np_weight_kg # Create array from height with correct units: np_height_m np_height_m = np.array(height) * 0.0254 # Create array from weight with correct units: np_weight_kg np_weight_kg = np.array(weight) * 0.453592 # Calculate the BMI: bmi bmi = np_weight_kg / np_height_m ** 2 # Print out bmi print(bmi)
numero=int(input("dime el numero del que quieres saber la tabla de multiplicar:")) i = 0 while i <= 10: print("{} X {} = {}".format(numero, i, numero*i)) i += 1 i = 5 while i <= 15: print("{} X {} = {}".format(numero, i, numero * i)) i += 1 i = 0 while i <= 10: if (numero*i) % 2 == 0: print("{} X {} = {}".format(numero, i, numero * i)) i += 1
numero_1 = int(input("dime el primer numero")) numero_2 = int(input("dime el segundo numero")) operacion = input("que quieres hacer Sumar, Restar , Multiplicar, Dividir?").capitalize() if operacion =="Sumar": print("{}".format(numero_1+numero_2)) elif operacion=="Restar": print("{}".format(numero_1 - numero_2)) elif operacion=="Multiplicar": print("{}".format(numero_1 * numero_2)) elif operacion=="Dividir": print("{}".format(numero_1 /numero_2))
# ######### ## Step 5 ## Create a List of TRex Running Postures ## Create a variable to record the index position ## Create a variable to define how many frames each running posture should be displayed ## When the Trex is at FLOOR level, animate to show run postures ## Change the Run Posture based on frames_per_image variable ## Add a sound when the Trex collides with the cactus ######### import random WIDTH = 600 HEIGHT = 600 FLOOR = 440 cactuses = ['cactus1','cactus2','cactus3','cactus4','cactus5'] random_cactus = random.choice(cactuses) trex = Actor('idle') trex.pos = (125,FLOOR) # Set the Position of the T-Rex cactus = Actor(random_cactus) cactus.pos = (544,FLOOR) # Set the Position of the Cactus speed = 3 # Sets the starting speed for the cactus to move to the left score = 0 # Set the starting score of the game JUMP_HEIGHT = (FLOOR - 100) FALL_SPEED = 4 # Running Postures of TRex trex_pose = ['run1','run2'] x = 0 # Number of Frames each image should be displayed frames_per_image = 30 def draw(): screen.clear() screen.fill((255,255,255)) screen.blit('floor-1',(5,456)) screen.draw.text(str(score),(430,5),fontsize=50,fontname='pixelmix_bold', color="black") # Display the Score on the Game Screen # use str() to display the score. # integers will not display on the game screen unless converted to string trex.draw() cactus.draw() def update(): global speed,score,x # Move the cactus to its left cactus.left -= speed # since the update function runs 60 times per second # we will increase the score by 1 for every 1 second score += 1/60 # display the score with just 2 decimal places score = round(score,2) # If the cactus disappears from the left of the screen # bring back a random cactus in original position if cactus.left < -10: cactus.pos = (544,FLOOR) cactus.image = random.choice(cactuses) # increases the speed each time a new cactus gets displayed speed += 0.1 # if the trex collides with the cactus, the score is reset to 0 if trex.colliderect(cactus): score = 0 sounds.point.play() # if trex jumps, it will have trex.y value less than FLOOR # it should then fall at the speed of FALL_SPEED variable if trex.y < FLOOR: trex.y += FALL_SPEED # the trex should not fall below FLOOR Level # when the trex reaches the floor level # maintain it at the same floor level elif trex.y == FLOOR: trex.y = FLOOR trex.image = trex_pose[x//frames_per_image] x += 1 if x//frames_per_image >= len (trex_pose): x = 0 def on_key_down(): if keyboard.SPACE: trex.y = JUMP_HEIGHT;
def plural_form (number, form0, form1, form2): if number % 10 == 1 or number == 1: print(number, form0) elif number % 10 >= 2 and number % 10 <= 4 or number >=2 and number <=4: print(number, form1) else: print(number, form2)
def getdate(): """Gives you current date and time""" import datetime return datetime.datetime.now() #MAIN FUNCTION def HMS(): """ This function is used for Health Management System for 3 People """ #LIST OF USERS user=["MANAN","HARSH","YASH"] #Diet data dd={1:"manandiet.txt",2:"pokardiet.txt",3:"yashdiet.txt"} #Exercise data ed={1:"mananexc.txt",2:"pokarexc.txt",3:"yashexc.txt"} while(1): try: print("WHAT DO YOU WANT TO DO?") print("PRESS 1 FOR LOGIN:") print("PRESS 2 FOR RETRIEVE:") #choice number 1 ch1=int(input()) if(ch1==0 or ch1>2): print("Enter 1 and 2 only") continue else: print("There you go.......") break except: print("Please Enter 1 or 2 only :-") #Code for login data if(ch1 == 1): while(1): try: print("\"\"You are logged in\"\"") print("Press 1 to Check Diet") print("Press 2 to check Exercise") #choice number 2 ch2 = int(input()) if(ch2>2 or ch2<=0): print("Please Enter 1 or 2 only :-") continue else: break except: print("Please Enter 1 or 2 only :-") if(ch2 == 1): count = 1 print("Whose diet you want to check") for i in user: print("PRESS", count, "for the user :-",i) count=count+1 #user input while (1): try: ui=int(input()) if (ui > len(user) or ui<=0): print("Input is incorrect") continue else: break except: print("Enter correct value") with open(dd[ui]) as f: print("[",getdate(),"]",end="") print(f.read()) print("thank you") while (1): try: print("Do you want to print again?") print("Press 1=Yes", "2=No") x = int(input()) if (int(x) == 0 or int(x) > 2): print("Enter 1 and 2 only") continue elif(int(x)==1): with open(dd[ui]) as f: print("[", getdate(), "]", end="") print(f.read()) else: break except: print("Please Enter 1 or 2 only :-") if(ch2 == 2): count = 1 print("Whose exercise you want to check") for i in user: print("PRESS", count, "for the user :-", i) count = count + 1 # user input while (1): try: ui = int(input()) if (ui > len(user) or ui <= 0): print("Input is incorrect") continue else: break except: print("Enter correct value") with open(ed[ui]) as f: print("[", getdate(), "]", end="") print(f.read()) print("thank you") while (1): try: print("Do you want to print again?") print("Press 1=Yes", "2=No") x = int(input()) if (int(x) == 0 or int(x) > 2): print("Enter 1 and 2 only") continue elif(int(x)==1): with open(ed[ui]) as f: print("[", getdate(), "]", end="") print(f.read()) else: break except: print("Please Enter 1 or 2 only :-") #Code to retrieve the data if(ch1 == 2): while (1): try: print("\"\"You are logged in\"\"") print("Press 1 to change Diet") print("Press 2 to change Exercise") # choice number 2 ch2 = int(input()) if (ch2 > 2 or ch2 <= 0): print("Please Enter 1 or 2 only :-") continue else: break except: print("Please Enter 1 or 2 only :-") if (ch2 == 1): count = 1 print("Whose diet you want to change") for i in user: print("PRESS", count, "for the user :-", i) count = count + 1 # user input while (1): try: ui = int(input()) if (ui > len(user) or ui <= 0): print("Input is incorrect") continue else: break except: print("Enter correct value") with open(dd[ui],'w') as f: f.write(input()) with open(dd[ui],'r') as f: print("new diet is") print("[", getdate(), "]", end="") print(f.read()) while (1): try: print("Do you want to edit again?") print("Press 1=Yes", "2=No") x = int(input()) if (int(x) == 0 or int(x) > 2): print("Enter 1 and 2 only") continue elif(int(x)==1): with open(dd[ui], 'w') as f: f.write(input()) with open(dd[ui], 'r') as f: print("new diet is") print("[", getdate(), "]", end="") print(f.read()) else: break except: print("Please Enter 1 or 2 only :-") if (ch2 == 2): count = 1 print("Whose exercise you want to change") for i in user: print("PRESS", count, "for the user :-", i) count = count + 1 # user input while (1): try: ui = int(input()) if (ui > len(user) or ui <= 0): print("Input is incorrect") continue else: break except: print("Enter correct value") with open(ed[ui],'w') as f: f.write(input()) with open(ed[ui],'r') as f: print("new exercise is") print("[", getdate(), "]", end="") print(f.read()) while (1): try: print("Do you want to edit again?") print("Press 1=Yes", "2=No") x = int(input()) if (int(x) == 0 or int(x) > 2): print("Enter 1 and 2 only") continue elif(int(x)==1): with open(ed[ui], 'w') as f: f.write(input()) with open(ed[ui], 'r') as f: print("new exercise is") print("[", getdate(), "]", end="") print(f.read()) else: break except: print("Please Enter 1 or 2 only :-") #for running again after one cycle while (1): try: print("Do you want to Run this Program again?") print("Press 1=Yes", "2=No") x = int(input()) if (x == 0 or x > 2): print("Enter 1 and 2 only") continue else: break except: print("Please Enter 1 or 2 only :-") if (x == 1): HMS() else: print("Good Bye") HMS()
try: i=int(input()) except Exception as e: print(e) else: print("every thing is good") finally: print("the entered number is")
class A(): var1="inside class a" def __init__(self): self.var1="inside a's function" class B(A): def __init__(self): self.var1="inside bs function" super().__init__() var1="inside class b" a=A() b=B() print(b.var1)
class First(): x=1 class Second(): x=2 class Third(Second,First): pass f=First() s=Second() t=Third() print(t.x)
import re pattern = r"Cookie" sequence = "Cookie" print(re.match(pattern, sequence)) # x=re.search(r'hi',"hello hi miami") # y=re.search(r'doba$','adoba adoba') # print(y) # # print("Lowercase w:", re.search(r'Co\wk\we', 'Cookie').group()) # # ## Matches any character except single letter, digit or underscore # print("Uppercase W:", re.search(r'C\Wke', 'C@ke').group()) # # ## Uppercase W won't match single letter, digit # print("Uppercase W won't match, and return:", re.search(r'Co\Wk\We', 'Cookie')) # print("Lowercase s:", re.search(r'Eat\scake', 'Eat cake').group()) # print("How many cookies do you want? ", re.search(r'\d+', '100 cookies').group()) # print("Uppercase S:", re.search(r'cook\Se', "cook'e").group()) # print("Lowercase w:", re.search(r'Cook\We', 'Cook"e').group()) """ \t - Lowercase t. Matches tab. \n - Lowercase n. Matches newline. \r - Lowercase r. Matches return. \A - Uppercase a. Matches only at the start of the string. Works across multiple lines as well. \Z - Uppercase z. Matches only at the end of the string. TIP: ^ and \A are effectively the same, and so are $ and \Z. Except when dealing with MULTILINE mode. Learn more about it in the flags section. """ # \b - Lowercase b. Matches only the beginning or end of the word. # # # Example for \t # print("\\t (TAB) example: ", re.search(r'Eat\tcake', 'Eat cake').group()) # # # Example for \b # print("\\b match gives: ",re.search(r'\b[A-E]ookie', 'Cookie').group()) # * - Checks if the preceding character appears zero or more times starting from that position. # # # Checks for any occurrence of a or o or both in the given sequence # re.search(r'Ca*o*kie', 'Cookie').group() # 'Cookie' # ? - Checks if the preceding character appears exactly zero or one time starting from that position. # # # Checks for exactly zero or one occurrence of a or o or both in the given sequence # re.search(r'Colou?r', 'Color').group() # 'Color' # # {x} - Repeat exactly x number of times. # {x,} - Repeat at least x times or more. # {x, y} - Repeat at least x times but no more than y times. # # re.search(r'\d{9,10}', '0987654321').group() # x=re.search(r'1+$', '00000098765432111111').group() # print(x) # iiiiiiiiiiiimmmmmmmmmmmmpppppppppppp statement = 'Please contact us at: [email protected]' match = re.search(r'([\w\.]+)@([\w\.]+)', statement) if statement: print("Email address:", match.group()) # The whole matched text print("Username:", match.group(1)) # The username (group 1) print("Host:", match.group(2)) # The host (group 2)
class Employee: name3="employee" def myprint(self): print( f"{self.name} {self.city} {self.birth} {self.rank}\n") def __init__(self,name,rank,birth,city): self.name=name self.rank=rank self.birth=birth self.city=city @classmethod def sum(cls,n): cls.name=n @classmethod def change_args(cls,str): return cls(*str.split("=")) @staticmethod def summer(x,y): return x+y class Prog(Employee): name2="fwefwfwef" def __init__(self,name,rank,birth,city): self.name=name self.rank=rank self.birth=birth self.city=city w=Prog(1,2,3,4) e=Employee(1,2,3,4) print(e.name2)
INF = float('inf') def minPathCost(graph,V): minCost = graph.copy() #[ [0 for x in range(V)] for x in range(V) ] for k in range(V): for i in range(V): for j in range(V): minCost[i][j] = min( minCost[i][j], minCost[i][k]+minCost[k][j] ) for l in range(V): for m in range(V): if( minCost[l][m] == INF): print("INF\t\t",end="") else: print(minCost[l][m],end="\t\t") print() print("\n\n\n\n") for i in range(V): for j in range(V): if( minCost[i][j] == INF): print("INF\t\t",end="") else: print(minCost[i][j],end="\t\t") print() graph = [ [0, 5, INF, 10], [INF, 0, 3, INF], [INF, INF, 0, 1], [INF, INF, INF, 0] ] minPathCost(graph,len(graph))
# 请在下面填入定义Book类的代码 # ********** Begin *********# class Book: # ********** End *********# # '书籍类' def __init__(self, name, author, data, version): self.name = name self.author = author self.data = data self.version = version def sell(self, bookName, price): print("%s的销售价格为%d" % (bookName, price))
#coding=utf-8 # 导入math模块 import math # 输入两个整数a和b a = int(input()) b = int(input()) # 请在此添加代码,要求判断是否存在两个整数,它们的和为a,积为b #********** Begin *********# for i in range(1,a): if b==i*(a-i): print('Yes') break else: print('No') #********** End **********#
class WrapClass(object): def __init__(self, obj): self.__obj = obj def get(self): return self.__obj def __repr__(self): return 'self.__obj' def __str__(self): return str(self.__obj) # 请在下面填入重写__getattr__()实现授权的代码 # ********** Begin *********# def __getattr__(self, item): return getattr(self.__obj, item) # ********** End **********# thelist = [] inputlist = input() for i in inputlist.split(','): result = i thelist.append(result) # 请在下面填入实例化类,并通过对象调用thelist,并输出thelist第三个元素的代码 #********** Begin *********# print(WrapClass(thelist).get()[2]) #********** End **********#
class Point: def __init__(self, x, y, z, h): self.x = x self.y = y self.z = z self.h = h def getPoint(self): return self.x, self.y, self.z, self.h class Line(Point): # 请在下面填入覆盖父类getPoint()方法的代码,并在这个方法中分别得出x - y与z - h结果的绝对值 # ********** Begin *********# def getPoint(self): length_one = abs(self.x - self.y) length_two = abs(self.z - self.h) # ********** End **********# print(length_one, length_two)
# coding=utf-8 # 创建并初始化menu_dict字典 menu_dict = {} while True: try: food = input() price = int(input()) menu_dict[food]= price except: break #请在此添加代码,实现对menu_dict的遍历操作并打印输出键与值 ###### Begin ###### print('\n'.join([ str(x) for x in menu_dict.keys()])) print('\n'.join([str(x) for x in menu_dict.values()])) ####### End #######
#coding=utf-8 # 输入两个正整数a,b a = int(input()) b = int(input()) # 请在此添加代码,求两个正整数的最大公约数 #********** Begin *********# def gcd(m,n): if not m:return n elif not n:return m elif m is n :return m if m>n: d=n else:d=m while m%d or n%d:d-=1 return d #********** End **********# # 调用函数,并输出最大公约数 print(gcd(a,b))
#!/usr/bin/python3 import sys def throws(): raise RuntimeError('this is the error message') def main(): try: throws() return 0 # Unterschied Python3 Pyhton2.7 # except Exception, err: except RuntimeError as err: sys.stderr.write('ERROR: %s\n' % str(err)) return 1 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/python import os import time import datetime # 1. the year as a four-digit number, e.g. 2007 # 2. the month (1, 2, , 12) # 3. the day of the month (1, 2, , 31) # 4. hour (0, 1, , 23) # 5. minutes (0, 1, , 59) # 6. seconds (0, 1, , 61 where 60 and 61 are used for leap seconds) # 7. week day (0=Monday, 1=Tuesday, , 6=Sunday) # 8. day of the year (1, 2, , 366) # 9. daylight saving time information (0, 1, or -1) while True: locTime = time.localtime() os.system('clear') lineHolder = str(locTime[3]) + '| ' for i in range(locTime[3]): lineHolder += '#' print lineHolder lineHolder = str(locTime[4]) + '| ' for i in range(locTime[4]): lineHolder += '#' print lineHolder lineHolder = str(locTime[5]) + '| ' for i in range(locTime[5]): lineHolder += '#' print lineHolder time.sleep(1)
from dataclasses import dataclass from collections import defaultdict, Counter from typing import Dict, List, Counter, Union from pathlib import Path # https://docs.python.org/3/library/dataclasses.html word_list = Path(r"wordle-small.txt").read_text().split() Green, Yellow, Miss = "GY." Word = str Score = int Reply = str Partition = Dict[Reply, List[str]] @dataclass class Node: guess: Word size: int branches: Dict[Reply, 'Tree'] Tree = Union[Node, Word] def reply_for(guess: Word, target: Word) -> Reply: "The five-character reply for this guess on this target." # We'll start by having each element of the reply be either Green or Miss ... reply = [Green if guess[i] == target[i] else Miss for i in range(5)] # ... then we'll change the elements that should be yellow counts = Counter(target[i] for i in range(5) if guess[i] != target[i]) for i in range(5): if reply[i] == Miss and counts[guess[i]] > 0: counts[guess[i]] -= 1 reply[i] = Yellow return ''.join(reply) def partition(guess, targets) -> Partition: branches = defaultdict(list) for target in targets: branches[reply_for(guess, target)].append(target) return branches def partition_counts(guess, targets) -> List[int]: "The sizes of the branches of a partition of targets by guess." counter = Counter(reply_for(guess, target) for target in targets) return sorted(counter.values()) reply_for("AROSE", "SKIRT") few = word_list[::10] #every 100 elements partition("AROSE", few) partition_counts("ROAST", few) def round(guess, actual, targets): partitions = partition(guess, targets) counts = partition_counts(guess, targets) print(guess, "Largest group:", max(counts), "Number of groups:", len(counts)) reply = reply_for(guess, actual) remaining_words = partitions[reply] print("Remaining words", remaining_words) return partitions, remaining_words # January 2nd 23 #round 1 partitions_r1, words_r1 = round('AROSE', 'SKIRT', word_list) #round 2 partitions_r2, words_r2 = round('SHIRT', 'SKIRT', words_r1) # maximise the number of groups and minimise the largest group results = [] for target in few: counts = partition_counts(target, few) results.append((target, max(counts), len(counts))) print(target, max(counts), len(counts)) guess = min(few, key=lambda guess: max(partition_counts(guess, few))) print("Guess", guess) results.sort(key=lambda y: y[1]) def minimizing_tree(metric, targets) -> Tree: """Make a tree that picks guesses that minimize metric(partition_counts(guess, targets)).""" if len(targets) == 1: return targets[0] else: guess = min(targets, key=lambda guess: metric(partition_counts(guess, targets))) branches = partition(guess, targets) return Node(guess, len(targets), {reply: minimizing_tree(metric, branches[reply]) for reply in branches}) test_tree = minimizing_tree(max, few)
#python version 3.9.5 #IP Address Defang userInput = input("Enter IP address to be defanged: ") defangedIP = [] for x in userInput: if x == '.': defangedIP.append("[.]") else: defangedIP.append(x) removeList =' '.join([str(i) for i in defangedIP]) print (removeList)
import numpy as np def random2D(row = 1, col = 0, logical = True): """ A simple generator for random 2d matrix Attributes __________ row :: int number of rows, default = 1 col :: int number of cols, default = 0 Logical :: bool type of the output matrix, if True a binary matrix, default = True Values ______ A row*col matrix Default output, single rv between (0,1) """ if row == 0 or col == 0: dim = max(row,col) result = np.random.random(dim) else: result = np.random.random((row,col)) if logical == True: result[result>0.5] = 1 result[result<=0.5] = 0 return(result)
import re def open_and_edit(): f = open("verbs.txt", 'r', encoding = "utf-8") s = f.read() f.close() s1 = s.lower() a = s1.split() for i, word in enumerate(a): a[i] = word.strip('.,!?();:*/\|<>-_%&#№@+~—"') return a def find_and_print(a): arr = [] for word in a: if re.search('^программир((у(ю(т|щ(и(й|ми?|е|х)|е(го|му?|й)|ая|ую))?|я|е(шь|те?))|ова(л(а|и)?|ть))(с(я|ь))?|уем(ы(й|ми?|е|х)?|о(го|му?|й)|ая?|ую))', word): if word not in arr: arr.append(word) for verb in arr: print(verb) def main(): text = open_and_edit() find_and_print(text) main()
import re def open_and_edit(): f = open("linguistics.txt", 'r', encoding = "utf-8") s = f.read() f.close() return s def replace_and_output(s): s1 = re.sub('язык([а-я]{,3}( |\.|,|\)))','шашлык\\1', s) s2 = re.sub('Язык([а-я]{,3}( |\.|,|\)))','Шашлык\\1', s1) f = open("shashlyk.txt", 'w', encoding = "utf-8") f.write(s2) print('Текст записан в файл shashlyk.txt') f.close() def main(): text = open_and_edit() replace_and_output(text) main()
# while 1: # i = input("请输入:") # print(type(eval(i))) # if i == "quit": # break # else: # print('结束') # def test(*para): # print('有 %d 个参数' % len(para)) # return para # # a = [1,2,3,4] # # print(test(*a)) # print('-----') # print(test(1,2,3,45,8)) # class student: # def __init__(self,name,age,sex): # self.name = name # self.age = age # self.sex = sex # self.study() # #私有类属性 # self.__do_thing() # def study(self): # print(self.age) # self.sleep() # def sleep(self): # print("%s正在睡觉" % self.name) # #self.__do_thing() # def __do_thing(self): # """ # 私有方法 # """ # print('私有方法') # def aaa(self): # print('无self调用') # def __del__(self): # pass # @staticmethod # def eat(): # print('静态') #使用@staticmethod类名调用静态方法student.eat() #对象调用静态方法 # student('zkl',22,'feamle').eat() #s = student('zhf',22,'m') #s.eat() """ 以追加的方式打开文件,每写入一行就读取一行并打印出来 """ import os from datetime import datetime # import time # # while True: # time.sleep(2) # f = open('/Users/karey/test/test.txt', 'a+') # #写数据之前的位置 # pos = f.tell() # print(pos) # f.write('\nthis time :' + datetime.now().strftime('%H:%M:%S') + '\n') # #写数据之后的位置 # new_pos =f.tell() # #移动到之前的位置 # f.seek(pos,0) # #读取数据 # line = f.read() # print(line) # #读完后,移动到写数据之后的位置 # f.seek(new_pos) # #print('pos: %d, new_pos: %d\n'% (pos, new_pos)) # #定义变量x,连续赋值3次并打印 # n = 1 # while n < 4: # x = input("请输入x的值:") # print(x) # n = n +1 #创建字典,访问字典 # a = {}.fromkeys(['a', 'b', 'c']) # b = {'a':1, 'b':2,'c':3 } # print(a,b) # print(a['a']) #计算200以内质数 #什么是质数,除以1和自身以外,没有可以被整除因子 #如何判断整除:n % i == 0,表明可以整除。或判断n / i 是否与 n // i 相等 #如何来整除1到自身的所有数?循环1到自身,并逐个尝试。200以内就从1到200循环,对每一个数字即可 l = [] loop = 0 for n in range(1,200): for i in range(2,int(n/2)+1): loop += 1 if n % i == 0: break else: l.append(n) print(l) print(len(l)) print("本次循环次数是:%d " % loop) #69进制转换,图片是二进制文件 #70函数:可复用可模块化 #对输入的字符串进行判断,确认其是否可以转换为一个有效的数字 def check_number(string): negative = 0 point = 0 is_valid = True for c in string: code = ord(c) if (code < 48 and code != 46) or code >57: is_valid =False break elif code ==45:negative += 1 elif code ==46:point += 1 if negative > 1: is_valid = False if point > 1: is_valid = False if negative == 1 and string[0] != '-': is_valid = False return is_valid
class Shape(): def __init__(self, height, length): self.height = height self.length = length def get_area(self): raise NotImplementedError() class Triangle(Shape): def get_area(self): area = (self.height * self.length)/2 return area class Rectangle(Shape): def get_area(self): area = self.height * self.length return area t = Triangle(3, 4) print(t.get_area()) r = Rectangle(3, 4) print(r.get_area())
def swap(f): def wrapper(*args, **kwargs): args = reversed(args) f(*args, **kwargs) return wrapper def div(x, y, show=False): res = x / y if show: print(res) return res div(2, 4, show = True) swapped = swap(div) swapped(2, 4, show = True) ''' или так @swap def div(x, y, show=False): res = x / y if show: print(res) return res div(2, 4, show=True) '''
# allows specifying explicit variable types from typing import Any, Dict, Optional, Text def find_duplicates(_list): """Find duplicate items in a list""" return set([x for x in _list if _list.count(x) > 1]) def dict2list(dictionary): if type(dictionary) == list: return dictionary elif type(dictionary) == dict: return [dictionary] def str2list(_str): if type(_str) == str: return [_str] elif type(_str) == list: return _str def unlist(_list): if len(_list) == 1: return _list[0] else: return _list
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module contains logic to get a link from wikipedia. Created on Mon Jan 25 20:47:33 2021 @author: macuser """ import wikipedia import requests def check_wiki(phrase): #takes an str and returns a str ''' Search in wiki for a keyphrase and return a correspondent link. If there is an url, add to the result as well as disambiguation page. If there is no page with the correspondent name, return a string with information about it. ''' try: page = wikipedia.page(phrase, auto_suggest=False) #if auto_suggest is True, it returns wrong result disambiguation_page = page.url + '_(disambiguation)' if requests.get(url=disambiguation_page).status_code == 404: result = page.url else: result = f'{page.url}.\n Також: {disambiguation_page}' except wikipedia.DisambiguationError: result = 'https://en.wikipedia.org/wiki/' + phrase + '_(disambiguation)' except wikipedia.PageError: result = 'На жаль, сторінки з таким іменем не існує.' return result
########### # EDIT DISTANCE ########### import numpy as np def edit_dist(str1, str2): m = len(str1) n = len(str2) if m == 0: return n if n == 0: return m a1 = np.zeros((m + 1, n + 1)) #create empty array # a1 = np.zeros([0 for x in range(n + 1)] for x in range(m + 1)) for i in range(m + 1): #vertical indexing through str1 for j in range(n + 1): #horizontal indexing through str2 if i == 0: #first row a1[i][j] = j# fill in with length of str2 elif j == 0: #first column a1[i][j] = i #fill in with length of str1 # these previous two operations represent # of ops. # creating the string from empty character elif str1[i-1] == str2[j-1]: a1[i][j] = a1[i-1][j-1] # if the two characters on index are equal, then # ignore and use moves of prev. character (diag) elif str1[i-1] != str2[j-1]: a1[i][j] = 1 + min( a1[i-1][j], #left = delete char a1[i-1][j-1], #diag = replace char a1[i][j-1] #up = insert a char ) # +1 to perform insert/replace/del return a1, a1[m][n] #returns the final spot in array str1 = str(input("String 1: ")) str2 = str(input("String 2: ")) print( edit_dist(str1, str2)) # print(f"Editing {str1} to {str2} would take {operations} operations.")
p1 = (input("Player 1, please input your play: ")) p2 = (input("Player 2, please input your play: ")) if p1.lower() == 'rock': if p2.lower() == 'scissors': print("Player 1 wins") elif p2.lower() == 'paper': print("Player 2 wins") elif p2.lower() == 'rock': print("Tie!") else: print('enter valid input') elif p1.lower() == 'scissors': if p2.lower() == 'scissors': print('Tie! Play again') elif p2.lower() == 'paper': print('Player 1 wins') elif p2.lower() == 'rock': print('Player 2 wins') else: print("enter valid input") elif p1.lower == 'paper': if p2.lower() == 'scissors': print("Player 2 wins") elif p2.lower() == 'rock': print("Player 1 wins") elif p2.lower() == 'paper': print('Tie! Play again') elif p2.lower() != 'paper' or 'rock' or 'scissors': print("enter valid input") else: print("enter valid input")
import math lower_bound = int(input("Enter a lower bound: ")) upper_bound = int(input("Enter an upper bound: ")) prime_numbers = [2, 3] i = lower_bound if(lower_bound<1): print("Your number is invalid. Please try again.") elif(1<=lower_bound<3): print(f"{n}st Prime number is : {prime_numbers[n-1]}") elif (lower_bound>2): prime_numbers = [] cont = True while (cont == True): i += 1 status = True #for j in range(2, int(math.sqrt(i) + 1)): #sqrt makes answer inaccurate #adi note - instead of setting sqrti, make it x * x < i for j in range(2, int(i/2 + 1)): if (i % j == 0): status = False break if (status == True): #if the number passes the above test, it is prime. we add the number to our prime numbers list prime_numbers.append(i) if i == upper_bound: cont = False print(prime_numbers)
# D. R. Y. "Don't repeat yourself." # Once your code repeats itself several times, try to find a way to condense things. # W.E.T. "Write everything twice" is what you don't want to do # Function goes at the top of the program. # def is defining a function, meaning you can use it # When you run with just the three lines below, nothing happens def greeting(): name = raw_input("What is your name? ") print "Hello, " + name # Adding this line makes it work. If you leave a string in, error # Because the error message says no function is given. #greeting() # need to pass argment for name # The function definition, and where you call the function # end up mirroring each other def hello(name): print "Hello, " + name # New definition for adding def add(a, b): # return sends arguments to add, "send in on back" return a + b hello("Sonya") print add(2, 3) + add(4, 5)
def sumTo(n): return (1+n)*n/2 def productTo2(n): ans = 1 for i in range(1, n): ans = ans * i return ans def func(): x = 1 for _ in range (1,15): x = x*2 return x
"""O modelo representea uma interação entre shops que vendem fun e agentes que compram fun. Agentes e shops tem uma Accont, onde os recursos para compra e venda de fun são depositados""" # Construção dos agentes do modelo import random # Cada Account tem um saldo (balance) que inicia com zero # Cada Account tem métodos específicos para depositar e sacar recursos e outro para fazer pagamentos class Account: def __init__(self, i): self.registration = i self.balance = 0 def deposito(self, valor): self.balance += valor def saque(self, valor): if self.balance < valor: return False else: self.balance -= valor return True def pagamento(self, valor): self.balance -= valor return True # Cada shop tem uma account, uma capacidade (quant de agentes que podem ser atendidos), # um estoque de fun e um cost (preço de venda) # tem também um método para realizar a venda de fun class Shop: def __init__(self, s): self.identity = s self.account = Account(s) self.capacity = random.randrange(1, 15) self.fun = random.randrange(1, 15) self.cost = random.randrange(2, 20) def venda(self, valor): if self.capacity > 0: self.capacity -= 1 if self.fun >= valor: self.fun -= valor return valor else: return False else: return False # Cada Agente tem uma conta e um estoque de fun que inicia com zero # Os agentes têm métodos para conferir se tem saldo suficiente para comprar fun (checa_grana) e para receber a fun adquirida (get_fun) class Agent: def __init__(self, a): self.id = a self.account = Account(a) self.fun = 0 def checa_grana(self, valor): if self.account.balance > valor: return True else: return False def get_fun(self, valor): self.fun += valor if __name__ == '__main__': print(type(Account)) print(type(Shop)) print(type(Agent)) joao = Agent(1) mesbla = Shop(1) print(joao) print(mesbla) joao.account.deposito(500) joao.account.saque(200) print(joao.account.balance) print(mesbla.capacity, mesbla.fun, mesbla.cost) print(mesbla.capacity)
'''Questão 8. Dicionários. Dado o dicionário: d = {‘a’: 0}: faça programas que 8.1 acrescente um par (chave, valor) {‘b’: 1}, ao dicionário; 8.2 verifique se a key ‘c’ está presente? 8.3 Concatene um dicionário a um outro dicionário: e = {z : 23}. Use o método ‘update’!''' d = {'a': 0} d['b'] = 1 # para testar se o programa identifica uma chave c incluída no dicionário basta tirar o # da linha abaixo #d['c'] = 4 print(d) if 'c' in d: print('O dicionario d possui a chave c') else: print('O dicionario d não possui a chave c') e = {'z': 23} d.update(e) print(d)
# I declare that my work contains no examples of misconduct, such as plagiarism, or collusion. # Any code taken from other sources is referenced within my code solution. # Student ID: ……w1810194………………..… # Date: ………2020-12-05…………..… #decalring variables to functions as counters for each progress method prog = 0 trail = 0 ret = 0 exc = 0 total = 0 data_list = [[120,0,0],[100,20,0],[100,0,20],[80,20,20],[60,40,20],[40,40,40],[20,40,60], [20,20,80],[20,0,100],[0,0,120]] #define function to determine progression outcome def progress(pas,defer,fail): #declaring the previously created variables as global variables, #to be used inside the function global prog global trail global ret global exc global total #create a while true loop to break after printing the respective progression outcome, #incrementing the respective counter, and incrementing the total value after each cycle while True: if(pas + defer + fail) != 120: print("Total incorrect") #break the loop if the total is incorrect break #if pass value is lesser than or equal to 80 and fail value is lesser than or equal to 60, #print("Do not progress - module trailer") elif (pas <= 80 and fail <=60): print("Do not Progress - module retriever") ret += 1 #if fail value is greater than or equal to 80, print 'exclude' elif (fail >= 80): print("Exclude") exc += 1 #if pass value is equal to 120, print 'progress' elif (pas == 120): print("Progress") prog += 1 #if pass value is equal to 100 and both defer and fail values equal to 20, #print 'progress(module trailer)' elif (pas == 100 and (defer == 20 or fail == 20)): print("Progress(module trailer)") trail += 1 total += 1 break #iterate through each element in the previously defined data list for i in data_list: #iterate through each element inside each sublist val1 = i[0] val2 = i[1] val3 = i[2] #parse each element to the 'progress' function as arguments progress(val1,val2,val3) #print the horizontal histogram print("\nProgress",prog,":",(prog*'*')) print("Trailing",trail,":",(trail*'*')) print("Retriever",ret,":",(ret*'*')) print("Excluded",exc,":",(exc*'*')) print("\n",total,"outcomes in total")
#!/usr/bin/python #[HL-2010-08-27 06:07] # Testing generator function.. doesn't seem to work so well # http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for import time # Function version def fibonA(n): a = b = 1 result = [] for i in xrange(n): time.sleep(1) result.append(a) a, b = b, a + b return result # Generator version def fibonB(n): a = b = 1 for i in xrange(n): time.sleep(1) yield a a, b = b, a + b if __name__ == "__main__": print "fibonA" for x in fibonA(5): print x, print "\nfibonB" for x in fibonB(5): print x,
#!/usr/bin/env python3 # coding: utf-8 n1 = 10 str1 = 'You\'re beautiful girl. ' print(n1) print(str1)
#!/usr/bin/python3 # coding: utf-8 import time localtime = time.asctime(time.localtime(time.time())) print('本地时间为:',localtime)
class FileValidationError(Exception): def __init__(self, *args): if args: self.message = f"An error happened while the compilation and the validation of the {args[0]} file." else: self.message = None def __str__(self): if self.message: return self.message else: return "An error has occured while the validation of the file is being made." class WrongFileExtensionError(Exception): def __init__(self, *args): if args: self.message = f"The filetype {args[0]} is not appropriate for the operation." else: self.message = None def __str__(self): if self.message: return self.message else: return "An error happened because the filetype is not appropriate ." class WrongKeywordError(Exception): def __init__(self, *args): if args: self.message = f"The keyword {args[0]} is not appropriate for the operation." else: self.message = None def __str__(self): if self.message: return self.message else: return "An error happened because the keyword is not appropriate ."
#!/usr/bin/env python from enum import Enum from textwrap import dedent from collections import defaultdict class Tile(Enum): WALL = '#' PASSAGE = '.' KEY = '🔑' DOOR = '🚪' def neighbors(loc): yield (loc[0], loc[1] - 1) yield (loc[0], loc[1] + 1) yield (loc[0] + 1, loc[1]) yield (loc[0] - 1, loc[1]) class Security: def __init__(self, letter=None, key_loc=None, door_loc=None): self.letter = letter self.key_loc = key_loc self.door_loc = door_loc class Map: def __init__(self, position, tiles, security, size): self.position = position self.tiles = tiles self.security = security self.size = size def __repr__(self): out = '' for y in range(self.size[1]): for x in range(self.size[0]): if (x,y) == self.position: out += '@' elif self.tiles[(x,y)] in (Tile.WALL, Tile.PASSAGE): out += self.tiles[(x,y)].value elif self.tiles[(x,y)] is Tile.KEY: out += self.security[(x,y)].letter.lower() elif self.tiles[(x,y)] is Tile.DOOR: out += self.security[(x,y)].letter.upper() out += '\n' return out[:-1] def build_graph(self): edges = defaultdict(lambda: []) Q = [self.position] seen = set(self.position) while len(Q) > 0: loc = Q.pop(0) for n in neighbors(loc): if self.tiles(n) is Tile.WALL: continue @classmethod def read_input(cls, lines): """ >>> inp = r''' ... ######### ... #[email protected]# ... ######### ... ''' >>> Map.read_input(dedent(inp).strip().split('\\n')) ######### #[email protected]# ######### """ position = None tiles = {} security = defaultdict(lambda: Security()) for y, line in enumerate(lines): for x, char in enumerate(line): if char == Tile.WALL.value: tiles[(x,y)] = Tile.WALL elif char == Tile.PASSAGE.value: tiles[(x,y)] = Tile.PASSAGE elif char == '@': position = (x,y) tiles[(x,y)] = Tile.PASSAGE elif char.islower(): tiles[(x,y)] = Tile.KEY security[(x,y)].letter = char.lower() security[(x,y)].key_loc = (x,y) elif char.isupper(): tiles[(x,y)] = Tile.DOOR security[(x,y)].letter = char.lower() security[(x,y)].door_loc = (x,y) else: raise Exception(f'Unknown character: {char}') return Map(position, tiles, security, (x+1, y+1)) if __name__ == "__main__": import sys lines = sys.stdin.readlines() program = Map.read_input(l.strip() for l in lines) print(program)
### INPUT OUTPUT FILE ### MEMBUAT FILE DENGAN MENGGUNAKAN PYTHON """ ATURAN/MODE DALAM MANIPULASI FILE DENGAN PYTHON 1) w = WRITE MODE/CREATE FILE : akan menulis dengan menimpa isi dari file lama/membuat file baru jika file belum ada 2) r = READ ONLY MODE : hanya membaca isi dari file 3) a = APPEDNDING MODE :menambahkan data di akhir baris 4) r+ = READ + WRITE MODE """ ### CONTOH PENGGUNAAN UNTUK FILE DENGAN NAMA "data.txt" ### Fungsi "w" file = open("data.txt","w") # pembuatan variabel dengan nama "file" khusus aktivitas "w" file.write("ini adalah file txt yang dibuat dengan Python") file.write("\nini baris kedua") file.write("\nini baris ketiga") file.write("\nini baris keempat") file.close() #wajib close file.. setelah di Run maka akan muncul file txt dalam folder ################################################ ################################################ ### Funfsi "r" bacaFile = open("data.txt", "r") ### cara baca file baca = bacaFile.read() # pembacaan isi file, jika dalam () diisi angka maka jumlah karakter sesuai angka tersebut yang akan ditampilkan print(baca) print(25 * "-") bacaFile.close() ################################################ ################################################ ### Fungsi "a" cobaAppend = open("data.txt","a") cobaAppend.write("\nbaris ini ditambahkan dengan mode append") cobaAppend.close()
text1 = "Data String!" print(text1) text2 = "ini hari jum'at" print(text2) ### untuk tanda petik 1 maupun 2 dalam string bisa diberikan tanda back-slash (\) text3 = "Kancil berkata \"Kemana broh?\"" print(text3) ### untuk menciptakan baris baru maka dapat digunakan \n text4 = "Hari ini ngantuk aja \nenaknya ngantuk" print(text4) ### baris baru bisa dilakukan didalam string yang berada dalam petik3 (""") text5 = """telo dicolong tuyul""" print(text5) ### untuk menuliskan tanda back-slash bisa menggunakan raw string (r) text6 = r"C:\New Disc" print(text6) ### perkalian string text7 = "wk" text8 = text7 * 5 ### penggabungan 2/lebih string dengan tanda pemisah koma(,) print("Sendal", "Jepit") ### penggabungan 2/lebih string yang telah ditugaskan dengan tanda pemisah plus(+) print(text8 + " " + text6)
import time import os import sys import random def f_dynamic_path_to_initial_list(file_name): """This function allow us to open file with the list of cities without regard to location folder """ dir_path = os.path.dirname(__file__) list_file = dir_path+'/'+file_name return list_file def f_get_word_list(): file = open(f_dynamic_path_to_initial_list("countries-and-capitals.txt"), 'r') word_list = file.readlines() splitted_word_list = [] for line in word_list: splitted_word_list.append(line.split('|')) file.close return splitted_word_list def f_random_word(): splitted_word_list = f_get_word_list() word = (splitted_word_list[random.randint(1, len(splitted_word_list))][1].upper()) return word def f_mask_word(word): masked_rand_word = [ '_' for i in range(len(list(word)))] return masked_rand_word def f_start_game(): global again global complete global decission global lives global word global board global used_letters again = 1 complete = 0 decission = 0 lives = 6 start = input("\nPress '1' to start the game: ") while True: if start == '1': word = str.strip(f_random_word()) board = f_mask_word(word) #this resetts board - not really by PP used_letters = [] #this resetts used letters - not really by PP print(word) print('\nThe word to guess is: ' ,board) # print('Used letters: ', used_letters) # print('Remaining lives: ' , lives) break else: start = input("To start, press 1: ") def f_choice_word_or_letter(): decission = input("\nDecide what to guess: (W)ord or (L)etter ").upper() while decission not in {"W", "L"}: decission = input("You can only press W or L. ").upper() return decission def f_guess_letter(word): global lives global board global complete global sleep # global used_letters print('\nThe word to guess: ' ,board) print('Remaining lives: ' , lives) print('Used letters: ', used_letters) guessed_letter = input("Please type desired letter ").upper() used_letters.append(guessed_letter) index = 0 success = 0 for i in list(word): if i == guessed_letter: board[index] = guessed_letter success += 1 index += 1 print("\nThat's a correct guess!") if success == 0: print("\nWrong guess, you lost 1 live") lives -= 1 print('Remaining lives: ' , lives, '\n') if list(word) == board: print("n/Yay! You won't be hanged today! ") complete = 1 print('The word to guess: ' ,board) if lives == 0: f_final_countdown() print('The secret word was: ', word) def f_guess_word(word): global lives global complete guessed_word = input("\nPlease provide the word: ").upper() if word == guessed_word: print("Success!") complete = 1 else: lives -= 2 print("Wrong guess, you lost 2 lives.") if lives <= 0: f_final_countdown() print('The secret word was: ', word) def f_final_countdown(): print("3..") time.sleep(0.5) print('2..') time.sleep(0.5) print('1...') time.sleep(0.5) print('YOU ARE DEAD') def f_repeat(): if lives <= 0 or complete == 1: rep = input('Wanna play again? If YES - press Y, if NO press any other key! ').upper() if rep == "Y": return 1 else: return 0 def f_main(): global word global lives global complete global board #needed to be set here otherwise if game was repeated f_guess word was giving board with guessed earlier signs, should be again covered global used_letters #same reason as with board line above again = 1 # board = f_mask_word(word) while again == 1: f_start_game() # system('clear') while (complete == 0) and (lives > 0): print('Remaining lives: ' , lives) dec = f_choice_word_or_letter() # print(dec) if dec == 'W': f_guess_word(word) again = f_repeat() else: f_guess_letter(word) again = f_repeat() #word = '' word = '' lives = 6 used_letters = [] complete = 0 decission = 0 board = [] f_main()
#!/usr/local/bin/python3 # NAME: Victor Mora # FILE: week8_exercises.py # DESC: Week 8 Exercises # DATE: October 8, 2016 import math # Write a function named reverser() that reverses lists # and strings. When the function is passed a string, # it returns a string. When the function is passed a list, # it returns a list. def reverser(thing): lst = [x for x in thing] lst.reverse() reversed = ''.join(lst) if isinstance(thing, str) else lst return reversed print("-"*50) print("Reverser:") print("-"*50+"\n") print("Reversed String: "+reverser('Fred')) print("Reversed List: ",) print(reverser(['Fred', 'Flinstone', 31, True])) print("\n") # Write a function that returns the volume of cubes or # spheres. By default the function will assume that # you’re calculating the volume of a sphere. The function # will look like this: def get_volume(dimension, kind='sphere'): if kind == 'sphere': volume = (4/3)*math.pi*(dimension**3) else: volume = dimension**3 return volume print("-"*50) print("Get Volume:") print("-"*50+"\n") print("Sphere Volume w/ Radius of 2: "+str(get_volume(2))) print("Cube Volume w/ Side of 2: "+str(get_volume(2, kind='cube'))+"\n") # Write a function that prints the keys and values of a # hash of sorted by key. Print the data in neat columns # using the String format() function. Your function should # handle a hash with any number of keys. def pretty_print_hash(**kwargs): for i in sorted(list((kwargs.keys()))): print("{0:>12}: {1}".format(i, kwargs[i])) print("-"*50) print("Pretty Print Hash:") print("-"*50+"\n") kwargs = {'first_name':'Fred', 'last_name':'Flinstone', 'age':31} pretty_print_hash(**kwargs) print("\n") # Write a function that uses a lambda function sort to sort a # list of employees by their salary. This function will take a # list of data as an argument and will employ the sorted function. # Use the sorted key option with a lambda function that sorts # the data by the last element of the list (salary). The list # of employees is given below. Your function should ignore the # first line. Print only the last name, first name and salary. # See the example output below employee_data = ["FName LName Tel Address City State Zip Birthdate Salary", "Arthur:Putie:923-835-8745:23 Wimp Lane:Kensington:DL:38758:8/31/1969:126000", "Barbara:Kertz:385-573-8326:832 Ponce Drive:Gary:IN:83756:12/1/1946:268500", "Betty:Boop:245-836-8357:635 Cutesy Lane:Hollywood:CA:91464:6/23/1923:14500", "Ephram:Hardy:293-259-5395:235 Carlton Lane:Joliet:IL:73858:8/12/1920:56700", "Fred:Fardbarkle:674-843-1385:20 Parak Lane:DeLuth:MN:23850:4/12/23:780900", "Igor:Chevsky:385-375-8395:3567 Populus Place:Caldwell:NJ:23875:6/18/68:23400", "James:Ikeda:834-938-8376:23445 Aster Ave.:Allentown:NJ:83745:12/1/1938:45000", "Jennifer:Cowan:548-834-2348:408 Laurel Ave.:Kingsville:TX:83745:10/1/35:58900", "Jesse:Neal:408-233-8971:45 Rose Terrace:San Francisco:CA:92303:2/3/2001:500", "Jon:DeLoach:408-253-3122:123 Park St.:San Jose:CA:04086:7/25/53:85100", "Jose:Santiago:385-898-8357:38 Fife Way:Abilene:TX:39673:1/5/58:95600", "Karen:Evich:284-758-2867:23 Edgecliff Place:Lincoln:NB:92743:11/3/35:58200", "Lesley:Kirstin:408-456-1234:4 Harvard Square:Boston:MA:02133:4/22/2001:52600", "Lori:Gortz:327-832-5728:3465 Mirlo Street:Peabody:MA:34756:10/2/65:35200", "Norma:Corder:397-857-2735:74 Pine Street:Dearborn:MI:23874:3/28/45:245700", "Paco:Gutierrez:835-365-1284:454 Easy Street:Decatur:IL:75732:2/28/53:123500", "Popeye:Sailor:156-454-3322:945 Bluto Street:Anywhere:USA:29358:3/19/35:22350", "Sir:Lancelot:837-835-8257:474 Camelot Boulevard:Bath:WY:28356:5/13/69:24500", "Steve:Blenheim:238-923-7366:95 Latham Lane:Easton:PA:83755:11/12/1956:20301", "Tommy:Savage:408-724-0140:1222 Oxbow Court:Sunnyvale:CA:94087:5/19/66:34200", "Vinh:Tranh:438-910-7449:8235 Maple Street:Wilmington:VM:29085:9/23/63:68900", "William:Kopf:846-836-2837:6937 Ware Road:Milton:PA:93756:9/21/46:43500", "Yukio:Takeshida:387-827-1095:13 Uno Lane:Ashville:NC:23556:7/1/29:57000", "Zippy:Pinhead:834-823-8319:2356 Bizarro Ave.:Farmount:IL:84357:1/1/67:89500", "Andy:Warhol:212-321-7654:231 East 47th Street:New York City:NY:10017:8/6/1928:2700000"] def salary_sort_vm(): data = [x.split(':') for x in employee_data] data.pop(0) d = {int(x[-1]):', '.join(x[1::-1]) for x in data} for i in sorted(list(d.keys()), reverse=True): print("{0:>12}: {1}".format(i, d[i])) def salary_sort(): data = [x.split(':') for x in employee_data] data.pop(0) d = {int(x[8]):x[0:7] for x in data} sorted_tuples = sorted(d.items(), key=lambda x: x[0], reverse=True) for i in sorted_tuples: print("{0:>10}, {1:>10} {2:>10}".format(i[1][1],i[1][0],i[0])) # print("{0:>12} {1:>12} {2:>12}".format(sorted_tuples[0], sorted_tuples[1])) print("-"*50) print("Salary Sort:") print("-"*50+"\n") salary_sort()
import math # make a SD calculator # take in inputs as numbers divided by commas # make a function which retruns the number of inputs (len(smth)) # make another function that add all values and returns value # make another function that calculates mean and returns its value # run a while loop which ends when user inputs '.' as their input # ask them what their digit is. after that, ask them how many times the value occurs (cannot be 0 for now) # after gathering the digit and the iterations, run a for loop which will insert the digit into a list def takeInputs(): cont = True numberList = list() print("Please enter the chosen digits and their frequencies below. If you want to stop entering any more digits, please enter a fullstop anytime, anywhere.\n") while(cont == True): digit = input("Enter a digit from your population: ") if '.' in digit: break iterations = input("Enter the frequency of the digit: ") if '.' in iterations: break for i in range(0,int(iterations)): numberList.append(int(digit)) print(" ") return numberList def choice(): print("What are you trying to find?") print("1- Mean") print("2- Variance") print("3- Standard Deviation") print("Please enter number assigned to what you are looking for.") print(" ") choice = input("Choice: ") print("") return int(choice[0]) def count(numberList): return len(numberList) def sumValue(numberList): return sum(numberList) def mean(numberList): return sumValue(numberList)/count(numberList) def differences(numberList): # subtract mean(numberlist) from each element in numberList # and append to a new list # return the new list differencesList = list() for i in numberList: differencesList.append(i - mean(numberList)) return differencesList #differencesList = differences(numberList) def differencesSquared(numberList): differencesList = differences(numberList) differencesSquaredList = list() for i in differencesList: differencesSquaredList.append(i**2) return differencesSquaredList #differencesSquaredList = differencesSquared(differencesList) def sumOfDifferencesSquared(numberList): differencesSquaredList = differencesSquared(numberList) return sum(differencesSquaredList) def variance(numberList): return sumOfDifferencesSquared(numberList)/count(numberList) #variance = variance(differencesSquaredList,numberList) def standardDeviation(numberList): variance1 = variance(numberList) return math.sqrt(variance1) #print("The standard deviation is "+ str(standardDeviation(variance)) + "." ) def main(): numberList = takeInputs() want = choice() if want == 1: print("The mean is "+ str(mean(numberList)) + ".") elif want == 2: #differencesList = differences(numberList) #differencesSquaredList = differencesSquared(numberList) variance1 = variance(numberList) print("The variance is " + str(variance1) + ".") elif want == 3: #differencesList = differences(numberList) #differencesSquaredList = differencesSquared(numberList) #variance1 = variance(numberList) standardDeviation1 = standardDeviation(numberList) print("The standard deviation is " + str(standardDeviation1) + ".") else: print("We do not provide what you are looking for. Please restart the program and try again.") main()
#! /usr/bin/env python # -*- coding: UTF-8 -*- import copy class Point: x = 0 y = 0 def __init__(self, x, y): self.x = x self.y = y def __str__(self): return '({0}, {1})'.format(self.x, self.y) def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def asTuple(self): return (self.x, self.y)
# **************************** Challenge: Sensitive Information **************************** ''' Author: Trinity Terry pyrun: python sensitive_info.py ''' # Create a class to represent a patient of a doctor's office. The Patient class will accept the following information during initialization # Social security number # Date of birth # Health insurance account number # First name # Last name # Address class Patient: # Define getters for all properties. # Define a setter for all but the read only property. # Ensure that only the appropriate value can be assigned to each. def __init__(self, ssn, dob, hianum, f_name, l_name, address): """ Creates Class Instance Student(first_name: str, last_name: str, age: int, cohort_number: int) Returns: Instance """ self.social_security_number = ssn self.date_of_birth = dob self.health_insurance_acc_num = hianum self.first_name = f_name self.last_name = l_name self.address = address # First name (string) @property def social_security_number(self): try: return self.__social_security_number except AttributeError: return 0 @social_security_number.setter def social_security_number(self, ssn): try: if self.social_security_number is 0 and type(ssn) is str: self.__social_security_number = ssn elif self.social_security_number is not 0: raise AttributeError elif type(ssn) is not str: raise TypeError except AttributeError: print("Cannot update social_security_number ") except TypeError: print("Please provide a string variable for the social_security_number") @property def date_of_birth(self): try: return self.__date_of_birth except AttributeError: return 0 @date_of_birth.setter def date_of_birth(self, dob): try: if self.date_of_birth is 0 and type(dob) is str: self.__date_of_birth = dob elif self.date_of_birth is not 0: raise AttributeError elif type(dob) is not str: raise TypeError except AttributeError: print("Cannot update date_of_birth ") except TypeError: print("Please provide a string variable for the date_of_birth") @property def health_insurance_acc_num(self): try: return self.__health_insurance_acc_num except AttributeError: return 0 @health_insurance_acc_num.setter def health_insurance_acc_num(self, hianum): try: if type(hianum) is str: self.__health_insurance_acc_num = hianum else: raise TypeError except TypeError as taco: print("Please provide a string variable for the health_insurance_acc_num") @property def first_name(self): try: return "" except AttributeError: return 0 @first_name.setter def first_name(self, first_name): try: if type(first_name) is str: self.__first_name = first_name else: raise TypeError except TypeError as taco: print("Please provide a string variable for the first_name") @property def last_name(self): try: return "" except AttributeError: return 0 @last_name.setter def last_name(self, last_name): try: if type(last_name) is str: self.__last_name = last_name else: raise TypeError except TypeError as taco: print("Please provide a string variable for the last_name") @property def full_name(self): try: return f"{self.__first_name} {self.__last_name}" except AttributeError: return 0 # instance of Product class cashew = Patient( "097-23-100", "08/13/92", "7001294103", "Daniela", "Agnoletti", "500 Infinity Way" ) # This should not change the state of the object cashew.social_security_number = "838-31-2256" # Neither should this cashew.date_of_birth = "7001294103" # But printing either of them should work print(cashew.social_security_number) # "097-23-1003" # These two statements should output nothing print(cashew.first_name) print(cashew.last_name) # # But this should output the full name print(cashew.full_name) # "Daniela Agnoletti"
''' Search algorithms. ''' import click from collections import deque from copy import copy from core.match import PatternMatcher from core.structures import AnnotatedSentence,Pattern class GraphSearch(): ''' Base class for Graph Searching Algorithms. Probably not as important in Python since duck-typing... ''' @staticmethod def find_all_paths(graph, start_node, queue): click.echo('# Uh oh! If this is called, something has not been properly configured.') return [] class BreadthFirstWithQueue(GraphSearch): ''' Search the graph using a Breadth-First search, with each level popping the search queue. ''' @staticmethod def find_all_paths(graph, start_node, queue, verbose=False): ''' Provide a graph reference, the starting node, and the search queue. ''' # The debug/verbose statements are useful for debugging, but they could # probably be cleaned up and re-worded. if verbose: # This just prints the queue in normal-order rather than reverse-order. q = [x.word for x in queue] q.reverse() click.echo('SearchQ: ' + ' '.join(q)) # if the queue is empty, pop() will throw an exception. Also there are no patterns # that could be found with an empty queue, so we just exit here. if not queue: if verbose: click.echo(click.style('No queue, exiting.', fg='bright_red')) return [] # Python doesn't provide a peek() method on queues, so to look at the first # item, it has to be popped and then reinserted to the *front* of the queue. first_word = queue.pop() # If the head of the queue doesn't match the pattern's start node, stop searching. # A queue of words must form a path through the pattern 'maze'. If it fails the # entry check, then no complete paths can exist. if verbose: click.echo('{}({})[{}] == {}({})[{}] ?'.format(first_word.word, first_word.pos, first_word.types, start_node.word, start_node._pos, start_node._types)) if not PatternMatcher.word_matches_pattern(first_word, start_node): if verbose: click.echo(click.style("'{}' doesn't match, stopping search.".format(first_word.word), fg='bright_red')) return [] # Add the first_word back into the queue so we can look at the successor nodes # The main search loop evaluates child elements, so we need to insert the # starting parent node back into the queue, so it can be treated like a child queue.appendleft(first_word) if verbose: click.echo("Word = {}".format(click.style(first_word.word, fg='cyan'))) # We have a queue of words (the annotated sentence), but now we need to create # a search_queue for the breadth-first-search algorithm implementation. search_queue = deque() search_queue.append((start_node,queue,[first_word])) saved_paths = [] # go until the search queue is empty while search_queue: if verbose: click.echo('> Search queue loop:') # each search_queue item is the graph-node, the current queue of words, # and the path/route taken through the pattern graph so far. node,wordq,path = search_queue.pop() if verbose: click.echo('Popped: {}({}) : {}'.format(node.word, node._pos, ','.join([x.pos for x in path]))) if verbose: click.echo('Successors (before end): {}'.format(','.join([x._pos for x in graph.successors(node)]))) # If end of graph (successfully found a path through the graph), save the # route as a matched pattern. if len(list(graph.successors(node))) == 0: if verbose: click.echo(click.style('END GRAPH, SAVING PATTERN', fg='green')) click.echo(click.style(' '.join([x.word for x in path]), fg='cyan')) # reached a final node, save this path. saved_paths.append((path)) # Breadth-first-search through all the successor nodes to find all paths # that match this pattern. for i,successor in enumerate(graph.successors(node)): # copy the queue rather than reference to avoid feeding a half-chewed # queue to the next iteration of the loop. queue_copy = copy(wordq) # exit if empty queue, because popping an empty queue throws an exception if not queue_copy: break # algorithm is evaluating the head of this queue word = queue_copy.pop() if verbose: click.echo('Checking word: {}'.format(click.style(word.word, fg='bright_cyan'))) click.echo('Successor -> {} {} {}'.format(i, successor.word, successor._pos)) if verbose: click.echo('Checking: {}({}) == {}({})'.format(click.style(word.word, fg='bright_cyan'), word.pos, click.style(successor.word, fg='bright_yellow'), successor._pos)) # Compare the word's attributes with the pattern node's attribute requirements if PatternMatcher.word_matches_pattern(word, successor, verbose=verbose): if verbose: click.echo('Successor MATCH: {}({}) = {}({})'.format(word.word, word.pos, successor.word, successor._pos)) # Avoids rare duplicates in path. Not sure why this happens, but this # conditional prevents the effects! if word not in path: path += [word] # Append the successors to the BFS queue search_queue.append((successor, queue_copy, path)) else: if verbose: click.echo(click.style('No match.', fg='bright_yellow')) return saved_paths class MatchBuilder(): @staticmethod def find_all_matches(annotated_sentence, pattern, algorithm, verbose=False): ''' Returns a list of all the paths that can be found in the provided sentence using the provided pattern graph. The algorithm used to traverse the graph and find patterns is also needed. ''' sentence_queue = annotated_sentence.get_queue() matches = [] # for every word in the sentence... while sentence_queue: # get the word that starts the queue # make a copy because we can have queues # this could be improved, but basically we get the first word to do the # initial evaluation, but because we still need this word, we put it back in. # Once the tests work, try just feed every word into the algorithm.find_all_paths(...) # and see if the result is the same (should be the proper way) queuecopy = copy(sentence_queue) # see if the word matches any of the entry points for the pattern for entry in pattern.graph_entry_points: # work with values rather than references, otherwise later patterns # would be provided with empty lists (all the data has been popped) q = copy(queuecopy) word = q.pop() q.append(word) if verbose: click.echo('Entry point: {}({})'.format(entry.word, entry._pos)) click.echo('Checking: {}({})'.format(word.word, word.pos)) # get a list of all the paths through the pattern graph results = algorithm.find_all_paths(pattern.graph, entry, q, verbose) if len(results) > 0: matches += results sentence_queue.pop() return matches
# 42. Write a Python program to convert a list to a tuple. list_=[1,2,4,9,5] print(list_) tuple_=tuple(list_) print("the reaquired tuple is:",tuple_)
# 7. Write a Python function that accepts a string and calculate the number of # upper case letters and lower case letters. def up_low(string_): upper_=0 lower_=0 for i in string_: if i.isupper(): upper_+=1 elif i.islower(): lower_+=1 else: pass return(upper_,lower_) print(up_low("How do we gain a basic idea about Python programming"))
# 12. Write a Python program to create a function that takes one argument, and # that argument will be multiplied with an unknown given number def fund1(n): return lambda x:x*n result=fund1(2) print("the multiplication is",result(10))
# 17. Write a Python program to multiplies all the items in a list. def mul_list(myList_): result = 1 for x in myList_: result = result * x return result list_1=[1,2,3] print(mul_list(list_1))
#! /usr/bin/python37 """ Author: Wytze Gelderloos Date: 30-7-2019 Overlap Graphs This function takes a list of DNA sequences and outputs an adjacency list All overlap between the ends of DNA sequences can only occur once. """ file = open("rosalind_grph.txt", "r") string = file.read() string_list= string.split(">") string_list.pop(0) ## reading the string obtained from file into a list of lists superstring_list=[] for string in string_list: all_str = string.split("\n") superstring = "".join(all_str[1:]) superstring_list.append([all_str[0],superstring]) ## formatting that list of lists into a dictionary string_dic = {} for item in superstring_list: string_dic[item[0]] = [item[1]] ## iteraing through the dic two times for key,values in string_dic.items(): for key2, values2 in string_dic.items(): if key != key2 and len(values) >= 1 and len(values2) >= 1: ## if the start of the dictionary is equal to the end of another if values[0][:3]== values2[0][-3:]: ## print print(key2, key) print(string_dic)
########################################################################## # Love is the Ruin of Us All # # The social network of infatuation can be represented by a dictionary # which maps a person's name to a set of people who are infatuated by # that person (one person can have a crush on many other people). For # instance, the dictionary # # s = {'Ana': {'Bine', 'Cene'}, # 'Bine': set(), # 'Cene': {'Bine'}, # 'Davorka': {'Davorka'}, # 'Eva': {'Bine'}} # # tells us that Ana has a crush on Bine and Cene. Bine is not infatuated # with anyone. Cene loves Bine, Davorka only loves herself, and Eva loves # Bine. ########################################################################## ########################################################################## # Write a function narcissists(d) that takes a dictionary of infatuation # and returns the _set_ of people who love themselves. Example (`s` is # the above dictionary): # # >>> narcissists(s) # {'Davorka'} ########################################################################## ########################################################################## # Write a function loved_ones(d) that takes a dictionary of infatuation # and returns the _set_ of those people who are loved by at least one # person. Example (`s` is the above dictionary): # # >>> loved_ones(s) # {'Bine', 'Davorka', 'Cene'} ########################################################################## ########################################################################## # Write a function couples(d) that takes a dictionary of infatuation # and returns the _set_ of couples who could be happily in love. Each couple # should occur only once in the set. The two names should be ordered # lexicographically. For instance, if Bine and Ana are happily in love # then the pair `('Ana', 'Bine')` should be included. Example (`s` is the # above dictionary): # # >>> couples(s) # {('Ana', 'Cene')} ########################################################################## ########################################################################## # Write a function compliant_people(name, d) that takes a person's name # and a dictionary of infatuation and returns the _set_ of people that are # overly compliant to that person. They are overly compliant because they # have a crush on that person or they have a crush on a person who is # compliant to that person. # # For example, if the dictionary is # # s2 = {'Ana': {'Bine', 'Cene'}, # 'Bine': {'Ana'}, # 'Cene': {'Bine'}, # 'Davorka': {'Davorka'}, # 'Eva': {'Bine'}} # # then Ana is compliant to Cene because she has a crush on him. Bine is # also compliant to Cene because he has a crush on Ana. Moreover, Eva is # compliant to Cene because she has a crush on Bine. Cene is compliant to # himself because he has a crush on Bine. Example: # # >>> compliant_people('Cene', s2) # {'Ana', 'Bine', 'Cene', 'Eva'} ##########################################################################
import random ########################################################################## # Write a function number_of_holes(n) that takes an integer n and returns # the total number of holes of its digits (when the number is written in # base 10). For instance, the digits 0, 4 have 1 hole each and the digit # 8 has 2 holes. # # Example: # # >>> number_of_holes(5423087) # 4 ########################################################################## ########################################################################## # Amicable numbers are two different numbers such that the sum of the # proper divisors of each is equal to the other number. Write a function # amicable(n) that takes an integer n and prints all such pairs (a, b) # of amicable numbers where $1 < a < b \leq n$. # # Example: # # >>> amicable(10000) # 220 284 # 1184 1210 # 2620 2924 # 5020 5564 # 6232 6368 ########################################################################## ########################################################################## # Write a function auto_numbering(s) that takes a string and replaces # every character '#' in the string with a number. The first '#' is # replaced by 1, the second '#' by 2 etc. # # Example: # # >>> auto_numbering('I saw # cow, # frogs and # bears.') # 'I saw 1 cow, 2 frogs and 3 bears.' ########################################################################## ########################################################################## # Write a function multiplication_table(n) that takes an integer and # prints the multiplication table of size n × n. # # Example: # # >>> multiplication_table(5) # 1 2 3 4 5 # 2 4 6 8 10 # 3 6 9 12 15 # 4 8 12 16 20 # 5 10 15 20 25 ########################################################################## ########################################################################## # Write a function buffon(n) that takes an integer n and simulates the # Buffon's needle experiment where the needle is thrown for n times. # The function should return the ratio between the number of positive # outcomes (the needle lies across a line) and the number of all performed # experiments. # # See https://en.wikipedia.org/wiki/Buffon's_needle for more details. # # Example: # # >>> buffon(100) # 0.651 ########################################################################## ########################################################################## # Write a function is_palindromic_sentence(s) that takes a string s and # returns True if and only if the string s is a palindromic sentence. We # say that a string is a palindromic sentence if it is a palindrome when # the non-alphabetical characters and the case are ignored. # # Examples: # # >>> is_palindromic_sentence("Tolpa natika kita na plot.") # True # >>> is_palindromic_sentence("We all live in a yellow submarine!") # False ##########################################################################
########################################################################## # Write a function in_union(x, y, circles) which returns True if the # point $(x, y)$ lies in at least one of the circles from the list # circles. Otherwise, the function must return False. # # The list circles is comprised of triples of the form $(x_i, y_i, r_i)$. # Each triple represents a circle with centre at $(x_i, y_i)$ and # radius $r_i$. # # Example: # # >>> circles = [(0, 0, 1), (1, 0, 0.5), (2.5, 1, 1.5)] # >>> in_union(3, 1, circles) # True # >>> in_union(0.75, 0, circles) # True # >>> in_union(0.75, 1, circles) # False ########################################################################## ########################################################################## # Write a function in_intersection(x, y, circles) which returns True if # the point $(x, y)$ lies in the intersection of all circles from the list # circles. Otherwise, the function must return False. # # Example: # # >>> circles = [(0, 0, 1), (1, 0, 0.5), (0, 1.5, 1.5)] # >>> in_intersection(0.8, 0.3, circles) # True # >>> in_intersection(0.75, 0, circles) # False ########################################################################## ########################################################################## # Write a function bounding_box(circles) which finds the smallest rectangle # that contains the union of circles from the list circles. Function should # return a tuple of the form $(x_min, y_min, x_max, y_max)$, i.e., the # coordinates of the bottom left corners followed by coordinates of the # top right cornes. # # Example: # # >>> circles = [(0, 0, 1), (1, 0, 0.5), (0, 1.5, 1.5)] # >>> bounding_box(circles) # (-1.5, -1, 1.5, 3) ########################################################################## ########################################################################## # Write a function approximate_area(circles, n) which determines the area # of the union of circles using the Monte Carlo method: # # The function randomly picks n points in the bounding box of the union # of circles. Then it counts the number of those points that lie in at # least one of those circles. The approximate area can be obtain as the # product of area of the bounding box and the ratio between the number # of points inside the union and number n. ##########################################################################
# Project Sudoku def load_sudoku(file_name): m = [] with open(file_name) as f: for i in range(9): line = list(f.readline().strip()) for j in range(len(line)): if line[j] == '.': line[j] = 0 else: line[j] = int(line[j]) m.append(line) return m def draw_sudoku(m): for i in range(9): if i % 3 == 0: print('+---+---+---+') line = '' for j in range(9): if j % 3 == 0: line += '|' line += ' ' if m[i][j] == 0 else str(m[i][j]) print(line + '|') print('+---+---+---+') def update_forbidden(fm, row, col, entry): for j in range(9): fm[row][j].add(entry) for i in range(9): fm[i][col].add(entry) ii = row // 3 jj = col // 3 for k in range(3): for l in range(3): fm[ii*3 + k][jj*3 + l].add(entry) def forbidden_matrix(m): f = [[set() for j in range(9)] for i in range(9)] for i in range(9): for j in range(9): if m[i][j] == 0: continue else: update_forbidden(f, i, j, m[i][j]) return f def solve(m): ALL_DIGITS = {1,2,3,4,5,6,7,8,9} f = forbidden_matrix(m) ii, jj, size = None, None, -1 for i in range(9): for j in range(9): if m[i][j] != 0: continue if len(f[i][j]) > size: size = len(f[i][j]) ii = i jj = j if ii is None: return m for d in ALL_DIGITS - f[ii][jj]: m2 = [l[:] for l in m] m2[ii][jj] = d solution = solve(m2) if not solution is None : return solution return None pass s = load_sudoku('easy01.txt') draw_sudoku(solve(s))
########################################################################## # Encryption # # A substitution cipher is a simple method of encryption by which each letter # of a given alphabet is replaced by another letter. Such a cipher is # represented by a dictionary that maps letter to their corresponding # encrypted letters. # # For instance, dictionary `{'A': 'B', 'C': 'C', 'B': 'D', 'D': 'A'}` # means that `'A'` is replaced by `'B'`, `'B'` by `'D'`, `'D'` by `'A'` # and `'C'` remains `'C'`. ########################################################################## # In all examples that follow the following substitution cipher will be used: our_cipher = { 'Y': 'K', 'A': 'O', 'C': 'Z', 'B': 'M', 'E': 'V', 'D': 'C', 'G': 'P', 'F': 'E', 'I': 'B', 'H': 'F', 'K': 'I', 'J': 'A', 'M': 'U', 'L': 'H', 'O': 'R', 'N': 'X', 'P': 'J', 'S': 'T', 'R': 'L', 'U': 'G', 'T': 'Y', 'V': 'N', 'Z': 'Q', 'X': 'S', 'Q': 'D', 'W': 'W' } ########################################################################## # Write a function encrypt(cipher, word) that returns the encryption # of `word` using `cipher`. Assume that each letter of the `word` is a # key of the dictionary `cipher`. Example: # # >>> encrypt(our_cipher, 'PHYSICS') # 'JFKTBZT' ########################################################################## ########################################################################## # Write a function is_cipher(dictionary) that determines if `dictionary` # represents a cipher, i.e., if it is a bijection on some alphabet. # Example: # # >>> is_cipher(our_cipher) # True ########################################################################## ########################################################################## # Write a function inverse(cipher) that returns the inverse of a given # cipher. If the inverse does not exist then the function should return # `None`. Example: # # >>> inverse({'A': 'D', 'B': 'A', 'D': 'J', 'J': 'B'}) # {'A': 'B', 'B': 'J', 'J': 'D', 'D': 'A'} ########################################################################## ########################################################################## # Write a function decrypt(cipher, word) that takes a cipher and an # encrypted word and returns the decrypted word. If the dictionary is # not a bijection (and it is therefore not possible to decrypt the word) # then the function should return `None`. Example: # # >>> decrypt(our_cipher, 'JFKTBZT') # 'PHYSICS' ##########################################################################
########################################################################## # FizzBuzz # # FizzBuzz is a popular game among children. Children pronounce numbers # 1, 2, 3, ... If the number is divisible by 3 then they should say ‘Fizz!’ # instead of the number. If it is divisible by 5 then they should say # ‘Buzz!’. If it is divisible by 3 and 5 then they should say ‘Fizz buzz!’. ########################################################################## ########################################################################## # Write a function fizzbuzz(n) that takes a natural number n as the # argument. The function should return a list of numbers from 1 to n, where: # # * the multiples of 3 are replaced with string 'Fizz', # * the multiples of 5 are replaced with string 'Buzz', # * the multiples of 15 are replaced with string 'FizzBuzz'. # # Example: # # >>> fizzbuzz(15) # [1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', # 13, 14, 'FizzBuzz'] ########################################################################## ########################################################################## # Write a function store_fizzbuzz(file_name, n) where the arguments are # a string file_name which contains the name of a file and a natural # number n. The function should store the elements of the list returned by # fizzbuzz(n) to the file named file_name. Each element should be in its # own line. # # Example: After the call store_fizzbuzz('fizzbuzz.txt', 5) the file # fizzbuzz.txt should contain: # # 1 # 2 # Fizz # 4 # Buzz ########################################################################## ########################################################################## # Write a function detect_errors(l) that takes a list l as the argument. # This list is a FizzBuzz sequence, but it may contain errors. # The function should return a list with those indices of the list l where # errors occured. The elements of this list should be sorted. # # Example: # # >>> detect_errors([1, 2, 3, 'Fizz', 'Buzz', 7, 'Fizz', 8]) # [2, 3, 5, 6] ########################################################################## ########################################################################## # Write a function buzzfizz(n) which should return the same result as the # fizzbuzz function. The function buzzfizz should be defined recursively. # # In this task you should not use for or while loop. Also, you are not # allowed to call the fizzbuzz function :-) # # Example: # # >>> buzzfizz(15) # [1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', # 13, 14, 'FizzBuzz'] ########################################################################## def buzzfizz(n): if n == 0: return [] if n % 3 == 0 and n % 5 == 0: lis = buzzfizz(n-1) lis.append('FizzBuzz') return lis elif n % 3 == 0: lis = buzzfizz(n-1) lis.append('Fizz') return lis elif n % 5 == 0: lis = buzzfizz(n-1) lis.append('Buzz') return lis else: lis = buzzfizz(n-1) lis.append(n) return lis print(buzzfizz(13))
""" File: extension.py -------------------------- This file collects more data from https://www.ssa.gov/oact/babynames/decades/names2010s.html https://www.ssa.gov/oact/babynames/decades/names2000s.html https://www.ssa.gov/oact/babynames/decades/names1990s.html Please print the number of top200 male and female on Console You should see: --------------------------- 2010s Male Number: 10890537 Female Number: 7939153 --------------------------- 2000s Male Number: 12975692 Female Number: 9207577 --------------------------- 1990s Male Number: 14145431 Female Number: 10644002 """ import requests from bs4 import BeautifulSoup def main(): for year in ['2010s', '2000s', '1990s']: print('---------------------------') print(year) url = 'https://www.ssa.gov/oact/babynames/decades/names'+year+'.html' ################## response = requests.get(url) html = response.text soup = BeautifulSoup(html) items = soup.tbody.text item = items.split() male_val = [] female_val = [] for i in range(0, len(item), 5): rank = item[i] man_val = '' for ch in item[i+2]: if ch != ',': man_val += ch woman_val = '' for ch in item[i + 4]: if ch != ',': woman_val += ch if rank == '200': male_val.append(int(man_val)) female_val.append(int(woman_val)) break male_val.append(int(man_val)) female_val.append(int(woman_val)) print('Male Number:', sum(male_val)) print('Female Number:', sum(female_val)) ################## if __name__ == '__main__': main()
# # 1. Дан список a = [1, 2, 2, 4, 11, 2, 3, 1]. Напишите код, который выведет # # список a без дубликатов. # print("Задание №1 :") # a = [1, 2, 2, 4, 11, 11, 3, 4, 4, 2, 5, 5, 3, 1] # print('Исходный список: ', a) # a = list(set(a)) # print(f'Новый список без дубликатов: {a}') # # # # 2. Дан список a = [‘John’, ‘Anna’, ‘Raychel’, ‘Katarina’, ‘Marko’, ‘Tom’] # # Удалите из списка 0, 4 и 5 элементы списка. # print("Задание №2 :") # a = ['John', 'Anna', 'Raychel', 'Katarina', 'Marko', 'Tom'] # del a[5] # del a[4] # del a[0] # print("Список после удаления элементов: ", a) # # # 3. Дан список [1, 2, 3, 4, 5, 6, 7, 8, 9]. Отсортируйте его в обратном # # порядке. # print("Задание №3 :") # list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9] # print("Исходный список: ", list_) # list_.sort(reverse=True) # print(f"Отсортированный список: {list_}") # # # # 4. Измените один элемент списка с любым значением на новое. # print("Задание №4 :") # list_ = [1, 2, 3, 4, 5, 6, 7, 8, 9] # new_item = int(input('Введите новое значение: ')) # list_[5] = new_item # print(list_) # # # 5. Попросить пользователя ввести слова через пробел. Отсортировать # # слова по количеству символов и вывести на экран результат. # print("Задание №5 :") # list_ = input("Введите слова через пробел: ") # sorted_list = list_.split() # sorted_list.sort(key=len) # print(sorted_list) # # # # 6. Напишите код для проверки существует ли ключ в dict. # print("Задача №6 ") # key_ = input('Введите ключ для проверки: ') # new_dict = dict(zip(['Russia', 'Kyrgyzstan', 'USA'], ['Moscow', 'Bishkek', 'washington'])) # key = 0 # a = "Такога ключа нет в словаре" # for key in new_dict.keys(): # if key == key_: # a = 'Такой ключ есть в словаре' # # print(a) # # # 7. Напишите программу для объединения двух словарей в один. # print("Задача №7 ") # currency = { # 'Kyrgyzstan': 'som', # 'Russia': 'rubli', # 'USA': 'dollar' # } # currency2 = { # 'UK': 'euro', # 'China': 'yuan' # } # currency.update(currency2) # print(f'Объединенный словарь: {currency}') # # # # 8. Напишите программу для сортировки dict по ключам. # print("Задача №8 ") # currency = {'Kyrgyzstan': 'som', 'Russia': 'rubli', 'USA': 'dollar', 'UK': 'euro', 'China': 'yuan'} # currency2 = {} # cur = sorted(currency.keys()) # for i in cur: # print(i, ':', currency.get(i)) # # # 9. Напишите код, который проверяет пуст ли словарь. # print("Задача №9 ") # dictionary_ = {} # if len(dictionary_) == 0: # print('Словарь пуст ') # else: # print('Словарь не пуст ') # # # 10. Создайте список. Добавьте в него 3 новых элемента. Сделайте так, # # чтобы этот список нельзя было больше изменить. # print("Задача №9 ") # dict_1 = {} # dict_1[1] = 'один' # dict_1[2] = 'два' # dict_1[3] = 'три' # print(dict_1) # dict_typle1 = tuple(dict_1.items()) # print(dict_typle1) # # # 11. Создайте программу, которая спрашивает логин и пароль. Запишите # # данные в dictionary и выведите результат. # print("Задача №11") # login = input(" Enter your login: ") # password = input('Enter your password: ') # if len(password) < 8: # print("Password too short!") # else: # d = {login: password} # print(d) # # # # 12. Напишите программу, чтобы проверить, является ли буква гласной # # или согласной. # # Пример: # # Введите букву алфавита: к # # Вывод: к согласная. # print("Задача №12") # rus_vowels = set('ауеыоэи') # eng_vowels = set('eyuioa') # letter = input("Enter one your letter: ") # if letter in rus_vowels or letter in eng_vowels: # print(f" The letter '{letter}' is vowel") # else: # print(f"The letter '{letter}' is consonant") # # # # 13. Есть корзина наполненная n количеством яблок. Так же есть x # # количество студентов. Разделите яблоки поровну между всеми # # студентами. Если студентов больше чем яблок, то оставьте их в # # корзине. Выведите в результат количество студентов, количество яблок # # и остаток в корзине. # print("Задача №13") # apples = int(input('Введите количество яблок:')) # students = int(input('Введите количество студентов')) # print(f'{students} студентов получают по {apples//students} яблок') # if apples % students == 0: # print("В корзине не осталось яблок") # else: # print(f'В корзине осталось - {str(apples%students)} яблок') # # # # 14. Для обустройства учебного кабинета необходимо приобрести парты. # # Количество учеников вводит пользователь. Необходимо определить # # сколько парт нужно купить, если ученики сидят по двое за одной партой. # # Так же если учеников нечетное количество, то кто-то будет сидеть один # # за партой. # print("Задача №14") # students = int(input("enter count of students: ")) # if students % 2 == 0: # print(students//2) # else: # print(f'You need {students//2 +1} desktops') # # # # 15. Напишите программу для расчета возраста собаки в человеческих # # годах. Пользователь может ввести возраст и размер (маленькая, # # средняя, крупная). Для вычисления умножте возраст собаки на 9 # # человеческих лет за каждый собачий для маленьких собак; # # 10,5 лет для средних собак; # # 12,5 лет для крупных собак; # print("Задача №15") # vozr = int(input("Введите возраст: ")) # razm = input("Введите размер (маленький, средний, крупный): ") # if razm == 'маленький': # print(f'Собаке {vozr *9} лет') # elif razm == 'средний': # print(f'Собаке {vozr * 10.5} лет') # else: # print(f'Собаке {vozr *12.5} лет') # # # # 16. Пользователь вводит три числа. Если все числа больше 10, то # # вывести на экран yes, иначе no. # # print('yes' if all(x>10 for x in nums) else 'no') # print("Задача №16") # list_ = [] # list_.append(int(input('Введите первое число: '))) # list_.append(int(input('Введите второе число: '))) # list_.append(int(input('Введите третье число:'))) # if all(x > 10 for x in list_): # print('Yes') # else: # print('No') # # # # 17. Дано три числа. Найти количество положительных чисел среди них. # print("Задача №17") # a = int(input("Первое число: ")) # b = int(input("Второе число: ")) # c = int(input("Третье число: ")) # print('Количество положительных чисел: ', (a > 0) + (b > 0) + (c > 0)) # # # # 18. Составить в интерпретаторе Python программу которая: # # - просит пользователя ввести целое число и присваивает его # # переменной num # # - просит пользователя ввести множитель для возведения в степень и # # присваивает его переменной step # # - проверяет истинность условия, что введенное пользователем целое # # число num меньше 100 # # - если это условие ИСТИННО, то необходимо возвести число num в # # степень step (напоминаю, возведение в степень осуществляется # # оператором **) и присвоить результат переменной rezult. # # Результат вывести на печать # # - если результат проверки ЛОЖЬ, то вывести на печать сообщение: # # "Введенное вами число > 100". # print("Задача №18") # num = int(input("Введите целое число: ")) # step = int(input("Введите степень: ")) # if num < 100: # rezult = num ** step # print(f'Число в степени = {rezult}') # else: # print("Введенное вами число > 100") # # # # 19. Вводятся три целых числа. Определить какое из них наибольшее. # # Пусть a, b, c - переменные, которым присваиваются введенные числа, а # # переменная m в конечном итоге должна будет содержать значение # # наибольшей переменной. Тогда алгоритм программы сведется к # # следующему: # # 1. Сначала предположим, что переменная a содержит наибольшее # # значение. Присвоим его переменной m. # # 2. Если текущее значение m меньше, чем у b, то следует присвоить m # # значение b. Если это не так, то не изменять значение m. # # 3. Если текущее значение m меньше, чем у c, то присвоить m # # значение c. Иначе ничего не делать. # print("Задача №19") # a = int(input("Первое число: ")) # b = int(input("Второе число: ")) # c = int(input("Третье число: ")) # m = a # if m < b: # m = b # if m < c: # m = c # print(f'Наибольшее число {m}') # # # # 20. Вводятся три разных числа. Найти, какое из них является средним # # (больше одного, но меньше другого). # # Проверить, лежит ли первое число между двумя другими. При этом # # может быть два случая: # # первое больше второго и первое меньше третьего, # # первое меньше второго и первое больше третьего. # # Если ни один из вариантов не вернул истину, значит первое число не # # среднее. Тогда проверяется, не лежит ли второе число между двумя # # другими. Это может быть в двух случаях, когда # # второе больше первого и меньше третьего, # # второе меньше первого и больше третьего. # # Если эти варианты также не вернули истину, то остается только один # # вариант - посередине лежит третье число. # print("Задача №20") # a = int(input("Первое число: ")) # b = int(input("Второе число: ")) # c = int(input("Третье число: ")) # if a < c and a > b or a > c and a < b: # print(f"Среднее число {a}") # elif b > a and b < c or b < a and b > c: # print(f"Среднее число {b}") # else: # print(f"Среднее число {c}")
import duckduckgo # diagnostic logging debug = False def DuckWebSearch(search, youtube=False): """Performs a DuckDuckGo Web search and returns the results. youtube : bool True if doing a Youtube lookup Returns: str : the result of the web search """ if debug: print 'DuckWebSearch: search=', search if debug: print 'DuckWebSearch: youtube=', youtube if youtube: #search = 'youtube' + ' ' + search args = {'ia': 'videos'} else: args = {'ia': 'web'} response = duckduckgo.query(search, **args) result = '' json = response.json keys = sorted(json.keys()) #result += str(keys) if 'Image' in keys: result += '\n' + json['Image'] if 'AbstractURL' in keys: result += '\n' + json['AbstractURL'] if 'Abstract' in keys: result += '\n' + json['Abstract'] #for key in keys: # result += '\n%s: %s' % (key, json[key]) return result.strip() def Duck(query, youtube=False): """Performs a DuckDuckGo Web search and returns the results. query : str the string to search for. youtube : bool True if doing a Youtube lookup Returns: str : the result of the web search """ result = DuckWebSearch(query, youtube=youtube) if debug: print 'Duck: result:', result #data = json.loads(result) #import pprint #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(data) return result
"""A helper function for parsing and executing regex skills.""" import logging import re import copy _LOGGER = logging.getLogger(__name__) async def calculate_score(regex, score_factor): """Calculate the score of a regex.""" # The score asymptotically approaches the max score # based on the length of the expression. return (1 - (1 / ((len(regex) + 1) ** 2))) * score_factor async def parse_regex(opsdroid, skills, message): """Parse a message against all regex skills.""" matched_skills = [] for skill in skills: for matcher in skill.matchers: if "regex" in matcher: opts = matcher["regex"] if opts["case_sensitive"]: regex = re.search(opts["expression"], message.text) else: regex = re.search(opts["expression"], message.text, re.IGNORECASE) if regex: new_message = copy.copy(message) new_message.regex = regex matched_skills.append({ "score": await calculate_score( opts["expression"], opts["score_factor"]), "skill": skill, "config": skill.config, "message": new_message }) return matched_skills
import string import nltk from nltk.corpus import stopwords def sort_it_1(fart): lst=list(fart.keys()) lst.sort() print('the keys:\n',lst,'\n') for key in lst: print(key,fart[key]) def sort_by_value(fart): lst=list() for key,val in list(fart.items()): lst.append((val,key)) lst.sort(reverse=True) for key,val in lst: print(key,val) location='text_doc.txt' with open (location) as my_file: lines =my_file.read() ## print('raw read:\n',lines,'\n') lines=lines.split() lines.sort() print('sorted word list:\n',lines,'\n') fart=dict() for word in lines: if word not in fart: fart[word]=1 else: fart[word]+=1 ##print ('word count dict:\n',fart,'\n') #sort_it_1(fart) sort_by_value(fart) R=['the','on','for','is','to','that','in','a','with','of','and','this','as','at'] R2=['*','&','-','/','!','@','_'] setA=set(R+R2) setB=set(lines) print('set R:\n',setA,'\n') print('sorted word list:\n',lines,'\n') print('set B:\n',setB,'\n') no_the=setB.difference(setA) print('without the:\n', no_the,'\n') stuff_removed=list(no_the) print('stuff removed:',stuff_removed) final=dict() for c in stuff_removed: if c not in final: final[c]=1 else: final[c]+=1 print('final dict:',final) sort_by_value(final)
print("Hi I'm test, who are you?", end=' ') name = input() print("How tall are you?", end=' '"Inches.") x = int(input()) height = x / 12 print(f"Hello {name}, you are {height} feet tall. ")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from tkinter import * import tkinter.messagebox as messagebox class MyAPP(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.creatWidget() def creat_widget(self): self.nameInput = Entry(self) self.nameInput.pack() self.button = Button(self, text='ok', command=self._hello) self.button.pack() def _hello(self): name = self.nameInput.get() or 'world' messagebox.showinfo('message', 'hello , %s' % name) app = MyAPP() app.master.title('H') app.mainloop()
def recite(start_verse, end_verse): song = """ a Partridge in a Pear Tree. two Turtle Doves, three French Hens, four Calling Birds, five Gold Rings, six Geese-a-Laying, seven Swans-a-Swimming, eight Maids-a-Milking, nine Ladies Dancing, ten Lords-a-Leaping, eleven Pipers Piping, twelve Drummers Drumming, """.split("\n") days = { 1 : "first", 2 : "second", 3 : "third", 4 : "fourth", 5 : "fifth", 6 : "sixth", 7 : "seventh", 8 : "eighth", 9 : "ninth", 10 : "tenth", 11 : "eleventh", 12 : "twelfth" } output = [f'On the {days[start_verse]} day of Christmas my true love gave to me: '] output[0] = str(output[0]) + str(song[start_verse:0:-1][0]) return output expected = [ "On the second day of Christmas my true love gave to me: " "two Turtle Doves, " "and a Partridge in a Pear Tree." ] print(f"Expected:\n{expected}\n") print(f"Received:\n{recite(2,2)}\n")
def square(number): if number>0 and number<65: return 2**(number-1) else: raise ValueError("Number must be between 1 and 64.") def total(): total=0 i = 1 while i<65: total+=square(i) i+=1 print(total) return total
#!/usr/bin/env python3 import sys print("Digite valores nao-nulos e positivos.") try: a = float(input("Entre com a medida do lado 1 do triangulo: ")) b = float(input("Entre com a medida do lado 2 do triangulo: ")) c = float(input("Entre com a medida do lado 3 do triangulo: ")) except ValueError: print("Digite somente numeros para as medidas 1, 2 e 3.") sys.exit(1) if a<=0 or b<=0 or c<=0 : print("voce declarou uma negativa") quit() if a==b and b==c : print("Triangulo equilatero.") elif a==b or b==c or c==a : print("Triangulo isosceles.") else: print("Triangulo escaleno.")
def students_per_category_line_list_constructor(students_per_category_matrix): """ :param students_per_category_matrix: integer matrix of size - students X rounds (3 rounds assumed) :return: return_list: list of strings used to construct a 2D array document containing the input matrix. details: # each expression in square parentheses is a cell to be printed in the document # cells left blank have the cells below them described in a lower row of the document. # the newrow_cell variable is used to mark a new row. """ newrow_cell = ['\#\#'] return_list = [] # constructing the column headers for a 2D array file (like csv): return_list += [''] + ['students_per_category'] + newrow_cell return_list += [''] + ['round_1'] + ['round_2'] + ['round_3'] + newrow_cell # constructing the row headers and inserting the values in students_per_category_matrix categories = len(students_per_category_matrix[0]) for category_index in range(categories): return_list += ['category_' + str(category_index + 1)] # indexed return_list += [str(students_per_category_matrix[0][category_index])] return_list += [str(students_per_category_matrix[1][category_index])] return_list += [str(students_per_category_matrix[2][category_index])] return_list += newrow_cell return return_list def students_line_list_constructor(worksheet): """ :param: students an object obtained with the syntax <object_name>.worksheet["students"] in analyze.py. :return: return_list: list of strings used to construct a 2D array document containing the input matrix. details: # each expression in square parentheses is a cell to be printed in the document # cells left blank have the cells below them described in a lower row of the document. # the newrow_cell variable is used to mark a new row. """ newrow_cell = ['\#\#'] students = worksheet['students'] google_categories = worksheet['google_categories'] # constructing the table header header_row1 = [''] * 7 + ["round_1"] + [''] * 43 + ["round_2"] + [''] * 43 + ["round_3"] + [''] * 43 roundstring1 = ['google_result_rating'] + [''] * 19 + ['selections_per_category'] + [''] * 9 + [''] + [ 'average_google_category_rank'] + [''] * 12 header_row2 = [''] * 4 + ["jdistances_vs_self_in_3_rounds"] + [''] * 2 + roundstring1 * 3 roundstring2 = [str(a_cell) for a_cell in google_categories] + [str(i + 1) for i in range(10)] + \ ['jdistance_vs_google'] + [str(i + 1) for i in range(10)] + ['pearson_pvalue'] + \ ['pearson_coefficient'] + ["number_of_categories_selected"] header_row3 = ["student_id"] + ["student_last_name"] + ["student_name"] + ["student_notes"] + ['rounds_1&2'] + \ ['rounds_1&3'] + ['rounds_2&3'] + roundstring2 * 3 return_list = header_row1+newrow_cell return_list += header_row2+newrow_cell return_list += header_row3+newrow_cell # constructing the table rows with the data in students for student in students: current_row = list() current_row += [str(student['student_id'])] + [str(student['student_last_name'])] + \ [str(student['student_name'])] + [student['student_notes']] jdistances = student['jdistances'] current_row += [str(jdistances[0]['(1,2)'])] + [str(jdistances[1]['(1,3)'])] + [str(jdistances[2]['(2,3)'])] for a_round in student['rounds']: for an_input in a_round['inputs']: current_row += [str(an_input)] category_selection_counts = list(a_round['category_selection_count'].items()) for index in range(len(category_selection_counts)): # problem reading from p current_row += [str(category_selection_counts[index][1])] current_row += [str(a_round['jdistance'])] for an_avg_google_rank in a_round['avg_google_rank']: current_row += [str(an_avg_google_rank)] current_row += [str(a_round['pearson']['pvalue'])] current_row += [str(a_round['pearson']['coefficient'])] current_row += [str(a_round['uniq_selected_categories'])] return_list += current_row + newrow_cell return return_list
import pickle from math import sqrt import numpy as np from scipy.stats import chi2 import os from .team_comparator import TeamComparator from ..game_attrs import GameValues, GameWeights, Team class PageRankComparator(TeamComparator): """ Ranks all Division I NCAA Basketball teams in a given year using PageRank. See https://en.wikipedia.org/wiki/PageRank """ def __init__( self, year: int, gender: str, iters: int = 10_000, alpha: float = 0.85 ): """ Args: year: The year that the NCAA championship game takes place. The 2019-2020 season would correpond to year=2020. alpha: A value between 0 and 1 that is a measure of randomness in PageRank meant to model the possibility that a user randomly navigates to a page without using a link. alpha=1 would be completely deterministic, while alpha=0 would be completely random. Google is rumored to use alpha=.85. iters: The number of iterations of PageRank matrix multiplication to perform. The default of iters=10_000, about 30x the number of Division I teams, is generally sufficient for ranking. """ super().__init__(year, gender) if not os.path.exists(f"./predictions/{gender}/{year}_pagerank_rankings.p"): self.__rank( year, gender, iters, alpha, serialize_results=True, first_year=True ) self.__build_model(year, gender) def __rank( self, year: int, gender: str, iters: int, alpha: float, **kwargs: dict[str, bool], ): """ Uses PageRank to create a vector ranking all teams. Kwargs: first_year: bool If False, then the previous year's rankings will be used initially. Otherwise, all teams start ranked equally. """ total_summary = TeamComparator.get_total_summary(year, gender) teams = TeamComparator.get_teams(total_summary) num_teams = len(teams) # Create PageRank matrix and initial vector if kwargs.get("first_year"): vec = np.ones((num_teams, 1)) else: vec = self.__rank(year - 1, gender, iters, alpha - 0.1, first_year=True) num_teams = max(num_teams, len(vec)) mat = np.zeros((num_teams, num_teams)) for game in total_summary: # We only want to count games where both teams are D1 (in teams list) # We choose to only look at games where the first team won so we don't double-count games # NOTE: These HOME_TEAM and AWAY_TEAM do not literally tell us if a team is home or away teamA = game[GameValues.HOME_TEAM.value] teamB = game[GameValues.AWAY_TEAM.value] if teamA in teams and teamB in teams and game[GameValues.WIN_LOSS.value]: # Game winner # Since we know the first/home team won, we can already assign the weight for that home_pr_score, away_pr_score = GameWeights.WEIGHTS.value[0], 0.0 # Effective field goal percentage if game[GameValues.HOME_eFGp.value] > game[GameValues.AWAY_eFGp.value]: home_pr_score += GameWeights.WEIGHTS.value[1] elif ( game[GameValues.AWAY_eFGp.value] > game[GameValues.HOME_eFGp.value] ): away_pr_score += GameWeights.WEIGHTS.value[1] # Turnover percentage if game[GameValues.HOME_TOVp.value] < game[GameValues.AWAY_TOVp.value]: home_pr_score += GameWeights.WEIGHTS.value[2] elif ( game[GameValues.AWAY_TOVp.value] < game[GameValues.HOME_TOVp.value] ): away_pr_score += GameWeights.WEIGHTS.value[2] # Offensive rebound percentage if game[GameValues.HOME_ORBp.value] > game[GameValues.AWAY_ORBp.value]: home_pr_score += GameWeights.WEIGHTS.value[3] elif ( game[GameValues.AWAY_ORBp.value] > game[GameValues.HOME_ORBp.value] ): away_pr_score += GameWeights.WEIGHTS.value[3] # Free throw rate if game[GameValues.HOME_FTR.value] > game[GameValues.AWAY_FTR.value]: home_pr_score += GameWeights.WEIGHTS.value[4] elif game[GameValues.AWAY_FTR.value] > game[GameValues.HOME_FTR.value]: away_pr_score += GameWeights.WEIGHTS.value[4] # Add weighted score for this game to matrix for both teams home_idx = teams.index(teamA) away_idx = teams.index(teamB) mat[home_idx, away_idx] += home_pr_score mat[away_idx, home_idx] += away_pr_score # Alter the matrix to take into account our alpha factor mat *= alpha mat += (1 - alpha) * np.ones((num_teams, num_teams)) / num_teams # Perform many iterations of matrix multiplication for _ in range(iters): vec = mat @ vec vec *= num_teams / sum(vec) # Keep weights summed to set value (numerator) # Build rankings sorted_pairs = sorted([(prob[0], team) for team, prob in zip(teams, vec)]) rankings = dict() for team in teams: rankings.setdefault(team, 0) for pair in sorted_pairs: rankings[pair[1]] = pair[0] TeamComparator.serialize_results(year, "pagerank", rankings, vec, gender) return vec def __build_model(self, year: int, gender: str): self._rankings = pickle.load( open(f"./predictions/{gender}/{year}_pagerank_rankings.p", "rb") ) vec = pickle.load(open(f"./predictions/{gender}/{year}_pagerank_vector.p", "rb")) self._df = chi2.fit(vec)[0] self._min_vec, self._max_vec = min(vec)[0], max(vec)[0] def compare_teams(self, a: Team, b: Team) -> float: """ Compare two teams from the same year. Returns the probability that a will win. """ rankA, rankB = self._rankings[a.name], self._rankings[b.name] max_cdf = chi2.cdf(self._max_vec, df=self._df) min_cdf = chi2.cdf(self._min_vec, df=self._df) diff = (max_cdf - min_cdf) / sqrt(2) a_cdf, b_cdf = chi2.cdf(rankA, df=self._df), chi2.cdf(rankB, df=self._df) prob = min(abs(a_cdf - b_cdf) / diff + 0.5, 0.999) return prob if rankA >= rankB else 1 - prob
from random import randrange def input_group(n, m): groups = [] for x in range(m): groups.append([]) for group in groups: for x in range(n): group.append(randrange(100, 1000)) return groups def output(groups_func): counter = 1 for group in groups_func: print("Group {} contains:".format(counter)) counter += 1 for x in group: print(x, end = " ") else: print() def primarity_test(number): for x in range(2, number): if number % x == 0: return False else: return True n = int(input("n = ")) m = int(input("m = ")) my_groups = input_group(n, m) output(my_groups) biggest_group_counter = 0 for group in my_groups: counter = 0 for number in group: if primarity_test(number): counter += 1 else: if biggest_group_counter < counter: biggest_group = group biggest_group_counter = counter print("""There are the most primal numbers in this group:{} There are {} primal numbers in it""".format(biggest_group, biggest_group_counter))
import sys import os class FizzBuzz(object): def __init__(self): self.line_count = 0 self.filename = '' self.check_file() def check_file(self): self.filename = str(sys.argv[1]) if os.path.exists(self.filename): self.import_list(self.filename) else: print "File not found, please try again." def import_list(self, filename): with open(filename) as load_import_data: for line in load_import_data: line = line.split() n = int(line.pop()) y = int(line.pop()) x = int(line.pop()) self.line_count += 1 self.validate_input(x, y, n) def validate_input(self, x, y, n): if 0 < x < 21: if 0 < y < 21: if 20 < n < 101: self.fizzb(x, y, n) else: # print "N value is out of range, skipping this line: {}.\n".format(self.line_count) return else: # print "Y value is out of range, skipping this line: {}.\n".format(self.line_count) return else: # print "X value is out of range, skipping this line: {}.\n".format(self.line_count) return def fizzb(self, x, y, n): for num in range(1, n +1): if (num % x == 0) & (num % y == 0): print 'FB', else: if num % x == 0: print 'F', if num % y == 0: print 'B', if num == n: print '\n' else: print num, test = FizzBuzz()
# -*- coding: utf-8 -*- import random def ls(a, s): found = False i = 0 while i < len(a) and not found: if a[i] == s: found = True i += 1 return found if __name__ == "__main__": array = [] for i in range(random.randint(0, 8)): array.append(random.randint(0, 13)) value = input(u"Введите число: ") g = ls(array, value) if g: print "Элемент найден" else: print "Элемент не найден" print array
import turtle import os import time HEIGHT = 800 WIDTH = 800 a_score = 0 b_score = 0 window = turtle.Screen() window.title("Pong Game") window.bgcolor("black") window.setup(width=WIDTH, height=HEIGHT) window.tracer(n=0) def Draw_shape(pos, wid=5, _len=1, ball=False): paddle = turtle.Turtle() paddle.speed(0) paddle.shapesize(stretch_wid=wid, stretch_len=_len) paddle.shape("square") paddle.penup() paddle.color("white") paddle.goto(pos) if ball: paddle.dx = 0.3 paddle.dy = 0.3 return paddle paddel_a = Draw_shape((-370, 0)) paddel_b = Draw_shape((370, 0)) ball = Draw_shape((0, 0), wid=1, ball=True) ####################Pen############################ pen = turtle.Turtle() pen.speed() pen.color("white") pen.hideturtle() pen.penup() pen.goto(0, 350) pen.write(f"{a_score} {b_score}", align="center", font=("Courier", 23, "bold")) ##################Movment########################### def move_up_a(): y = paddel_a.ycor() y += 15 paddel_a.sety(y) def move_down_a(): y = paddel_a.ycor() y -= 15 paddel_a.sety(y) def move_up_b(): y = paddel_b.ycor() y += 15 paddel_b.sety(y) def move_down_b(): y = paddel_b.ycor() y -= 15 paddel_b.sety(y) window.listen() window.onkeypress(move_up_a, "w") window.onkeypress(move_down_a, "x") window.onkeypress(move_up_b, "Up") window.onkeypress(move_down_b, "Down") while True: window.update() ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) if paddel_b.ycor() - 40 <= -380 : paddel_b.sety(-350) if paddel_a.ycor() - 40 <= -380 : paddel_a.sety(-350) if paddel_b.ycor() + 40 >= 380 : paddel_b.sety(350) if paddel_a.ycor() + 40 >= 380 : paddel_a.sety(350) if ball.ycor() > 390 : os.system("aplay bounce.wav&") ball.dy *= -1 if ball.ycor() < -390: os.system("aplay bounce.wav&") ball.dy *= -1 if ball.xcor() > 390: ball.dx *= -1 a_score += 1 os.system("aplay bounce.wav&") pen.clear() pen.write(f"{a_score} {b_score}", align="center", font=("Courier", 23, "bold")) ball.goto(0, 0) time.sleep(0.6) if ball.xcor() < -390: ball.dx *= -1 b_score += 1 os.system("aplay bounce.wav&") pen.clear() pen.write(f"{a_score} {b_score}", align="center", font=("Courier", 23, "bold")) ball.goto(0, 0) time.sleep(0.6) if (ball.xcor() > 360 and ball.xcor() < 380) and (ball.ycor() < paddel_b.ycor() + 50 and ball.ycor() > paddel_b.ycor() - 50): ball.setx(350) os.system("aplay bounce.wav&") ball.dx *= -1 if (ball.xcor() < -360 and ball.xcor() > -380) and (ball.ycor() < paddel_a.ycor() + 50 and ball.ycor() > paddel_a.ycor() - 50): ball.setx(-350) os.system("aplay bounce.wav&") ball.dx *= -1