text
stringlengths
37
1.41M
''' 1431. 拥有最多糖果的孩子 给你一个数组 candies 和一个整数 extraCandies ,其中 candies[i] 代表第 i 个孩子拥有的糖果数目。 对每一个孩子,检查是否存在一种方案,将额外的 extraCandies 个糖果分配给孩子们之后,此孩子有 最多 的糖果。注意,允许有多个孩子同时拥有 最多 的糖果数目。 示例 1: 输入:candies = [2,3,5,1,3], extraCandies = 3 输出:[true,true,true,false,true] 解释: 孩子 1 有 2 个糖果,如果他得到所有额外的糖果(3个),那么他总共有 5 个糖果,他将成为拥有最多糖果的孩子。 孩子 2 有 3 个糖果,如果他得到至少 2 个额外糖果,那么他将成为拥有最多糖果的孩子。 孩子 3 有 5 个糖果,他已经是拥有最多糖果的孩子。 孩子 4 有 1 个糖果,即使他得到所有额外的糖果,他也只有 4 个糖果,无法成为拥有糖果最多的孩子。 孩子 5 有 3 个糖果,如果他得到至少 2 个额外糖果,那么他将成为拥有最多糖果的孩子。 示例 2: 输入:candies = [4,2,1,1,2], extraCandies = 1 输出:[true,false,false,false,false] 解释:只有 1 个额外糖果,所以不管额外糖果给谁,只有孩子 1 可以成为拥有糖果最多的孩子。 示例 3: 输入:candies = [12,1,12], extraCandies = 10 输出:[true,false,true] ''' from typing import List class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: max_val = max(candies) result = [] for ca in candies: result.append(True if ca + extraCandies >= max_val else False) return result so = Solution() print(so.kidsWithCandies([2,3,5,1,3], 3) == [True, True, True, False, True]) print(so.kidsWithCandies([4,2,1,1,2], 1) == [True, False, False, False, False]) print(so.kidsWithCandies([12,1,12], 10) == [True, False, True])
def finalcountdown(param1,param2,param3,param4): count=param2 while(count<param3): if count % param1 == 0 and count !=param4: print count count=count+1 if __name__ == '__main__': finalcountdown(3,5,17,9)
def lettergrade(score): if score < 60: print "score:" +str(score)+ ".grade:F" elif score >=60 and score <=69: print "score:{}.grade{}".format(score,"D") elif score >70 and score <=79: print "score:{}.grade{}".format(score,"C") elif score >80 and score <= 89: print "score:{}.grade{}".format(score,"B") elif score >=90: print "score:{}.grade{}".format(score,"A") if __name__=='__main__': lettergrade(1000)
def negative(arr): newarr=[] for i in range (len(arr)): if arr[i]>0: newarr.append(arr[i]*-1) else: newarr.append(arr[i]) return newarr if __name__ == '__main__': print(negative([2,5,-9,19]))
def MakeItBig(arr): for i in range (len(arr)): if arr[i]>0: arr[i]="big" return arr if __name__ == '__main__': print(MakeItBig([-1,3,5,-5]))
def lowhigh(arr): low=arr[0] high=arr[0] for i in range (len(arr)): if arr[i]>high: high=arr[i] elif arr[i]<low: low=arr[i] print low return high if __name__ == '__main__': print(lowhigh([40]))
def max_of_array(arr): max=arr[0] for i in range (len(arr)): if arr[i]>max: max=arr[i] print max if __name__=='__main__': max_of_array([1,2,3,4,5])
def previouslengths(arr): for i in range (len(arr)): if type(arr[i])is str: arr[i]=len(arr[i]) print arr[i] return arr if __name__ == '__main__': print(previouslengths(["vineel","sindhu",9]))
import unittest from decision_tree.question import Question class QuestionTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.training_data = [ ['Green', 3, 'Apple'], ['Yellow', 3, 'Apple'], ['Red', 1, 'Grape'], ['Red', 1, 'Grape'], ['Yellow', 3, 'Lemon'] ] def test_question_constructor(self): question = Question(0, 'Green') self.assertEqual(question.column_index, 0) self.assertEqual(question.value, 'Green') def test_match(self): question = Question(0, 'Green') example = self.training_data[0] self.assertTrue(question.match(example)) def test_does_not_match(self): question = Question(0, 'Red') example = self.training_data[0] self.assertFalse(question.match(example)) def test_match_with_numeric_value(self): question = Question(1, 3) example = self.training_data[0] self.assertTrue(question.match(example)) def test_does_not_match_with_numeric_value(self): question = Question(1, 4) example = self.training_data[0] self.assertFalse(question.match(example)) def test_repr(self): expected_repr = 'Is feature 0 == Red?' question = Question(0, 'Red') self.assertEqual(expected_repr, repr(question)) def test_repr_with_numeric_value(self): expected_repr = 'Is feature 1 >= 2?' question = Question(1, 2) self.assertEqual(expected_repr, repr(question)) if __name__ == '__main__': unittest.main()
def checkio(*args): count = 0 top = 0 bottom = 0 for i in args: i = float(i) if count == 0: count += 1 top = i bottom = i else: if i > top: top = i elif i < bottom: bottom = i return top - bottom
def checkio(number): number = str(number) bignum = 1 for i in number: if i == "0": continue else: bignum *= int(i) return bignum
def checkio(text): alphabet = create_dict(text) print(alphabet) highest = [] q = 0 for k, v in alphabet.items(): if v > q: q = v highest = [] highest.append(k) elif v == q: highest.append(k) highest.sort() print(highest[0]) return highest[0] def create_dict(text): alphabetic = {} for i in text: i = i.lower() if "": continue elif i.isalpha() and i not in alphabetic: alphabetic[i] = 1 elif i.isalpha() and i in alphabetic: alphabetic[i] += 1 return alphabetic if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio("Hello World!") == "l", "Hello test" assert checkio("How do you do?") == "o", "O is most wanted" assert checkio("One") == "e", "All letter only once." assert checkio("Oops!") == "o", "Don't forget about lower case." assert checkio("AAaooo!!!!") == "a", "Only letters." assert checkio("abe") == "a", "The First." print("Start the long test") assert checkio("a" * 9000 + "b" * 1000) == "a", "Long." print("The local tests are done.")
def i_love_python(): """ Let's explain why do we love Python. """ print('Throw your hands in the air.......') print('B/c Python is the bommmmbb') print('I can read and write w/o a Rosetta Stone') print('It helps me think and get sh** done.') print('3 months in and having too much fun to be done.') print('So join the crowd and get with python.') print('thats why: ') return "I love Python!"
def min(*args, **kwargs): key = kwargs.get("key", None) mymin = 'None' if len(args) > 1: for i in args: if mymin == 'None': mymin = i elif key: if key(i) < key(mymin): mymin = i else: if i < mymin: mymin = i return mymin else: for i in args: for x in i: if mymin == 'None': mymin = x elif key: if key(x) < key(mymin): mymin = x else: if x < mymin: mymin = x return mymin def max(*args, **kwargs): key = kwargs.get("key", None) mymax = 'None' if len(args) > 1: for i in args: if mymax == 'None': mymax = i elif key: if key(i) > key(mymax): mymax = i else: if i > mymax: mymax = i return mymax else: for i in args: for x in i: if mymax == 'None': mymax = x elif key: if key(x) > key(mymax): mymax = x else: if x > mymax: mymax = x return mymax if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert max(3, 2) == 3, "Simple case max" assert min(3, 2) == 2, "Simple case min" assert max([1, 2, 0, 3, 4]) == 4, "From a list" assert min("hello") == "e", "From string" assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items" assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key"
#!/usr/bin/env python3 ## ## subprograms ## # recursive predicate for checking for sequential increase # is there a more obvious arithmetic test? yes ... see two.f90 def is_increasing ( string_of_digits ): if len( string_of_digits ) == 1: return True i = 0 for a in string_of_digits: i += 1 for b in string_of_digits[i:]: if int(a) > int(b): return False else: return is_increasing( string_of_digits[1:] ) # recursive predicate for the "repeated" rule # repeated_digits_found is an array of each digit's repeat count def has_repeats ( string_of_digits, repeated_digits_found ): if len( string_of_digits ) == 1: # base case if any( [ x == 1 for x in repeated_digits_found ] ): return True # at least one single-repeat else: return False else: a, b = [ d[0] for d in [ string_of_digits[:-1], string_of_digits[1:] ] ] if int( a ) == int( b ): j = int( a ) # use its value for indexing repeated_digits_found[j] += 1 # recur with remainder of string return has_repeats( string_of_digits[1:], repeated_digits_found ) #return False # should never get here def rules ( lower_bound, upper_bound ): list_of_possibilities = [] for i in range( lower_bound, upper_bound ): candidate_digits = str( i ) if not is_increasing( candidate_digits ): continue if not has_repeats( candidate_digits, [0]*10 ): continue list_of_possibilities.append( i ) return list_of_possibilities ## ## main program ## with open("puzzle.txt") as fo: puzzle = fo.readline().strip() print( "\n read %d characters from input file\n" % ( len(puzzle) ) ) lower_bound, upper_bound = map( int, puzzle.split('-') ) possibilities = rules( lower_bound, upper_bound ) #print( possibilities ) print( "\n number of possible passwords: %d\n\n" % len( possibilities ) )
import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import train_test_split from sklearn import preprocessing df = pd.read_csv("profiles.csv") df=df.dropna(axis=0, subset=['height','education']) #print df.education.value_counts() def education_level(ed): if ed =='graduated from college/university': return 2. elif ed=='graduated from masters program': return 3. elif ed== 'working on college/university': return 1.5 elif ed== 'working on masters program': return 2. elif ed== 'graduated from two-year college': return 2. elif ed== 'graduated from high school': return 1. elif ed== 'graduated from ph.d program': return 4. elif ed== 'graduated from law school': return 2.5 elif ed== 'working on two-year college': return 1.5 elif ed== 'dropped out of college/university': return 1.5 elif ed== 'working on ph.d program': return 3. elif ed== 'college/university': return 2. elif ed== 'graduated from space camp': return 1. elif ed== 'dropped out of space camp': return 1. elif ed== 'graduated from med school': return 2.5 elif ed== 'working on space camp': return 1. elif ed== 'working on law school': return 1.5 elif ed== 'two-year college': return 2. elif ed== 'working on med school': return 1.5 elif ed== 'dropped out of two-year college': return 1.5 elif ed== 'dropped out of masters program': return 2. elif ed== 'masters program': return 3. elif ed== 'dropped out of ph.d program': return 3. elif ed== 'dropped out of high school': return 0. elif ed== 'high school': return 1. elif ed== 'working on high school': return 1. elif ed== 'space camp': return 1. elif ed== 'ph.d program': return 4. elif ed== 'law school': return 2.5 elif ed== 'dropped out of law school': return 1.5 elif ed== 'dropped out of med school': return 1.5 elif ed== 'med school': return 1.5 elif ed== 'NaN': return 1. df["education_level"]=df.education.map(education_level) #Question: Do short men need to put in more effort on dating sites? #If that's the case, there should be a (negative) correlation with amount of detail given in essay answers with height among males. #Create height categories for very short, short, 'normal', tall, and very tall #<5, 5 - 5'8, ,5'8-6.,6'1-6'4,>6'4 def Height_Rank(h): if h<=60: return 0 elif h<=68: return 1 elif h<=72: return 2 elif h<=76: return 3 else: return 4 df["height_code"]=df.height.map(Height_Rank) #print df.height.head() #print df.height_code.head() # We have created (somewhat arbitrary) height rankings #Now we can use essay text length as a measure of 'effort' essay_cols = ["essay0","essay1","essay2","essay3","essay4","essay5","essay6","essay7","essay8","essay9"] # Removing the NaNs all_essays = df[essay_cols].replace(np.nan, '', regex=True) # Combining the essays all_essays = all_essays[essay_cols].apply(lambda x: ' '.join(x), axis=1) df["essay_len"] = all_essays.apply(lambda x: len(x)) #print df.sex.head() #I'm interested in males specifically, so let's do this: df_men=df.loc[df['sex'] == 'm'] plt.figure(1) plt.scatter(df_men.height,df_men.essay_len) plt.xlabel("Height (inches)") plt.ylabel("Combined Essay Length") #plt.show() #This does not suggest a linear relationship, but we can try all the same. min_max_scaler = preprocessing.MinMaxScaler() X_temp=df_men[["height","education_level"]].values X_scaled=min_max_scaler.fit_transform(X_temp) Y=np.array(df_men.essay_len) X=pd.DataFrame(X_scaled, columns=["height","education level"]) X_train, X_test, Y_train, Y_test = train_test_split(X,Y,random_state=42) model1=LinearRegression() model1.fit(X_train,Y_train) Y_predict=model1.predict(X_test) score=model1.score(X_test,Y_test) print 'linear score', score #now let's try a nearest neighbour regressor #for n in range(1,100): # model2=KNeighborsRegressor(n_neighbors=n) # model2.fit(X_train,Y_train) # print n, model2.score(X_test,Y_test) model2=KNeighborsRegressor(n_neighbors=37) model2.fit(X_train,Y_train) predict_2=model2.predict(X_test) plt.figure(2) plt.scatter(X_test["height"],Y_test,alpha=0.5) plt.scatter(X_test["height"],Y_predict) plt.scatter(X_test["height"],predict_2) plt.legend(['Test Samples', 'Linear Predictions', 'NN Predictions']) plt.xlabel("Height (normalised)") plt.ylabel("Combined Essay Length") #One issue here is that the line is biased towards the region with the most samples #should create normalised frequency histogram #make new column:verbose, 1 or 0 (more than average, less than average) avg_word=Y.mean() def is_verbose(x): if x>avg_word: return 1 else: return 0 df_men["verbose"]=df_men.essay_len.map(is_verbose) print pd.crosstab(df_men.height_code, df_men.verbose) H=[0,1,2,3,4] #numbers from crosstab No_verbose=np.array([46.,5594.,11569.,4605.,347.]) Yes_verbose=np.array([17.,3350.,7254.,2833.,214.]) plt.figure(3) plt.scatter(H,Yes_verbose/(Yes_verbose+No_verbose)) plt.xticks(H,['VS','S','A','T','VT']) plt.xlabel('Height Category') plt.ylabel('Relative Frequency of Long Essays') #plt.figure(4) #plt.hist(df.education_level.dropna(), bins=8) #plt.xlabel('Education Level') #plt.ylabel('Frequency') # #plt.figure(5) #plt.hist(df.age.dropna(), bins=20) #plt.xlabel('Age') #plt.ylabel('Frequency') # #plt.figure(6) #plt.hist(df.height.dropna(), bins=20) #plt.xlabel('Height (inches)') #plt.ylabel('Frequency') #I'm pretty convinced the result here is a negative one. Let's try one more regression problem #Q2: Can we predict income based on combined essay length + education level? plt.show()
#largest among 3 numbers #getvalue from user a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) c = float(input("Enter third number: ")) print(max(a,b,c))
import random rn = random.randint(1,10) myn = 0 while myn != rn: myn = input("Guess a number between 1 and 10: ") if type(myn) is int: if myn < rn: print('Too Low :(') if myn > rn: print('Too High :(') else: print("Please type in numbers only") print("You won, the number was {} ".format(rn))
A = 2 B = 4 C = 3 print(A) print(int(B)) #Int foran float, viser dem som Int, men omdifinerer dem ikke print(C) print((str(B)+"\n")*10) #\n i et string felt, skifter linie *10, så sker det ti gange message = ("Hej med jeg") #Det er muligt at ændre en variabel til noget andet undervejs i programmet print(message) message = ("Hej med dig også") print(message) print('Det her er "Nice"') #Både " og * kan bruges til at definere en string, det gør det muligt at bruge dem i en sætning name = "allan jensen" #Strings kan behandles på forskellig vis, .title gør stort forbogstav på navn print(name.title()) print(name.upper()) print(name.lower()) first_name = "allan" #To strings ligges sammen last_name = "jensen" full_name = first_name + " " + last_name message = ("Hey, " + full_name.title() + "!!") print(message) print("\nMin adresse er:\n\tFælledvej 72\n\t\t8700 Horsens\n\t\t\tDanmark\n") whitespace = " Allan " print(whitespace) print(whitespace.rstrip().lstrip()) #For at fjerne overflødigt "whitespace" Q = 0.2 + 0.1 print(Q) alder = 23 print("\nIillykke med de " +str(alder) + " år!")
from typing import List def kvadrat(x: float) -> str: return str(x*x) print('Resultatet er: ' + kvadrat(9)) print('----------------------------------------------------------') listen = [1, 2, 3, 4] def minsum(liste: List[int]) -> str: return str(sum(liste)) print(minsum(listen)) print('-----------------------------------------------------------') listen2 = ['Christian', 'Anel', 'Allan'] """print(minsum(listen2))"""
Norden = ['danmark', 'sverige', 'norge', 'finland', 'grønland','færøerne', 'danmark'] if 'danmark' in Norden: print('Ja') else: print('Nej') if 'tyskland' in Norden: print('Ja') else: print('Nej') print('----------------------------------------------------------------') Fundet = False print('Vil ud søge hele listen? J/N') Alle = input(': ').lower() while not Fundet: print('Hvilket land vil du søge efter i listen?') Land = input(': ').lower() for Nord in Norden: if Land in Nord: if not Fundet: print('Ja i:') print('\t' + Nord.title()) Fundet = True if Alle == 'n': break if not Fundet: print('Nej, desværre')
# Opgave 7-5 side 121 i bogen Entre = True Total = 0 Igen = False print('Velkommen til MegaScope!') while Entre: Flere = '' Alder = int(input('Hvor gammel er du? ')) if Alder < 3: print('Du har gratis entre!') elif 3 <= Alder <= 12: print('Entre koster 100kr') Total += 100 elif Alder > 12: print('Entre koster 120kr') Total += 120 Igen = True while Igen: Flere = input('Er I flere som skal i bio? (j/n)') if Flere == 'n': Entre = False break elif Flere == 'j': Igen = False else: print('Indtastning ikke forstået') print('Det bliver i alt ' + str(Total) + ('kr.'))
# coding: utf-8 import sys from abc import ABCMeta, abstractmethod import random class Hand(object): HANDVALUE_GOO = 0 HANDVALUE_CHO = 1 HANDVALUE_PAA = 2 class __Hand(object): name = ["グー", "チョキ", "パー"] def __init__(self, hand_value): self.__hand_value = hand_value def is_stronger_than(self, hand): return self.__fight(hand) == 1 def is_weaker_than(self, hand): return self.__fight(hand) == -1 def __fight(self, hand): if self == hand: return 0 elif (self.__hand_value + 1) % 3 == hand.__hand_value: return 1 else: return -1 def __str__(self): return self.name[self.__hand_value] hand = [ __Hand(HANDVALUE_GOO), __Hand(HANDVALUE_CHO), __Hand(HANDVALUE_PAA), ] @classmethod def get_hand(cls, hand_value): return cls.hand[hand_value] class Strategy(object, metaclass=ABCMeta): @abstractmethod def next_hand(self): pass @abstractmethod def study(self, win): pass class WinningStrategy(Strategy): def __init__(self, seed): random.seed(seed) self.__won = False self.__prev_hand = None def next_hand(self): if not self.__won: self.__prev_hand = Hand.get_hand(random.randint(0, 2)) return self.__prev_hand def study(self, win): self.__won = win class ProbStrategy(Strategy): def __init__(self, seed): random.seed(seed) self.__prev_hand_value = 0 self.__current_hand_value = 0 self.__history = [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] def next_hand(self): bet = random.randint(0, self.__get_sum(self.__current_hand_value)) hand_value = 0 if (bet < self.__history[self.__current_hand_value][0]): hand_value = 0 elif (bet < self.__history[self.__current_hand_value][0] + self.__history[self.__current_hand_value][1]): hand_value = 1 else: hand_value = 2 self.__prev_hand_value = self.__current_hand_value self.__current_hand_value = hand_value return Hand.get_hand(hand_value) def __get_sum(self, hv): sum = 0 for i in range(3): sum += self.__history[hv][i] return sum def study(self, win): if win: self.__history[self.__prev_hand_value][self.__current_hand_value] += 1 else: self.__history[self.__prev_hand_value][(self.__current_hand_value + 1) % 3] += 1 self.__history[self.__prev_hand_value][(self.__current_hand_value + 2) % 3] += 1 class Player(object): def __init__(self, name, strategy): self.__name = name self.__strategy = strategy self.__win_count = 0 self.__lose_count = 0 self.__game_count = 0 def next_hand(self): return self.__strategy.next_hand() def win(self): self.__strategy.study(True) self.__win_count += 1 self.__game_count += 1 def lose(self): self.__strategy.study(False) self.__lose_count += 1 self.__game_count += 1 def even(self): self.__game_count += 1 def __str__(self): return "[{}:{} games, {} win, {} lose]".format( self.__name, self.__game_count, self.__win_count, self.__lose_count ) if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python strategy.py randomseed1 randomseed2") print("Example: python strategy.py 314 15") sys.exit() seed1 = int(sys.argv[1]) seed2 = int(sys.argv[2]) player1 = Player("Taro", WinningStrategy(seed1)) player2 = Player("Hana", ProbStrategy(seed2)) for i in range(10000): next_hand1 = player1.next_hand() next_hand2 = player2.next_hand() if next_hand1.is_stronger_than(next_hand2): print("Winner:", player1, sep="") player1.win() player2.lose() elif next_hand2.is_stronger_than(next_hand1): print("Winner:", player2, sep="") player1.lose() player2.win() else: print("Even...") player1.even() player2.even() print("Total result:") print(player1) print(player2)
#Write a Python program to enter decimal number and calculate and display binary eqyivalent of this number def convertToBinary(n): if n > 1: convertToBinary(n//2) print(n % 2,end = '') dec = int(input("Enter number : ")) convertToBinary(dec) print()
#Write a python program to read the email id'email of n users and create a list of user id's email = [] user_id = [] n = int(input("Enter how many strings you want to add : ")) i = 0 for i in range(0,n): t = "Enter string no."+str(i+1)+" : " email.append(str(input(t))) for i in range(0,len(email)): s = email[i] for j in range(0,len(s)): if "@" == s[j]: user_id.append(s[:j]) print("List of user id : ",user_id)
#!/usr/bin/env python3 # This is basic HTTP echo server. It is mostly usable for inspecting # incoming requests. Loosely based on this: # https://gist.github.com/huyng/814831 # # curl -s -H "X-Hello: World!" IP:PORT # curl -s -H "X-Hello: World!" -d @some/file IP:PORT # import http.server import logging import argparse default_port = 8080 default_interface = '' class EchoHandler(http.server.BaseHTTPRequestHandler): # Str8 from the Python logging tutorial. logger = logging.getLogger('EchoHandler') logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) logger.addHandler(console_handler) def command_handler(self): self.logger.info("Handling {}".format(self.command)) self.logger.info("request path = '{}'".format(self.path)) self.logger.info("headers = {}".format(self.headers)) if self.command in {'POST', 'PUT'}: content_length = int(self.headers['Content-Length']) self.logger.info("POST data = {}".format(self.rfile.read(content_length))) self.logger.info("{} done.".format(self.command)) self.send_response(200) self.send_header("Set-Cookie", "hello=simplehttp") self.end_headers() do_GET = command_handler do_POST = command_handler do_DELETE = command_handler do_PUT = command_handler if __name__ == "__main__": parser = argparse.ArgumentParser(description='Simple HTTP echo server.') parser.add_argument('-p', dest='port', default=default_port, type=int, help='Port number') parser.add_argument('-i', dest='interface', default=default_interface, help='Interface to bind to (default: {})'.format(default_interface)) args = parser.parse_args() server = http.server.HTTPServer((args.interface, args.port), EchoHandler) server.serve_forever()
richest = "none" maxBal = 0 for count in range(1,3): name = input ("Name: ") balance = float (input ("Enter balance: ")) if balance > maxBal : richest = name maxBal = balance print("Richest guy: {0:s} has balance of ${1: ,.2f}" . format(richest, maxBal))
#!/usr/bin/env python2 # # A script to generate random sat formulas inspired from the paper # Achlioptas, Jia and Moore: Hiding Satisfying Assignments: Two are Better than One, # # TODO: sometimes the maximum number of clauses to be generated is lower than # the number of clauses requested and thus the program never finishes import sys import optparse import random parser = optparse.OptionParser('usage: %prog [options] variables') parser.add_option('-r', '--ratio', dest='ratio', type='float', default=5., help='ratio between the number of clauses and the number of variables', metavar='R') parser.add_option('-k', '--literals', dest='literals', type='int', default=5, help='literals per clause', metavar='K') parser.add_option('-s', '--seed', dest='seed', type='int', default=None, help='seed for the random number generator', metavar='SEED') try: options, args = parser.parse_args() variables = int(args[0]) clauses = int(variables * options.ratio) literals = options.literals random.seed(options.seed) except ValueError: parser.print_usage() exit(1) sequence = range(variables) while True: # generates a random assignment assignment = [random.choice([-1, +1]) for v in xrange(variables)] formula = set() while len(formula) < clauses: found = False while not found: # selects some random variables clause = random.sample(sequence, literals) # and randomly creates a clause good = [False, False] for l in xrange(literals): flip = random.choice([-1, +1]) good[0] = good[0] or (+ assignment[clause[l]] * flip) > 0 good[1] = good[1] or (- assignment[clause[l]] * flip) > 0 clause[l] = (clause[l] + 1) * flip # clause must satisfy both assignment and complented assignment found = good[0] and (literals == 2 or good[1]) clause.sort() clause = tuple(clause) if clause not in formula: formula.add(clause) _ = set() for clause in formula: _.update(clause) if len(_) == 2 * variables: break print 'c', variables, 'variables,', clauses, 'clauses,', literals, 'literals per clause' print 'c', for v in xrange(variables): print (v + 1) * assignment[v], print print 'p', 'cnf', variables, clauses for clause in formula: for literal in clause: print literal, print 0
# mostrar los multiplos de 3 del 0 al 800 i=0 suma=0 while(i>800): suma =i i =3 #fin_while print("multiplos de 3 son:", multiplo)
import pandas as pd import subprocess, os def df_to_hdfs(df,path,index=False,sep='|',header=False,*args,**kwargs): """ Function to write a pandas dataframe to a specified location in HDFS. If the file already exists, it will be overwritten. """ #delete file if already exists on hdfs os.system("hadoop fs -rm -f {hdfs_path}".format(hdfs_path=path)) #set up hadoop put streaming command put = ['hadoop','fs','-put','-',path] #set up subprocess p = subprocess.Popen(put, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) #stream dataframe to hdfs df.to_csv(p.stdin, index=index, sep=sep, header=header,*args,**kwargs) #close subprocess p.stdin.close()
# -*- coding: utf-8 -*- """Helper functions to load and save CSV data. This contains a helper function for loading and saving CSV files. """ import csv def load_csv(csvpath): """Reads the CSV file from path provided. Args: csvpath (Path): The csv file path. Returns: A list of lists that contains the rows of data from the CSV file. """ with open(csvpath, "r") as csvfile: data = [] csvreader = csv.reader(csvfile, delimiter=",") # Skip the CSV Header next(csvreader) # Read the CSV data for row in csvreader: data.append(row) return data def save_csv(csv_data,csv_path): """Saves the CSV file to path provided. Args: csv_path (Path): The csv file path. csv_data : Data to be saved to csv file """ with open(csv_path,'w',newline='') as f: csvwriter = csv.writer(f) # Write Qualifying Data for data in csv_data: csvwriter.writerow(data)
""" Day 2 语言元素 """ import math def Fahrenheit_to_Celsius(): f = float(input("请输入华氏温度:")) c = (f - 32) / 1.8 print('%.1f华氏度 = %.1f摄氏度' % (f, c)) def cycle(): radius = float(input('请输入圆的半径:')) perimeter = 2 * math.pi * radius area = math.pi * radius * radius print('周长:%.2f' % perimeter) print('面积:%.2f' % area) def leap_year(): year = int(input('请输入年份:')) is_leap = (year % 4 == 0 and yaer % 100 != 0 or year % 400 == 0) print(is_leap) if __name__ == '__main__': Fahrenheit_to_Celsius() cycle() leap_year()
""" Day 11 读取文件 """ def reading_file(): try: with open('./res/ball.png', 'rb') as file_in: data = file_in.read() print(type(data)) with open('./res/ball-copy.png', 'wb') as file_out: file_out.write(data) except FileNotFoundError as e: print('无法打开指定文件!') except IOError as e: print('无法读写指定文件!') print('执行成功') if __name__ == '__main__': reading_file()
# Створення прикладних програм на мові Python # Лабораторна робота 5 # Chepil Dmytro, 15 print ('Створення прикладних програм на мові Python, Лабораторна 5') print ('Chepil Dmytro, 15') N = int(input ('Введіть число: ')) proste = 0 while proste < N: proste2 = proste + 6 x = 0 y = 0 for j in range(1,proste+1): if proste % j == 0: x += j if x-1 == proste: for j in range(1,proste2+1): if proste2 % j == 0: y += j if y-1 == proste2: print('(',proste, proste2, end = ' ) ') proste += 1
class Person(): def __init__(self): self.name = None self.sname = None self.byear = None def input(self): self.name = input('Name:') self.sname = input('Surname:') self.byear = input('B.Year:') def __str__(self): return '{},{}'.format(self.name, self.sname, self.byear) class PersonFull(Person): def __init__(self): super(Person,self).__init__() self.phone = None def input(self): Person.input(self) self.phone = input('Phone number:') def __str__(self): return 'Name: {}, Surname {}, B.Year: {}, Phone number: {}'.format(self.name, self.sname, self.byear, self.phone) s=PersonFull() s.input() print(s)
count=0 while count<=10: count+=1 if count % 2 == 0: continue print(count)
def ProductS_Quant(): while True: NumbApl = input("\nHow many apples would you like to buy? \n> ") NumbOrng = input("\nHow many oranges would you like to buy? \n> ") if NumbApl.isdigit() and NumbOrng.isdigit() == True: InitApl = int(NumbApl) InitOrng = int(NumbOrng) return InitApl, InitOrng elif NumbApl.isalpha() or NumbOrng.isalpha() == True: print("\nInputs must be both numerical values.") elif NumbApl.isspace() or NumbOrng.isspace() == True: print("\nPlease fill all the blanks.") else: if "," in NumbApl or NumbOrng: ModNumApl, ModNumOrng = CommaReader(NumbApl, NumbOrng) if ModNumApl.isdigit() and ModNumOrng.isdigit() == True: FnlApl = int(ModNumApl) FnlOrng = int(ModNumOrng) return FnlApl, FnlOrng else: if "." in ModNumApl or ModNumOrng: ValueChckApl = ModNumApl.split(".") ValueChckOrng = ModNumOrng.split(".") if (len(ValueChckApl)) + (len(ValueChckOrng)) == 4: if (int(ValueChckApl[1]) > 0) and (int(ValueChckOrng[1]) > 0): print("\nYou can't purchase a fraction of our products.\nPlease enter whole quantity values.") elif (int(ValueChckApl[1]) == 0) and (int(ValueChckOrng[1]) == 0): EligiApl= int(ValueChckApl[0]) EligiOrng = int(ValueChckOrng[0]) return EligiApl, EligiOrng elif (int(ValueChckApl[1]) == 0) and (int(ValueChckOrng[1]) > 0): print("\nYou can't purchase a fraction of an orange.\nPlease enter whole quantity values.") elif (int(ValueChckApl[1]) > 0) and (int(ValueChckOrng[1]) == 0): print("\nYou can't purchase a fraction of an apple.\nPlease enter whole quantity values.") elif (len(ValueChckApl)) + (len(ValueChckOrng)) == 3: if (len(ValueChckApl)) == 2: if int(ValueChckApl[1]) > 0: print("\nYou can't purchase a fraction of an apple.\nPlease enter whole quantity values.") elif int(ValueChckApl[1]) == 0: EligiApl= int(ValueChckApl[0]) EligiOrng = int(ValueChckOrng[0]) return EligiApl, EligiOrng elif (len(ValueChckApl)) == 1: if int(ValueChckOrng[1]) > 0: print("\nYou can't purchase a fraction of an orange.\nPlease enter whole quantity values.") elif int(ValueChckOrng[1]) == 0: EligiApl= int(ValueChckApl[0]) EligiOrng = int(ValueChckOrng[0]) return EligiApl, EligiOrng def CommaReader(AplInp, OrngInp): if "," in AplInp and OrngInp: Price_01 = AplInp.replace(",","") Price_02 = OrngInp.replace(",","") return Price_01, Price_02 elif "," in AplInp: AplprcOnly = AplInp.replace(",","") return AplprcOnly, OrngInp elif "," in OrngInp: OrngprcOnly = OrngInp.replace(",","") return AplInp, OrngprcOnly else: return AplInp, OrngInp def total_(NumApl, NumOrng): ttlprc_apl = NumApl*20 ttlprc_orng = NumOrng*25 summation = ttlprc_apl + ttlprc_orng return summation apl_quant, orng_quant = ProductS_Quant() grnd_total = total_(apl_quant, orng_quant) print(f"\nThe total amount is {grnd_total:,} Php.")
from tkinter import * from functools import partial # clculator # https://www.youtube.com/watch?v=_1tTS638xUQ root = Tk() root.title('First Program') frame = Frame(root) frame.pack(side=TOP) num_input = Entry(frame,border=10,width=25,insertwidth=1,font=30) num_input.pack(side=TOP) def Calculator(num): if num == 'CLEAR': num_input.delete(0,END) else: string = num_input.get() if num != '=': num_input.insert(len(string),num) if num == '=': num1, index, num2, operator = '', 0, '', '' for i in range(len(string)): if string[i].isdigit(): num1 += string[i] else: operator = string[i] index = i break num2 = string[index+1:] if operator == '+': num_input.delete(0,END) num_input.insert(0,int(num1)+int(num2)) elif operator == '-': num_input.delete(0,END) num_input.insert(0,int(num1)-int(num2)) elif operator == '*': num_input.delete(0,END) num_input.insert(0,int(num1)*int(num2)) elif operator == '%': num_input.delete(0,END) num_input.insert(0,int(num1)%int(num2)) else: num_input.delete(0,END) num_input.insert(0,int(num1)//int(num2)) button = Button(frame,text='0',padx=30,pady=10,bd=6,command=partial(Calculator,0)) button.pack(side=LEFT) button = Button(frame,text='1',padx=30,pady=10,bd=6,command=partial(Calculator,1)) button.pack(side=LEFT) button = Button(frame,text='2',padx=30,pady=10,bd=6,command=partial(Calculator,2)) button.pack(side=LEFT) frame1 = Frame(root,bg='red') frame1.pack() button1 = Button(frame1,text='3',padx=30,pady=10,bd=6,command=partial(Calculator,3)) button1.pack(side=LEFT) button1 = Button(frame1,text='4',padx=30,pady=10,bd=6,command=partial(Calculator,4)) button1.pack(side=LEFT) button1 = Button(frame1,text='5',padx=30,pady=10,bd=6,command=partial(Calculator,5)) button1.pack(side=LEFT) frame2 = Frame(root) frame2.pack() button2 = Button(frame2,text='6',padx=30,pady=10,bd=6,command=partial(Calculator,6)) button2.pack(side=LEFT) button2 = Button(frame2,text='7',padx=30,pady=10,bd=6,command=partial(Calculator,7)) button2.pack(side=LEFT) button2 = Button(frame2,text='8',padx=30,pady=10,bd=6,command=partial(Calculator,8)) button2.pack(side=LEFT) frame3 = Frame(root) frame3.pack() button3 = Button(frame3,text='9',padx=30,pady=10,bd=6,command=partial(Calculator,9)) button3.pack(side=LEFT) addition_button = Button(frame3,text='+',padx=30,pady=10,bd=6,command=partial(Calculator,'+')) addition_button.pack(side=LEFT) subs_button = Button(frame3,text='-',padx=30,pady=10,bd=6,command=partial(Calculator,'-')) subs_button.pack(side=LEFT) frame4 = Frame(root) frame4.pack() multi_button = Button(frame4,text='*',padx=30,pady=10,bd=6,command=partial(Calculator,'*')) multi_button.pack(side=LEFT) divi_button = Button(frame4,text='/',padx=30,pady=10,bd=6,command=partial(Calculator,'/')) divi_button.pack(side=LEFT) perc_button = Button(frame4,text='%',padx=30,pady=10,bd=6,command=partial(Calculator,'%')) perc_button.pack(side=LEFT) frame5 = Frame(root) frame5.pack() resu_button = Button(frame5,text='=',width=10,padx=30,pady=10,bd=6,command=partial(Calculator,'=')) resu_button.pack(side=LEFT) clear = Button(frame5,text='CLEAR',padx=30,pady=10,bd=6,command=partial(Calculator,'CLEAR')) clear.pack(side=LEFT) root.mainloop()
num = [0,1,2,0,13,44,0,56] print(num) index_0 = [] count = 0 for i in range(len(num)): if num[i] != 0: index_0.append(num[i]) else: count += 1 for j in range(count): index_0.append(0) print(index_0)
import random play = [] deal = [] for i in range(0,2): player = random.randint(1,10) dealer = random.randint(1,10) play.append(player) deal.append(dealer) print('You drew {} and {}.'.format(play[0], play[1])) print('Your Total is ',(play[0]+play[1])) print('The Dealer has',deal[0],'and',deal[1]) print('Dealer\'s total is',(deal[0]+deal[1])) if (play[0]+play[1]) > (deal[0]+deal[1]): print('Player WIN') else: print('Dealer WIN')
tup = tuple(range(10)) #print(tup) l = list(tup) #print(l) l2 = l[::-1] #print(tuple(l2)) # replace last value of tuples in a list(my way) tulps = [] for i in range(5): tulps.append(tuple(range(1,5))) print(tulps) for j in range(len(tulps)): arr = list(tulps[j]) arr[-1] = 'gg' tulps[j] = tuple(arr) print(tulps) # replace last value of tuples in a list (simplst way to do it) l = [(10, 20, 40), (40, 50, 60), (70, 80, 90)] print([t[:-1] + (100,) for t in l])
# https://www.codewars.com/kata/decoded-string-by-the-numbers string = 'abc\\5defghi\\2jkl' ch_holder, spot1, spot2 = [], 0, 0 for i in range(0,len(string)): if string[i] == '\\': spot1 = i+2 spot2 = (i+2) + int(string[i+1]) ch_holder.append(string[spot1:spot2]) else: if i >= spot1 and i < spot2: continue else: if not(string[i].isdigit()): ch_holder.append(string[i]) print(ch_holder)
def addition(a,b): return a+b def subsraction(a,b): return a-b def division(a,b): return a/b def multiplication(a,b): return a*b while True: string = str(input('>')) if string[0] == '0':break else: if string[1] == '+': print(addition(int(string[0]),int(string[2]))) elif string[1] == '-': print(subsraction(int(string[0]),int(string[2]))) elif string[1] == '*': print(multiplication(int(string[0]),int(string[2]))) else: print(division(int(string[0]),int(string[2])))
num = 26 isNot = False for i in range(num): if i*i == num: isNot = True print(num,'is a square Number!') if isNot == False: print(num,'is Not a square Number!')
num = int(input()) if num % 2 != 0: print("Weird") if num % 2 == 0: if 2 <= num: if num <= 5: print("Not Weird!") if num % 2 == 0: if num >= 6: if num < 20: print("Weird!") else: print("Not Weird!") """ tab = [1,2,5,8,6,65,5,4,54,5,56,8,7,4,21,21,1,7,8,9,47,5,7,44,55,64,31,89,45,34,65,64,654] print(tab.__len__()) num = 0 for x in tab: num +=1 print("list lenght is :",num) """
string = 'fun time' ch = list(string) print(string) for i in range(0,len(ch)): ch[i] = chr(ord(ch[i])+1) print(''.join(ch))
import random arr = [] for i in range(15): arr.append(random.randint(4,23)) print(arr) #get the lowest number temp = 0 for j in range(len(arr)): if arr[0] > arr[j]: temp = arr[0] arr[0] = arr[j] arr[j] = temp print('lower number = ',arr[0]) #get the highst number for x in range(len(arr)): if arr[0] < arr[x]: temp = arr[0] arr[0] = arr[x] arr[x] = temp print('high number = ',arr[0])
print("Hello %s %s! You just delved" " into python " % (str(input("enter ur name :")) ,str(input("enter ur last name:")))) string = "this is a srting" string = string.split(" ") print("-".join(string)) #string = "-".join(string) #print(string) #another solution print(*input().split(" "), sep='-') #another solution line = "can you do me a favor" print("-".join(line.split(" ")))
x,y=map(int,input().split()) x1=list(map(int,input().split())) if y in x1: print("yes") else: print("no")
x123=list(input()) for i in range(0,len(x),2): c123=x[i] x123[i]=x123[i+1] x123[i+1]=c123 for i in x123: print(i,end="")
string=(input()) string2=string[0: :2] string3=string[1: :2] print(string2,string3,end=" ")
x=(int(input())) temp=x sos=0 while(x!=0): temp=x%10 sos+=temp*temp x=x//10 print(sos)
import os from Board import Board def start_mastermind(): temp_difficulty_select = 0 ant = " "; #setting up the game by selecting a difficulty while temp_difficulty_select != 1: if temp_difficulty_select == -1: print("That was not a valid number") print("Difficulty options:") print("Easy :0") print("Medium:1") print("Select a difficulty setting :") ant = input() try: if (int(ant) == 0) or (int(ant) == 1) : mastermind = Board(int(ant)) mastermind.generate() temp_difficulty_select = 1 else: temp_difficulty_select = -1 except Exception as e: temp_difficulty_select = -1 os.system('cls') #running the game game_won = mastermind.give_boardstare() while game_won == 0: print("Game Difficulty: " + str(mastermind.difficulty) + ", currently at row: "+ str(mastermind.give_current_row()+1)) print("| Game guesses: || Evaluations: |") print(" =01= =02= =03= =04= ==== ==== ==== ==== ") for row_count in range(8,-1,-1): temp_row = mastermind.give_row(row_count) temp_row_evaluation = mastermind.give_evaluation(row_count) print( "| " + str(temp_row[0]).zfill(2) + " | " + str(temp_row[1]).zfill(2) + " | " + str(temp_row[2]).zfill(2) + " | " + str(temp_row[3]).zfill(2) + " || " + str(temp_row_evaluation[0]).zfill(2) + " | " + str(temp_row_evaluation[1]).zfill(2) + " | " + str(temp_row_evaluation[2]).zfill(2) + " | " + str(temp_row_evaluation[3]).zfill(2) + " | ") print(" ==== ==== ==== ==== ==== ==== ==== ====") guess = [] print("guess 1:") try: guess.append(int(input())) except Exception as e: guess.append(0) print("guess 2:") try: guess.append(int(input())) except Exception as e: guess.append(0) print("guess 3:") try: guess.append(int(input())) except Exception as e: guess.append(0) print("guess 4:") try: guess.append(int(input())) except Exception as e: guess.append(0) mastermind.make_guess(guess) game_won = mastermind.give_boardstare() os.system('cls') print("Game Difficulty: " + str(mastermind.difficulty) + ", currently at row: "+ str(mastermind.give_current_row()+1)) print("| Game guesses: || Evaluations: |") print(" =01= =02= =03= =04= ==== ==== ==== ==== ") for row_count in range(8,-1,-1): temp_row = mastermind.give_row(row_count) temp_row_evaluation = mastermind.give_evaluation(row_count) print( "| " + str(temp_row[0]).zfill(2) + " | " + str(temp_row[1]).zfill(2) + " | " + str(temp_row[2]).zfill(2) + " | " + str(temp_row[3]).zfill(2) + " || " + str(temp_row_evaluation[0]).zfill(2) + " | " + str(temp_row_evaluation[1]).zfill(2) + " | " + str(temp_row_evaluation[2]).zfill(2) + " | " + str(temp_row_evaluation[3]).zfill(2) + " | ") print(" ==== ==== ==== ==== ==== ==== ==== ====") if mastermind.give_boardstare() == 1: print("Well done you won!") print("In " + str(mastermind.give_current_row()) + " guesses.") print("the correct answer was: " + str(mastermind.show_solution())) else: print("You lost :(") print("the correct answer was: " + str(mastermind.show_solution())) start_mastermind() print("I'm done!")
''' This program loads a list of the most common python libraries and allows the user to select a library, view its methods, select one and see the help documentation on it. It also allows the user to see the list of others that are installed and then to enter ones not in the pre-populated list. ''' # import the things import tkinter as tk from tkinter import ttk from tkinter import scrolledtext as tkst import pydoc import os import sys import re import importlib import io import time from pathlib import Path from contextlib import redirect_stdout # Class for our gui class MainMenu(tk.Tk): # define the main window/initializer def __init__(self, master=None): tk.Tk.__init__(self, master) # do some styling self.style = ttk.Style(self) self.style.theme_use('alt') # set the title and window size self.title('Method definition') self.geometry('800x425') # build out the lists self.list1 = self.librlist() self.list2 = [] # establish the input box self.inputbox() # make the button to display the libraries and place the thing self.displayall = ttk.Button(text = "For libraries see terminal window", command = self.get_help) self.displayall.grid(row = 0, column = 1, pady = (10,0)) # make the comboboxes self.drop_menu1 = self.drop_menu(self.list1, 'Libraries', 0) self.drop_menu1.bind("<<ComboboxSelected>>", self.get_methods) self.drop_menu2 = self.drop_menu(self.list2, 'Methods', 2) self.drop_menu2.bind("<<ComboboxSelected>>", self.get_choice) # get the text box self.textbox = self.gettext() # reads the file to populate def librlist(self): # This is the text we do not want banned = 'Please wait a moment while I gather a list of all available modules...\ Enter any module name to get more help. Or, type "modules spam" to search\ for modules whose name or summary contain the string "spam".' # see if the file exists there my_file = Path('test.txt') if my_file.is_file(): print("") # if not then make it else: file = open('test.txt', 'w+') sys.stdout = file help('modules') sys.stdout = sys.__stdout__ file.close() self.MainMenu() # open the file to read it file = open('test.txt') # make an empty list mod_list = [] # read the file line by line modules = file.readlines() # This is the pattern to match pattern = re.compile(r'^([a-zA-Z_]+)$') # for the things in the word line for module in modules: # split them up mod = module.split() # for each word see if it matches the pattern then if it is in banned. If it does and is not then put it in the list for i in mod: matches = pattern.findall(i) for match in matches: if match == i and match not in banned: mod_list.append(match) # it doesnt get 'os' so go ahead and add that ## mod_list.append('os') # sort the list mod_list.sort() # send it back return mod_list # function to display the modules in test.txt and write to the textbox def get_help(self): file = open('test.txt') data = file.read() # destroy it and remake it because destroy is fun and it makes it clean self.textbox.destroy() self.textbox = self.gettext() # insert the data now self.textbox.insert(1.0, data) # function to let the user put in libraries not in the list def inputbox(self): # the label self.inputboxlabel = ttk.Label(text = "Enter a library to search: ") self.inputboxlabel.grid(row = 4, column = 0) # The input box itself self.inputbox = ttk.Entry(self) self.inputbox.grid(row = 4, column = 1) # get the button to make the magic thing self.getinputbox() # function to update the library list def updatelist(self): # add the users input to a list, sort it and update the combobox input1 = self.inputbox.get() self.list1.append(input1) self.list1.sort() self.drop_menu1.configure(values = self.list1) # button to update the library list with the users input def getinputbox(self): self.inputbutton = ttk.Button(text = "Click to apply your module", command = self.updatelist) self.inputbutton.grid(row = 4, column = 2) # function to make the comboboxes def drop_menu(self, list1, var1, var2): self.comboExample = ttk.Combobox(self, values = list1, state = 'readonly', height = 10) self.comboExample.set(var1) self.comboExample.grid(row = 0, column = var2, pady = (10, 0)) return self.comboExample # make the text box with scrolling def gettext(self): # make the scrolled text box self.text = tkst.ScrolledText(self, wrap = tk.WORD, width = 85, height = 20, name = 'defs') self.text.grid(padx = 10, pady = 10, row = 2, columnspan = 3, sticky = tk.W + tk.E) self.text.insert('1.0', '') # send it back return self.text # function to populate the text box with the usrs selection def get_choice(self, event): # get the selection self.meth = self.drop_menu2.get() # if the 2 selections are not the default if self.libr != 'Libraries' and self.meth != 'Methods': # destroy and remake the box self.textbox.destroy() self.textbox = self.gettext() # Get the definitions definition = pydoc.render_doc(f'{self.libr}.{self.meth}', renderer = pydoc.plaintext) # add the definition to the text box self.textbox.insert('1.0', definition) # a function to attempt to load the methods of a library def get_methods(self, event): # make an empty list self.list2 = [] # get the selection of the drop menu self.libr = self.drop_menu1.get() # try to get the library try: # import whatever module the user selected imported_module = importlib.import_module(self.libr) # set the pattern. We included _ for the _doc_ and other useful things pattern = re.compile(r'[a-z_]') # the library dict is empty self.lib_dict = {} # set the key in the dictionary to be the value for the selection if it matches the pattern self.lib_dict[self.libr] = [function for function in dir(imported_module) if pattern.match(function)] # send the value to our methods box self.drop_menu2.configure(values = self.lib_dict[self.libr]) # if there is an error tell the user it is broken except ModuleNotFoundError: self.textbox.destroy() self.textbox = self.gettext() self.textbox.insert('1.0', "That one will not work. Try another.") # define our main function def main(): # set app to be our function app = MainMenu() # call app to make the window app.mainloop() main()
""" Helper Methods """ import numpy as np from statistics import variance, stdev, mean ## Plot Libraries import matplotlib.pyplot as plt import numpy as np from math import exp, sqrt def same(population): m = [] def med(population): """ population med """ m = [] for c in population: m.append(c.fitness()) return mean(m) def dev(population): """ Population standard deviation """ m = [] for c in population: m.append(c.fitness()) return stdev(m) def var(population): """ variance """ m = [] for c in population: m.append(c.fitness()) return variance(m) def plot(data, title): """ plot results from a ES algorithm """ plt.plot(data[0], (data[1]), label='Média da População') plt.plot(data[0], (data[2]), label='Desvio Padrão') plt.plot(data[0], (data[3]), label='Variância') plt.plot(data[0], data[4], label="Melhor Individuo") plt.xlabel('Número de Interações') plt.ylabel('Fitness') plt.title(title) plt.legend() plt.show() def plot2(data, title): """ plot results from a ES algorithm """ plt.plot(data[0], data[1], label='Média da População') plt.plot(data[0], data[2], label='Desvio Padrão') plt.plot(data[0], data[3], label='Variância') plt.plot(data[0], data[4], label="Melhor Individuo") plt.xlabel('Número de Interações') plt.ylabel('Fitness') plt.title(title) plt.legend() plt.show() def perturbation(dim, std): mu, sigma = 0, 1 pert = [0.0]*dim for idx, s in enumerate(std): pert[idx] = s*(np.random.normal(mu, sigma, 1))[0] return pert def update_step(std): mu, sigma = 0, 1 for idx, val in enumerate(std): p = exp(1/sqrt(30)*(np.random.normal(mu, sigma, 1))[0]) std[idx] = val*p
#定义一个函数 def get_name(first_name,last_name,middle_name=''): if middle_name: full_name=first_name.title()+middle_name+last_name else: full_name=first_name.title()+last_name return full_name user1=get_name('wang','qing','yong') print(user1) user2=get_name('bralan','jaery') print(user2) friend={} friend[user1]=user2 for key,value in friend.items(): print(key+"`s frind is "+value+"!") """ 结果: Wangyongqing Bralanjaery Wangyongqing`s frind is Bralanjaery! """ #定义给已有字典添加键值的函数 def get_name(users,first_name,last_name): users[first_name]=last_name a_users={} get_name(a_users,'a','tom') get_name(a_users,'b','lisa') get_name(a_users,'c','zreak') for key,value in a_users.items(): print("\nfirst_name:"+key.title()) print("last_name:"+value) print("\n"+str(a_users)) """ 结果: first_name:A last_name:tom first_name:B last_name:lisa first_name:C last_name:zreak {'a': 'tom', 'b': 'lisa', 'c': 'zreak'} """ #传递任意数量的实参 def make_pizza(size,*name): print("size:"+str(size)) for names in name: print(names.title()) make_pizza(12,'a') make_pizza(33,'a','b','c') """ 结果: size:12 A size:33 A B C """ #使用任意数量的关键字实参 def users(first_name,last_name,**userss): user={} user['first_name']=first_name.title() user['last_name']=last_name.title() for key,value in userss.items(): user[key]=value return user user1=users('a','tom',age=12) user2=users('b','jafk',age=14,area='beijing') print(user1) print(user2) """ 结果: {'first_name': 'A', 'last_name': 'Tom', 'age': 12} {'first_name': 'B', 'last_name': 'Jafk', 'age': 14, 'area': 'beijing'} """
b = int(input("Enter the number of inputs : ")) name = [] for x in range(b): n = str(input()) name.append(n) for o in name: print(o.capitalize())
""" Problem 001 - Multiples of 3 and 5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :description: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. :url: https://projecteuler.net/problem=1 :answer: 233168 :author: :updated: 2014-11-18 """ def sum_divisibles(limit): """ Sum the numbers below limit that are divisible by 3 or 5. >>> sum_divisibles(10) 23 """ res = [x for x in range(limit) if x % 3 == 0 or x % 5 == 0] return sum(res) def sum_divisibles_lambda(limit): """ Sum the numbers below limit that are divisible by 3 or 5. >>> sum_divisibles_lambda(10) 23 """ f = lambda x: x % 3 == 0 or x % 5 == 0 ls = [x for x in range(limit) if f(x)] return sum(ls) if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python # coding: utf-8 # In[71]: from splinter import Browser from bs4 import BeautifulSoup from selenium import webdriver import pandas as pd import time # In[4]: def init_browser(): executable_path = {'executable_path': 'chromedriver.exe'} return Browser("chrome", **executable_path, headless=False) # In[90]: def scrape(): #create empty dictionaty to store the required data mars_data = {} browser = init_browser() # visit website1 to gather data site1 = "https://mars.nasa.gov/news/" browser.visit(site1) html = browser.html # create a soup object from the html and parse the title and article teaser body soup_obj = BeautifulSoup(html, "html.parser") news_title =soup_obj.find('div', attrs={'class': 'content_title'}).text article_teaser_body = soup_obj.find('div', attrs={'class': 'article_teaser_body'}).text #Adding the values to the dictionary mars_data["news_title"] = news_title mars_data["article_teaser_body"] = article_teaser_body # visit website2 to gather data site2 = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" browser.visit(site2) # traverse to the desired page by clicking on relevant buttons browser.click_link_by_id('full_image') time.sleep(2) browser.click_link_by_partial_text('more info') html = browser.html #create a soup object from the html and parse the featured image from the webpage soup_obj = BeautifulSoup(html, "html.parser") image = soup_obj.find("img", attrs={'class':'main_image'}) image = image['src'] image_src = "https://www.jpl.nasa.gov"+image #Adding the value to the dictionary mars_data["featured_image_url"] = image_src # visit website3 to gather data site3 = "https://twitter.com/marswxreport?lang=en" browser.visit(site3) html = browser.html # create a soup object from the html and parse the weather data from the tweet soup_obj = BeautifulSoup(html, "html.parser") tweet = soup_obj.find('div', attrs={'class': 'js-tweet-text-container'}).find('p').text #Adding the value to the dictionary mars_data["mars_weather"] = tweet #close the browser once all web scraping is done browser.quit() # visit website4 to gather data using pandas site4 = "http://space-facts.com/mars/" table = pd.read_html(site4) df = table[0] df.columns = ['Description','Value'] df.set_index('Description', inplace=True) mars_facts = df.to_html() df.to_html('table.html') #Adding the value to the dictionary mars_data["mars_facts"] = mars_facts #return the dictionary return mars_data
myfunc = lambda x,y:x+y res = myfunc(1,2) print(res) myfunc1 = lambda x,y=1:x+y res1 = myfunc1(2) print(res1) mylist = [lambda x:x**2,lambda x:x**3,lambda x:x**4] res2 = mylist[0](2) print(res2) print('----------------') for var in mylist: print(var(2)) print('----------------') #跳转表 #func #函数对象 #func() #函数调用 def func(): print('func') def func1(): print('func1') def func2(): print('func2') mylist1 = [func,func1,func2] #给别人看起来不直观 mylist1[0]()
# 异常处理 # 捕捉异常可以使用try/except语句。 # # try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。 # # 如果你不想在异常发生时结束你的程序,只需在try里捕获它。 # # 语法: # # 以下为简单的try....except...else的语法: # # try: # <语句> #运行别的代码 # except <名字>: # <语句> #如果在try部份引发了'name'异常 # except <名字>,<数据>: # <语句> #如果引发了'name'异常,获得附加的数据 # else: # <语句> #如果没有异常发生 # try的工作原理是,当开始一个try语句后,python就在当前程序的上下文中作标记,这样当异常出现时就可以回到这里,try子句先执行, # 接下来会发生什么依赖于执行时是否出现异常。 # # 如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句 # (除非在处理异常时又引发新的异常)。 # 如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印缺省的出错信息)。 # 如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句 # 使用except而不带任何异常类型 # 你可以不带任何异常类型使用except,如下实例: # # try: # 正常的操作 # ...................... # except: # 发生异常,执行这块代码 # ...................... # else: # 如果没有异常执行这块代码 # 以上方式try-except语句捕获所有发生的异常。但这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息。因为它捕获所有的异常 # 使用except而带多种异常类型 # 你也可以使用相同的except语句来处理多个异常信息,如下所示: # # try: # 正常的操作 # ...................... # except(Exception1[, Exception2[,...ExceptionN]]]): # 发生以上多个异常中的一个,执行这块代码 # ...................... # else: # 如果没有异常执行这块代码 # try-finally 语句 # try-finally 语句无论是否发生异常都将执行最后的代码。 # # try: # <语句> # finally: # <语句> #退出try时总会执行 # raise # 异常的参数 # 一个异常可以带上参数,可作为输出的异常信息参数。 # # 你可以通过except语句来捕获异常的参数,如下所示: # # try: # 正常的操作 # ...................... # except ExceptionType, Argument: # 你可以在这输出 Argument 的值... # 变量接收的异常值通常包含在异常的语句中。在元组的表单中变量可以接收一个或者多个值。 # # 元组通常包含错误字符串,错误数字,错误位置。 # 触发异常 # 我们可以使用raise语句自己触发异常 # # raise语法格式如下: # # raise [Exception [, args [, traceback]]] # 语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。 # # 最后一个参数是可选的(在实践中很少使用),如果存在,是跟踪异常对象。
import re example="hello world this is 2019" print(re.findall("\w\w",example)) print(re.findall("\w(\w)",example)) print(re.findall("(\w)\w",example)) print(re.findall("(\w)(\w)",example)) ''' ['he', 'll', 'wo', 'rl', 'th', 'is', 'is', '20', '19'] ['e', 'l', 'o', 'l', 'h', 's', 's', '0', '9'] ['h', 'l', 'w', 'r', 't', 'i', 'i', '2', '1'] [('h', 'e'), ('l', 'l'), ('w', 'o'), ('r', 'l'), ('t', 'h'), ('i', 's'), ('i', 's'), ('2', '0'), ('1', '9')] ''' print(re.findall(".*",example)) print(re.findall(".*?",example)) print(re.findall(".*",example)) ''' re.M 每一行当作一个新的字符 '''
#coding=utf-8 def printme(parameters ): "打印传递进函数的字符串" print(parameters) return printme("Hello Python !") # python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。 # 不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如fun(a),传递的只是a的值,没有影响a对象本身。 # 比如在 fun(a)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。 # # 可变类型:类似 c++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后fun外部的la也会受影响 def ChangeInt( a ): a = 10 b = 2 ChangeInt(b) print(b) # 结果是 2 # 可写函数说明 def changeme( mylist ): "修改传入的列表" mylist.append([1,2,3,4]); print ("函数内取值: ", mylist) return # 调用changeme函数 mylist = [10,20,30]; changeme( mylist ); print("函数外取值: ", mylist) #参数 : 必备参数 , 关键字参数 , 默认参数 , 不定长 参数 #必备参数, 需要传递参数进去函数 # 关键字参数 。传递参数的时候 。形如 : str="" 参数名,参数值一起传入 。 printme( parameters ="sss") #如果是多个参数。顺序可以随意 #缺省参数 (默认参数)没传递age的时候有默认值 def function(name,age=35): print (name,age) return; # 不定长参数 加了 *的变量名字会存放所有未命名的变量参数 def printinfo( arg1, *vartuple ): "打印任何传入的参数" print("输出: ") print(arg1) for var in vartuple: print(var) return; a = 1 def func(): a = 2 print('函数内部的a是:',a) func() print('函数外部的a是:',a) def func1(): global a a = 2 print('函数内部的a是:',a) func1() print('函数外部的a是:',a) import copy mylist = [1,2,3] def func3(obj): obj = ['a','b','c'] print('inside a is:',obj) def func2(obj): obj = copy.deepcopy(obj) obj = ['a','b','c'] #我们把这个列表 深拷贝给了 obj print('inside a is:',obj) func3(mylist)#传参 print('外部的a修改完成后是:',mylist) print('------------------') mylist = [1,2,3] func2(mylist)#传参 print('外部的a修改完成后是:',mylist)
''' 引用与拷贝 浅拷贝的方式: 浅拷贝 不会拷贝数据中的子对象 import copy 切片,copy() 深拷贝: 深拷贝 会拷贝数据中的子对象 import copy copy.deepcopy() ''' mylist=[1,2,3] mylist1=mylist[:] mylist1[0]=3 print(mylist,mylist1)
#登录 user_file = open(r'C:\Users\Administrator\Desktop\文件操作续集\user_info.txt') islogin = 0 #标志位 while True: if islogin == 0: account = input('请输入你要登录的帐号:') user_file.seek(0,0) for user in user_file: if user.split(':')[0] == account: passwd = input('请输入你要登录的密码:') #做密码核对的功能 if user.split(':')[1].strip() == passwd: print('登录成功') islogin = 1 break else: passwd_index = 1 while passwd_index < 3: print('密码检查失败,请重新输入,你还剩余的次数为:',3-passwd_index) passwd = input('请输入你要登录的密码:') if user.split(':')[1].strip() == passwd: print('登录成功') islogin = 1 break passwd_index+=1 break else: print('没有这个用户,您需要注册一下') else: break user_file.close()
#HATALAR #print(sayi) > NAME ERROR değişken tanımlanmadı #sayi1 = int ("1,2,3asd") > VALUE ERROR değerde hata var #sayi3 = 5/0 > ZeroDivisionError #print("merhaba"dünya) > SyntaxError #HATA AYIKLAMA try: sayi1=int("1,2,3asd") print("try bloğu içerisinde") except ValueError: print("hata oluştu")#direkt exceptiona geçiyor print("try bloğu dışı") try: sayi2= 5/0 except ZeroDivisionError: print("sıfıra bölünme hatası") """ ***********************************************""" try: sayi3 = int(input("sayi1: ")) sayi4 = int(input("sayi2: ")) print(sayi3/sayi4) except ValueError: print("lütfen sadece rakam giriniz") except ZeroDivisionError: print("sayı 2 0 olamaz") finally: print("Finally bloğu her zaman çalışır") """ ***********************************************""" def terstenYazdir(metin): if(type(metin) != str): raise ValueError("sadece string değerler olmalı") else: return metin[::-1] print(terstenYazdir("yaren")) try: print(terstenYazdir(50)) except ValueError: print("hata oluştu")
#FONKSİYONLAR #def FonksiyonAdi (par1,par2,....): # fonksiyonunKodları def karsilama(isim): print("Merhaba ben Siri , Hoşgeldin", isim) karsilama("Yaren") def karesiniAl(sayi): print(sayi*sayi) karesiniAl(10) def topla(sayi1,sayi2,sayi3): print("sonuç : ", sayi1+sayi2+sayi3) topla(10,20,30) def topla2(*sayilar):#* ile ist. kadar sayı girebilirim toplam=0 for i in sayilar: toplam+=i return toplam print(topla2(1,2,3,5,4,5676,7)) """ ***********************************************""" #Faktöriyel Hesaplama def faktoriyel(sayi): sonuc=1 for i in range(2,sayi+1): sonuc *=i print("Faktoriyel : " + sonuc) faktoriyel(5) """ ***********************************************""" #ebob def ebobBul(sayi1,sayi2): bolen=1#başlangıç değeri ebob=1 while(bolen <= sayi1 and bolen <= sayi2): if((sayi1 % bolen == 0) and(sayi2 % bolen == 0 )): ebob=bolen bolen +=1 return ebob sayi1=int(input("sayi1 : ")) sayi2=int(input("sayi2 : ")) print("Ebob : " , ebobBul(sayi1,sayi2)) """ ***********************************************""" #Mükemmel Sayı #1 sayının bölenleri toplamı kendisine eşitse #kendisi hariç def muko(sayi): toplam = 0 for bolen in range(1,sayi): if(sayi % bolen == 0): toplam += bolen return toplam == sayi for i in range(9999): if(muko(i)): print(i) """ ***********************************************""" #YEREL -GLOBAL DEĞİŞKENLER a=10 def f1(): global a #artık her yerde 50 a=50 print(a) f1() print(a)#fonk. dışında 10 içinde 50 #Global örneği def Menu(): return input("(T)opla (F)ark (Y)azdir (C)ikis") sayi1=0. sayi2=0.0 sonuc=0.0 def sayiGir(): global sayi1,sayi2 sayi1=float(input("Sayi1 : ")) sayi2=float(input("Sayi2 : ")) def Yazdir(): print(sonuc) def Topla(): global sonuc sonuc=sayi1+sayi2 def Fark(): global sonuc sonuc=sayi1-sayi2 def main(): while True: secim = Menu() if secim == "T" or secim == "t": sayiGir() Topla() Yazdir() elif secim == "F" or secim == "f": sayiGir() Fark() Yazdir() elif secim == "Y" or secim == "y": Yazdir() elif secim == "C" or secim == "c": break main() """ ***********************************************""" #LAMBDA: özet fonks. def kupAl(n): return n**3 print(kupAl(5)) kupAl2 = lambda x : x**3 print(kupAl2(3)) toplaLambda = lambda x,y,z : x+y+z print(toplaLambda(2,4,5)) tersCevir = lambda s : s[::-1] print(tersCevir("merhaba")) print(tersCevir("1234567")) """ ***********************************************""" #2 basamaklı sag-yı birler = ["","bir","iki","üç","dört","beş","altı","yedi","sekiz","dokuz"] onlar = ["","on","yirmi","otuz","kırk","elli","altmış","yetmiş","seksen","doksan"] def okuma(sayi): birinvi=sayi%10#1.basamak ikinci=sayi//10#2.basamak return onlar[ikinci] +" " +birler[birinci] sayi=int(input("Sayi : ")) print(okuma(sayi))
class Libro: def __init__(self, codigo_ISBN = '', titulo = '', genero = 0, idioma = 0, precio = 0.0): self.codigo_ISBN = codigo_ISBN self.titulo = titulo self.genero = genero self.idioma = idioma self.precio = precio # Muestra el libro con los idiomas y generos en palabras y no en codigos def to_string(libro): genero = ['Autoayuda', 'Arte', 'Ficción', 'Computacion', 'Economía', 'Escolar', 'Sociedad', 'Gastronomía', 'Infantil', 'Otros'] idioma = ['Español', 'Inglés', 'Francés', 'Italiano', 'Otros'] cadena = '' cadena += '{:<10}'.format(' identificacion: ' + str(libro.codigo_ISBN) + '\t') cadena += '{:<10}'.format('| titulo: ' + libro.titulo + '\t') cadena += '{:<10}'.format('| genero: ' + genero[libro.genero] + '\t') cadena += '{:<10}'.format('| idioma: ' + idioma[libro.idioma - 1] + '\t') cadena += '{:<10}'.format('| precio: ' + str(libro.precio) + '\t') return cadena # Muestra los libros pero con los codigos en idioma y genero def write(libro): cadena = '' cadena += '{:<10}'.format(' identificacion: ' + str(libro.codigo_ISBN) + '\t') cadena += '{:<10}'.format('| titulo: ' + libro.titulo + '\t') cadena += '{:<10}'.format('| genero: ' + str(libro.genero) + '\t') cadena += '{:<10}'.format('| idioma: ' + str(libro.idioma) + '\t') cadena += '{:<10}'.format('| precio: ' + str(libro.precio) + '\t') return cadena def test(): lib = Libro(159159, "Harry Explorer", 5, 2, 500) print(to_string(lib)) print("-"*40) write(lib) if __name__ == '__main__': test()
from functools import wraps import time def Calculate_Time(function): @wraps(function) def wrapper(*args,**kwargs): print(f'Executing.....{function.__name__}') T1 =time.time() returned_value = function(*args,**kwargs) T2 = time.time() Total_Time = T2-T1 print(f'This function took{Total_Time} Second') return returned_value return wrapper @Calculate_Time def square_finder(n): return[i**2 for i in range(1,n+1)] square_finder(1000)
import re def clean_word(word): word = re.sub(r'[^A-Za-z]', "", word.lower()) return word
#Code to count number of inversions #Author: Taruna Agrawal countInv = 0 # Merge Sort def mergeSort( num ): n = len(num)//2 if len(num) < 2: return else: leftArr = num[:n] rightArr = num[n:] mergeSort( leftArr ) mergeSort( rightArr) def merge(): nL = len(leftArr) nR = len(rightArr) i = 0; j = 0; k = 0 while i < nL and j < nR: if leftArr[i] < rightArr[j]: num[k] = leftArr[i] i += 1 else: num[k] = rightArr[j] j += 1 global countInv countInv = countInv + nL-i k += 1 while i < nL: num[k] = leftArr[i] i += 1 k += 1 while j < nR: num[k] = rightArr[j] j += 1 k += 1 merge() return num = [] #Read from file f = open('IntegerArray.txt', 'r') for line in f: num.append(int(line)) f.close() mergeSort(num) print ("Number of inversions are ", int(countInv))
""" listas: son colecciones de datos bajo un unico nombre , y para acceder esos nombres se utiliza un indice numerico """ pelicula = "Batman" #print(pelicula) #definir lista peliculas = [ "barman","spiderman", "El senor de los anillos"] cantantes= list(("2pac","Drake","Dualipa")) #transforma una tupla a lista year = list(range(2020,2040)) variable = ["maria",20,5.6,True] """ print(peliculas) print(cantantes) print(year) print(variable) """ #indices peliculas[1]= "Gran Torino " print(peliculas[1]) print(peliculas[-2]) print(cantantes[0:1]) # imprime de tal a tal print(peliculas[1:])# del 1 a todos #anadir elementos a la lista cantantes.append("Kase O") print(cantantes) #recorrer lista """ nueva="" while(nueva != "parar"): nueva= input("introduce tu pelicula") if nueva != "parar": peliculas.append(nueva) print("\n###########Listado##############") for pelicula in peliculas: print(f"{peliculas.index(pelicula)+1}.{pelicula}") """ #lista multidimencionales print("\n ########Lista de contactos#######") contactos = [ ['antonio','antonio.com'], ["luis", "luis.com"], ["salvador","salvador.com"] ] print(contactos[1][1]) for contacto in contactos: for elemento in contacto: if contacto.index(elemento)==0: print("Nombre: " + elemento) else: print("Email:"+ elemento) print("\n")
# operador de aisganacion edad = 26 print(edad) edad+= 5 edad = edad + 5 edad-= 5 print(edad) #operador de incremento y decremento year = 33 year = year +1 print(year) # Decremento year = year - 1
""" Ejericico 6 Mostrar todas las tablas de multiplicar del 1 al 10 , mostrando el titulo de la multiplicacion y luego las multiplicaciones """ numero = 1 while numero <= 10: print(f"###Tabla del {numero}###") for contador in range(1,11): print(f"{numero} x {contador} = {numero * contador}") numero += 1 print("\n")
""" Ejericio 2 Escribir un script que nos muestre por pantalla todos los numeros pares del 1 al 120 """ numero = 1 # con while while numero <=120: numero_par = numero % 2 if numero_par == 0 : print(numero) numero+=1 # con for for contador in range(1,121): if contador % 2 == 0: print(contador)
print("What is your weight?") weight = int(input('> ')) print("How many feet tall are you? For instance, if you're 5 feet and 11 inches tall, enter '5'") feet = int(input('> ')) print("And how many inches tall are you? For instance, if you're 6 feet and 2 inches tall, enter '2'") inches = int(input('> ')) height = (feet * 12) + inches bmi = weight / (height * height) * 703 print("You're BMI is", bmi)
import itertools import random def deck(): color = ['pik', 'kier', 'karo', 'trefl'] value = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jupek', 'Królowa', 'Król', 'As'] deck = list(itertools.product(value, color)) return deck def shuffle_deck(decko): random.shuffle(decko) def deal(deck, n): if(n*5 < 52): random.shuffle(deck) playersDeck = list() for i in range(n): playersCards = list() for j in range(5): playersCards.append(deck.pop(0)) playersDeck.append(playersCards) return playersDeck else: return false deck = deck() print(deal(deck, 5))
def inputFunc (): userInput = input() return(userInput) def inputFuncValidation (userInput): if userInput == '1' or userInput == '2' or userInput == '3' or userInput == '4' : valid = userInput else: valid = 0 return(valid)
# Given a positive integer num, output its complement number. # The complement strategy is to flip the bits of its binary representation. class Solution: def findComplement(self, num: int) -> int: a = format(num, 'b') op = '' for x in a: if x == '0': op += '1' else: op += '0' return int(op, 2)
# Given an arbitrary ransom note string and another string containing letters from all the magazines, # write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. # Each letter in the magazine string can only be used once in your ransom note. class Solution: def constructDict(self, s: str) -> dict: d = {} for x in s: try: d[x] += 1 except KeyError: d[x] = 1 return d def canConstruct(self, ransomNote: str, magazine: str) -> bool: r = self.constructDict(ransomNote) for k, v in r.items(): if magazine.count(k) < v: return False return True
u"""This is the naive implementation of a server handling many concurrent connections at once.""" import itertools, socket HOST = '127.0.0.1' PORT = 9001 def reverse(data): return ''.join(reversed(data)) commands = {'reverse' : reverse } def dispatcher(data): u"""Receives data, parses command and the payload. Then runs the command with the payload.""" parts = data.split(';', 1) cmd = commands.get(parts[0], False) if cmd and len(parts) > 1: return cmd(parts[1]) else: return data # TODO: Implement this, you know you want to! :) # def broadcast(*args, **kwargs): # u"""Receives a message and sends it to all connected clients.""" # # pass s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) print u'Starting and connecting to host: {0} and port {1}'.format(HOST, PORT) s.listen(1) # Activate the server print u'Waiting for connections...' conn, addr = s.accept() try: print u'Connected by addr: {0}'.format(addr) while True: print u'Receiving...' data = conn.recv(1024) if not data: break print u'Got data:' print data print u'Processing and sending...' conn.send(dispatcher(data)) finally: conn.close()
#!/usr/bin/env python """ Usage example employing Lasagne for digit recognition using the MNIST dataset. This example is deliberately structured as a long flat file, focusing on how to use Lasagne, instead of focusing on writing maximally modular and reusable code. It is used as the foundation for the introductory Lasagne tutorial: http://lasagne.readthedocs.org/en/latest/user/tutorial.html More in-depth examples and reproductions of paper results are maintained in a separate repository: https://github.com/Lasagne/Recipes """ from __future__ import print_function import sys import os import time import numpy as np import theano import theano.tensor as T import pickle # import lasagne.layers.dnn import lasagne from lasagne.layers import InputLayer, DenseLayer, DropoutLayer # from lasagne.layers.dnn import Conv2DDNNLayer as ConvLayer from lasagne.layers import Conv2DLayer as ConvLayer from lasagne.layers import MaxPool2DLayer as PoolLayer from lasagne.layers import LocalResponseNormalization2DLayer as NormLayer from lasagne.utils import floatX from utils import getTriplets import ipdb # ##################### Build the neural network model ####################### # This script supports three types of models. For each one, we define a # function that takes a Theano variable representing the input and returns # the output layer of a neural network model built in Lasagne. def build_mlp(input_var=None): # This creates an MLP of two hidden layers of 800 units each, followed by # a softmax output layer of 10 units. It applies 20% dropout to the input # data and 50% dropout to the hidden layers. # Input layer, specifying the expected input shape of the network # (unspecified batchsize, 1 channel, 28 rows and 28 columns) and # linking it to the given Theano variable `input_var`, if any: l_in = lasagne.layers.InputLayer(shape=(None, 1, 28, 28), input_var=input_var) # Apply 20% dropout to the input data: l_in_drop = lasagne.layers.DropoutLayer(l_in, p=0.2) # Add a fully-connected layer of 800 units, using the linear rectifier, and # initializing weights with Glorot's scheme (which is the default anyway): l_hid1 = lasagne.layers.DenseLayer( l_in_drop, num_units=800, nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.GlorotUniform()) # We'll now add dropout of 50%: l_hid1_drop = lasagne.layers.DropoutLayer(l_hid1, p=0.5) # Another 800-unit layer: l_hid2 = lasagne.layers.DenseLayer( l_hid1_drop, num_units=800, nonlinearity=lasagne.nonlinearities.rectify) # 50% dropout again: l_hid2_drop = lasagne.layers.DropoutLayer(l_hid2, p=0.5) # Finally, we'll add the fully-connected output layer, of 10 softmax units: l_out = lasagne.layers.DenseLayer( l_hid2_drop, num_units=10, nonlinearity=lasagne.nonlinearities.softmax) # Each layer is linked to its incoming layer(s), so we only need to pass # the output layer to give access to a network in Lasagne: return l_out def build_custom_mlp(input_var=None, depth=2, width=800, drop_input=.2, drop_hidden=.5): # By default, this creates the same network as `build_mlp`, but it can be # customized with respect to the number and size of hidden layers. This # mostly showcases how creating a network in Python code can be a lot more # flexible than a configuration file. Note that to make the code easier, # all the layers are just called `network` -- there is no need to give them # different names if all we return is the last one we created anyway; we # just used different names above for clarity. # Input layer and dropout (with shortcut `dropout` for `DropoutLayer`): network = lasagne.layers.InputLayer(shape=(None, 1, 28, 28), input_var=input_var) if drop_input: network = lasagne.layers.dropout(network, p=drop_input) # Hidden layers and dropout: nonlin = lasagne.nonlinearities.rectify for _ in range(depth): network = lasagne.layers.DenseLayer( network, width, nonlinearity=nonlin) if drop_hidden: network = lasagne.layers.dropout(network, p=drop_hidden) # Output layer: softmax = lasagne.nonlinearities.softmax network = lasagne.layers.DenseLayer(network, 10, nonlinearity=softmax) return network def build_cnn(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 1, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional layers. # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=32, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.GlorotUniform()) # Expert note: Lasagne provides alternative convolutional layers that # override Theano's choice of which implementation to use; for details # please see http://lasagne.readthedocs.org/en/latest/user/tutorial.html. # Max-pooling layer of factor 2 in both dimensions: network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=32, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=9, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_small(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 1, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional layers. # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=16, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.GlorotUniform()) # Expert note: Lasagne provides alternative convolutional layers that # override Theano's choice of which implementation to use; for details # please see http://lasagne.readthedocs.org/en/latest/user/tutorial.html. # Max-pooling layer of factor 2 in both dimensions: network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=16, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=64, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=9, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_pose_embedding(input_var=None, sizeIm=150): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 1, sizeIm, sizeIm), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) # # network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) # network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) # network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # # # A fully-connected layer of 256 units with 50% dropout on its inputs: # network = lasagne.layers.DenseLayer( # lasagne.layers.dropout(network, p=.5), # num_units=128, # nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=32, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn2(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 1, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional layers. # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=32, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.GlorotUniform()) # Expert note: Lasagne provides alternative convolutional layers that # override Theano's choice of which implementation to use; for details # please see http://lasagne.readthedocs.org/en/latest/user/tutorial.html. # Max-pooling layer of factor 2 in both dimensions: network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=32, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=32, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=9, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_pose(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 1, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=32, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=4, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_pose_color(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=32, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=4, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_appLight(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: input = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( input, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=32, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=12, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_shape(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 1, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=32, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=10, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_shape_k(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: input = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( input, num_filters=32, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.0), num_units=128, nonlinearity=lasagne.nonlinearities.rectify) ## A fully-connected layer of 256 units with 50% dropout on its inputs: #network = lasagne.layers.DenseLayer( # lasagne.layers.dropout(network, p=.0), # num_units=128, # nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=10, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_shape_medium(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: input = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( input, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=128, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=10, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_shape_large(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional layers. # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=256, filter_size=(7, 7), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.GlorotUniform()) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(3, 3)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=256, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=256, filter_size=(3, 3), nonlinearity=lasagne.nonlinearities.rectify) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=256, filter_size=(3, 3), nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=10, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_light(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: input = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( input, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=32, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=9, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_app(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: input = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( input, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=32, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=3, nonlinearity=lasagne.nonlinearities.linear) return network class MeanLayer(lasagne.layers.Layer): def get_output_for(self, input, **kwargs): return input.mean(axis=1).mean(axis=1) def get_output_shape_for(self, input_shape): return [input_shape[0],1] def build_cnn_mask(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: input = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( input, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=225, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=2250, nonlinearity=lasagne.nonlinearities.linear) numSmallMask = 2250 scaleFactor = 10 network = lasagne.layers.ReshapeLayer(network, ([0],1, numSmallMask)) # A fully-connected layer of 256 units with 50% dropout on its inputs: mask = lasagne.layers.Upscale1DLayer( incoming=network, scale_factor=scaleFactor) mask = lasagne.layers.ReshapeLayer(mask, ([0], numSmallMask*scaleFactor)) mask = lasagne.layers.NonlinearityLayer( mask, nonlinearity=lasagne.nonlinearities.sigmoid) return mask def build_cnn_mask_large(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: input = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( input, num_filters=256, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) lasagne.layers.get_output_shape(network) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=256, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=256, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) network = ConvLayer( network, num_filters=256, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) # network = lasagne.layers.MaxPool2DLayer(network, pool_size=(1, 1)) network = ConvLayer( network, num_filters=256, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) # network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=1125, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=1125, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network), num_units=2500, nonlinearity=lasagne.nonlinearities.linear) # numSmallMask = 2250 # scaleFactor = 10 # network = lasagne.layers.ReshapeLayer(network, ([0],1, numSmallMask)) # # # A fully-connected layer of 256 units with 50% dropout on its inputs: # mask = lasagne.layers.Upscale1DLayer( # incoming=network, # scale_factor=scaleFactor) # # mask = lasagne.layers.ReshapeLayer(mask, ([0], numSmallMask*scaleFactor)) mask = lasagne.layers.NonlinearityLayer( network, nonlinearity=lasagne.nonlinearities.sigmoid) return mask def build_cnn_appmask(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: input = lasagne.layers.InputLayer(shape=(None, 3, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( input, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=256, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=2250, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: mask = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=22500, nonlinearity=lasagne.nonlinearities.rectify) inputR = lasagne.layers.SliceLayer(input, 0, axis=1) inputG = lasagne.layers.SliceLayer(input, 1, axis=1) inputB = lasagne.layers.SliceLayer(input, 2, axis=1) reshapedMask = lasagne.layers.ReshapeLayer(mask, ([0],150, 150)) outR = MeanLayer(lasagne.layers.ElemwiseMergeLayer(incomings=[inputR, reshapedMask], merge_function=theano.tensor.mul)) outG = MeanLayer(lasagne.layers.ElemwiseMergeLayer(incomings=[inputG, reshapedMask], merge_function=theano.tensor.mul)) outB = MeanLayer(lasagne.layers.ElemwiseMergeLayer(incomings=[inputB, reshapedMask], merge_function=theano.tensor.mul)) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.ConcatLayer(incomings=[outR, outG, outB], axis=0) network = lasagne.layers.ReshapeLayer(network, ([0],3)) return network def build_cnn_pose_norm(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 1, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = lasagne.layers.normalization.batch_norm(ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = lasagne.layers.normalization.batch_norm(ConvLayer( network, num_filters=64, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = lasagne.layers.normalization.batch_norm(ConvLayer( network, num_filters=128, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.normalization.batch_norm(lasagne.layers.DenseLayer( network, num_units=256, nonlinearity=lasagne.nonlinearities.rectify)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.normalization.batch_norm(lasagne.layers.DenseLayer( network, num_units=32, nonlinearity=lasagne.nonlinearities.rectify)) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=4, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_pose_large(input_var=None): # As a third model, we'll create a CNN of two convolution + pooling stages # and a fully-connected hidden layer in front of the output layer. # Input layer, as usual: network = lasagne.layers.InputLayer(shape=(None, 1, 150, 150), input_var=input_var) # This time we do not apply input dropout, as it tends to work less well # for convolutional layers. # Convolutional layer with 32 kernels of size 5x5. Strided and padded # convolutions are supported as well; see the docstring. network = ConvLayer( network, num_filters=96, filter_size=(7, 7), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.GlorotUniform()) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(3, 3)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=256, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=512, filter_size=(3, 3), nonlinearity=lasagne.nonlinearities.rectify) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=512, filter_size=(3, 3), nonlinearity=lasagne.nonlinearities.rectify) # Another convolution with 32 5x5 kernels, and another 2x2 pooling: network = ConvLayer( network, num_filters=512, filter_size=(3, 3), nonlinearity=lasagne.nonlinearities.rectify) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(3, 3)) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=4096, nonlinearity=lasagne.nonlinearities.rectify) # A fully-connected layer of 256 units with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( lasagne.layers.dropout(network, p=.5), num_units=1024, nonlinearity=lasagne.nonlinearities.rectify) # And, finally, the 10-unit output layer with 50% dropout on its inputs: network = lasagne.layers.DenseLayer( network, num_units=4, nonlinearity=lasagne.nonlinearities.linear) return network def build_cnn_pose_large_norm(input_var=None): network = lasagne.layers.InputLayer(shape=(None, 1, 150, 150), input_var=input_var) network = lasagne.layers.normalization.batch_norm(ConvLayer( network, num_filters=96, filter_size=(7, 7), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.GlorotUniform())) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(3, 3)) network = lasagne.layers.normalization.batch_norm(ConvLayer( network, num_filters=256, filter_size=(5, 5), nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2)) network = lasagne.layers.normalization.batch_norm(ConvLayer( network, num_filters=512, filter_size=(3, 3), nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.normalization.batch_norm(ConvLayer( network, num_filters=512, filter_size=(3, 3), nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.normalization.batch_norm(ConvLayer( network, num_filters=512, filter_size=(3, 3), nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.MaxPool2DLayer(network, pool_size=(3, 3)) network = lasagne.layers.normalization.batch_norm(lasagne.layers.DenseLayer( network, num_units=4096, nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.normalization.batch_norm(lasagne.layers.DenseLayer( network, num_units=1024, nonlinearity=lasagne.nonlinearities.rectify)) network = lasagne.layers.DenseLayer( network, num_units=4, nonlinearity=lasagne.nonlinearities.linear) return network def iterate_minibatches(inputs, targets, batchsize, shuffle=False): assert len(inputs) == len(targets) if shuffle: indices = np.arange(len(inputs)) np.random.shuffle(indices) for start_idx in range(0, len(inputs) - batchsize + 1, batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) yield inputs[excerpt], targets[excerpt] def iterate_minibatches_triplets(inputs, inputs_t1, inputs_t2, batchsize, shuffle=False): assert len(inputs) == len(inputs_t1) == len(inputs_t2) if shuffle: indices = np.arange(len(inputs)) np.random.shuffle(indices) for start_idx in range(0, len(inputs) - batchsize + 1, batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) yield inputs[excerpt], inputs_t1[excerpt], inputs_t2[excerpt] def iterate_minibatches_h5(inputs_h5, trainSet, trainValSet, targets, batchsize, shuffle=False): assert len(trainValSet) == len(targets) print("Loading minibatch set") if shuffle: indices = np.arange(len(trainValSet)) np.random.shuffle(indices) for start_idx in range(0, len(trainValSet), batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) boolSet = np.zeros(len(inputs_h5)).astype(np.bool) boolSet[trainSet[trainValSet[excerpt]]] = True yield inputs_h5[boolSet,:,:], targets[excerpt] print("Ended loading minibatch set") def load_network(modelType='cnn', param_values=[], imgSize=150): # Load the dataset # Prepare Theano variables for inputs and targets input_var = T.tensor4('inputs') # Create neural network model (depending on first command line parameter) print("Building model and compiling functions...") if modelType == 'mlp': network = build_mlp(input_var) elif modelType.startswith('custom_mlp:'): depth, width, drop_in, drop_hid = modelType.split(':', 1)[1].split(',') network = build_custom_mlp(input_var, int(depth), int(width), float(drop_in), float(drop_hid)) elif modelType == 'cnn': network = build_cnn(input_var) elif modelType == 'cnn2': network = build_cnn2(input_var) elif modelType == 'cnn_pose': network = build_cnn_pose(input_var) elif modelType == 'cnn_pose_embedding': network = build_cnn_pose_embedding(input_var, imgSize) elif modelType == 'cnn_pose_large': network = build_cnn_pose_large(input_var) elif modelType == 'cnn_pose_color': network = build_cnn_pose_color(input_var) elif modelType == 'cnn_pose_norm': network = build_cnn_pose_norm(input_var) elif modelType == 'cnn_pose_large_norm': network = build_cnn_pose_large_norm(input_var) elif modelType == 'cnn_light': network = build_cnn_light(input_var) elif modelType == 'cnn_shape': network = build_cnn_shape(input_var) elif modelType == 'cnn_shape_large': network = build_cnn_shape_large(input_var) elif modelType == 'cnn_shape_medium': network = build_cnn_shape_medium(input_var) elif modelType == 'cnn_appLight': network = build_cnn_appLight(input_var) elif modelType == 'cnn_app': network = build_cnn_app(input_var) elif modelType == 'cnn_appmask': network = build_cnn_appmask(input_var) elif modelType == 'cnn_mask': network = build_cnn_mask(input_var) elif modelType == 'cnn_mask_large': network = build_cnn_mask_large(input_var) else: print("Unrecognized model type %r." % modelType) if param_values: lasagne.layers.set_all_param_values(network, param_values) return network def get_prediction_fun(network): # Load the dataset # Prepare Theano variables for inputs and targets input_var = lasagne.layers.get_all_layers(network)[0].input_var prediction = lasagne.layers.get_output(network, deterministic=True) prediction_fn = theano.function([input_var], prediction) return prediction_fn def get_prediction_fun_nondeterministic(network): # Load the dataset # Prepare Theano variables for inputs and targets input_var = lasagne.layers.get_all_layers(network)[0].input_var prediction = lasagne.layers.get_output(network, deterministic=False) prediction_fn = theano.function([input_var], prediction) return prediction_fn def train_nn_h5(X_h5, trainSetVal, y_train, y_val, meanImage, network, modelType = 'cnn', num_epochs=150, saveModelAtEpoch=True, modelPath='tmp/nnmodel.pickle', param_values=[]): # Load the dataset print("Loading validation set") if meanImage.ndim == 2: meanImage = meanImage[:,:,None] X_val = X_h5[trainSetVal::].astype(np.float32) - meanImage.reshape([1,meanImage.shape[2], meanImage.shape[0],meanImage.shape[1]]).astype(np.float32) print("Ended loading validation set") model = {} model['mean'] = meanImage model['type'] = modelType if param_values: lasagne.layers.set_all_param_values(network, param_values) input_var = lasagne.layers.get_all_layers(network)[0].input_var target_var = T.fmatrix('targets') prediction = lasagne.layers.get_output(network) params = lasagne.layers.get_all_params(network, trainable=True) test_prediction = lasagne.layers.get_output(network, deterministic=True) if modelType == 'cnn_mask': loss = lasagne.objectives.binary_crossentropy(prediction, target_var) loss = loss.mean() test_loss = lasagne.objectives.binary_crossentropy(test_prediction, target_var) test_loss = test_loss.mean() else: loss = lasagne.objectives.squared_error(prediction, target_var) loss = loss.mean() test_loss = lasagne.objectives.squared_error(test_prediction, target_var) test_loss = test_loss.mean() updates = lasagne.updates.nesterov_momentum( loss, params, learning_rate=0.01, momentum=0.9) train_fn = theano.function([input_var, target_var], loss, updates=updates) # Compile a second function computing the validation loss and accura# cy: val_fn = theano.function([input_var, target_var], test_loss) # Finally, launch the training loop. print("Starting training...") # We iterate over epochs: patience = 20 best_valid = np.inf best_valid_epoch = 0 best_weights = None batchSize = 128 for epoch in range(num_epochs): # In each epoch, we do a full pass over the training data: train_err = 0 train_batches = 0 start_time = time.time() slicesize = 20000 sliceidx = 0 for start_idx in range(0, trainSetVal, slicesize): sliceidx += 1 print("Working on slice " + str(sliceidx) + " of " + str(int(trainSetVal/slicesize))) X_train = X_h5[start_idx:min(start_idx + slicesize,trainSetVal)].astype(np.float32) - meanImage.reshape([1,meanImage.shape[2], meanImage.shape[0],meanImage.shape[1]]).astype(np.float32) for batch in iterate_minibatches(X_train, y_train[start_idx:min(start_idx + slicesize,trainSetVal)], batchSize, shuffle=True): # print("Batch " + str(train_batches)) inputs, targets = batch train_err += train_fn(inputs, targets) train_batches += 1 # And a full pass over the validation data: val_err = 0 val_batches = 0 for batch in iterate_minibatches(X_val, y_val, batchSize, shuffle=False): inputs, targets = batch err = val_fn(inputs, targets) val_err += err val_batches += 1 if val_err < best_valid: best_weights = lasagne.layers.get_all_param_values(network) if saveModelAtEpoch: model['params'] = best_weights with open(modelPath, 'wb') as pfile: pickle.dump(model, pfile) best_valid = val_err best_valid_epoch = epoch elif best_valid_epoch + patience < epoch: print("Early stopping.") # print("Best valid loss was {:.6f} at epoch {}.".format( # best_valid, best_valid_epoch)) break # Then we print the results for this epoch: print("Epoch {} of {} took {:.3f}s".format( epoch + 1, num_epochs, time.time() - start_time)) print(" training loss:\t\t{:.6f}".format(train_err / train_batches)) print(" validation loss:\t\t{:.6f}".format(val_err / val_batches)) model['params'] = best_weights return model from lasagne.regularization import regularize_layer_params_weighted, l2, l1 def train_triplets_h5(X_h5, Xt1_h5, Xt2_h5, trainSetVal, meanImage, network, modelType = 'cnn', num_epochs=150, saveModelAtEpoch=True, modelPath='tmp/nnmodel.pickle', param_values=[]): # Load the dataset print("Loading validation set") if meanImage.ndim == 2: meanImage = meanImage[:,:,None] X_val = X_h5[trainSetVal::].astype(np.float32) X_t1_val = Xt1_h5[trainSetVal::].astype(np.float32) X_t2_val = Xt2_h5[trainSetVal::].astype(np.float32) # height = X_h5[0].shape[2] # width = X_h5[0].shape[3] print("Ended loading validation set") model = {} model['mean'] = meanImage model['type'] = modelType if param_values: lasagne.layers.set_all_param_values(network, param_values) input_var = lasagne.layers.get_all_layers(network)[0].input_var # target_var = T.fmatrix('targets') predictions = lasagne.layers.get_output(network) params = lasagne.layers.get_all_params(network, trainable=True) batchSize = 36 batchStepSize = int(batchSize / 3) test_predictions = lasagne.layers.get_output(network, deterministic=True) test_predictions_t0 = test_predictions[0:batchStepSize] test_predictions_t1 = test_predictions[batchStepSize:2*batchStepSize] test_predictions_t2 = test_predictions[2*batchStepSize::] # loss = lasagne.objectives.binary_crossentropy(prediction, prediction_t1, prediction_t2) m = 0.001 predictions_t0 = predictions[0:batchStepSize] predictions_t1 = predictions[batchStepSize:2*batchStepSize] predictions_t2 = predictions[2*batchStepSize::] loss = T.sum((predictions_t1 - predictions_t0)**2, axis=1) / (T.sum((predictions_t2 - predictions_t0)**2, axis=1) + m) loss = loss.mean() # ipdb.set_trace() layers = lasagne.layers.get_all_layers(network) regLayers = {layer:0.01 for layer in layers} l2_penalty = regularize_layer_params_weighted(regLayers,l2) # loss = loss test_loss = T.sum((test_predictions_t1 - test_predictions_t0)**2, axis=1) / (T.sum((test_predictions_t2 - test_predictions_t0)**2, axis=1) + m) test_loss = test_loss.mean() # test_loss = test_loss updates = lasagne.updates.nesterov_momentum( loss, params, learning_rate=0.01, momentum=0.9) train_fn = theano.function([input_var], loss, updates=updates) pred_t0_fn = theano.function([input_var], test_predictions_t0) pred_t1_fn = theano.function([input_var], test_predictions_t1) pred_t2_fn = theano.function([input_var], test_predictions_t2) # Compile a second function computing the validation loss and accura# cy: val_fn = theano.function([input_var], test_loss) # Finally, launch the training loop. print("Starting training...") # We iterate over epochs: patience = 20 best_valid = np.inf best_valid_epoch = 0 best_weights = None for epoch in range(num_epochs): # In each epoch, we do a full pass over the training data: train_err = 0 train_batches = 0 start_time = time.time() slicesize = 10000 sliceidx = 0 for start_idx in range(0, trainSetVal, slicesize): sliceidx += 1 print("Working on slice " + str(sliceidx) + " of " + str(int(trainSetVal/slicesize))) X_train = X_h5[start_idx:min(start_idx + slicesize,trainSetVal)].astype(np.float32) X_t1_train = Xt1_h5[start_idx:min(start_idx + slicesize,trainSetVal)].astype(np.float32) X_t2_train = Xt2_h5[start_idx:min(start_idx + slicesize, trainSetVal)].astype(np.float32) # parameterVals = y_train[start_idx:min(start_idx + slicesize,trainSetVal)] # anchorIdx, closeIdx, farIdx = getTriplets(parameterVals, closeDist=5 * np.pi / 180, farDist=15 * np.pi / 180, normConst=2 * np.pi, chunkSize=10) for batch in iterate_minibatches_triplets(X_train, X_t1_train, X_t2_train, batchStepSize, shuffle=True): # print("Batch " + str(train_batches)) inputs, inputs_t1, inputs_t2 = batch # # p0 = pred_t0_fn(np.concatenate([inputs, inputs_t1, inputs_t2], axis=0)) # p1 = pred_t1_fn(np.concatenate([inputs, inputs_t1, inputs_t2], axis=0)) # p2 = pred_t2_fn(np.concatenate([inputs, inputs_t1, inputs_t2], axis=0)) # nperr = np.sum((p1 - p0) ** 2, axis=1) / (np.sum((p2 - p0)**2, axis=1) + m) train_err += train_fn(np.concatenate([inputs, inputs_t1, inputs_t2],axis=0)) # # # p0 = pred_t0_fn(np.concatenate([inputs, inputs_t1, inputs_t2], axis=0)) # p1 = pred_t1_fn(np.concatenate([inputs, inputs_t1, inputs_t2], axis=0)) # p2 = pred_t2_fn(np.concatenate([inputs, inputs_t1, inputs_t2], axis=0)) # # nperr = np.sum((p1 - p0) ** 2, axis=1) / (np.sum((p2 - p0)**2, axis=1) + m) train_batches += 1 # And a full pass over the validation data: val_err = 0 val_batches = 0 for batch in iterate_minibatches_triplets(X_val, X_t1_val, X_t2_val, batchStepSize, shuffle=True): inputs, inputs_t1, inputs_t2 = batch err = val_fn(np.concatenate([inputs, inputs_t1, inputs_t2], axis=0)) val_err += err val_batches += 1 if val_err < best_valid: best_weights = lasagne.layers.get_all_param_values(network) if saveModelAtEpoch: model['params'] = best_weights with open(modelPath, 'wb') as pfile: pickle.dump(model, pfile) best_valid = val_err best_valid_epoch = epoch elif best_valid_epoch + patience < epoch: print("Early stopping.") # print("Best valid loss was {:.6f} at epoch {}.".format( # best_valid, best_valid_epoch)) break # Then we print the results for this epoch: print("Epoch {} of {} took {:.3f}s".format( epoch + 1, num_epochs, time.time() - start_time)) print(" training loss:\t\t{:.6f}".format(train_err / train_batches)) print(" validation loss:\t\t{:.6f}".format(val_err / val_batches)) model['params'] = best_weights return model
filename = "file.txt" ## Writing file = open(filename, 'w') for i in range(1, 11): file.write("This is line %i \n" % i) file.close() file = open(filename, 'r') for line in file: print(line, end = '') file.close()
letters = {"A": "E", "B": "F", "C": "G", "D": "H", "E": "I", "F": "J", "G": "K", "H": "L", "I": "M", "J": "N", "K": "O", "L": "P", "M": "Q", "N": "R", "O": "S", "P": "T", "Q": "U", "R": "V", "S": "W", "T": "X", "U": "Y", "V": "Z", "W": "A","X": "B", "Y": "C", "Z": "D"} message = input("Enter your message: ").upper() encrypted = "" for letter in message: if letter in letters: encrypted += letters[letter] else: encrypted += letter print(encrypted)
# This program calculates the shift of characters (the key) that has been used # when a message has been decrypted by a substitution cipher. sentance = "amrwxsr xli hsk jsyklx sjj e fiev" sentance = sentance.lower() sentanceList = sentance.split(" ") # sorts the list into order using the sorted function. # longest word first so more likely to find in dictionary # as less likely to accidently stumble on a word newlist = sorted(sentanceList, key=len, reverse = True) keyFound = False key = 1 decryptedChars = [] # creates empty list for string to be passed through # Opens a dictionary file to be scanned for the decrypted words with open('myDictionary.txt') as dictionary_file: dictionary = dictionary_file.read() x = 0 while(x < len(newlist)): while(keyFound == False): for chars in newlist[x]: # goes through each char of the first word print chars num = ord(chars) # turns char to ascii value num -= key # adds the current key to it decryptedChars.append(chr(num)) #turns back into chars and adds them to the empty list decryptedWord = "".join(str(x) for x in decryptedChars) #converts the list into a string to be able to search for print decryptedWord #might have to put a for loop here to search for word in file if decryptedWord in dictionary: #checks if the decryplist string is in the dictionary keyFound = True # if yes this will exit loop and print the key value print "FOUND!!" print "The Key is {0}".format(key) else: key += 1 decryptedChars = [] if key > 26: print ("Could not find word in first instance") break # if not, increments key by 1 # and also clears the list of its current values, making it empty # again for processing the next bunch of characters x+=1 key = 0 # next need to be able to go to the next word if it was unable # to find the key with the first word. also need it to stop if # probably when key hits 25 do newlist[1] # and also need to solve problem of zxy abc etc.
#Decrypts it with key of 3 #Also works around z #Ascii number for z is 122 #Ascii number for a is 97 #when DECRYPTING only have to care about a #when ENCRYPTING have to care about z #Word is phenomenal. key = 4 sentance = 'the world can be one together cosmos without hatred' sentanceList = sentance.split(" ") i = 0 encryptedChars = [] def encryptIt(num): j = 0 while(j < key): num += 1 if num > 122: num = 97 #num += 1 j += 1 encryptedChars.append(chr(num)) while(i < len(sentanceList)): for char in sentanceList[i]: num = ord(char) encryptIt(num) encryptedChars.append(' ') i+=1 print "".join(str(x) for x in encryptedChars) #modulus to get remainder. #maths is the answer #probably some mathmatical function that will make it work.
from random import shuffle class Card: suits = ["spades", "hearts", "diamonds", "clubs"] # first two items are None so that index matches card value values = [None, None, "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] def __init__(self, value, suit): # suits and values should be integers self.value = value self.suit = suit # determines if card is less than opponent's card def __lt__(self, other): if self.value < other.value: return True if self.value == other.value: if self.suit < other.suit: return True else: return False return False # determines if card is greater than opponent's card def __gt__(self, other): if self.value > other.value: return True if self.value == other.value: if self.suit > other.suit: return True else: return False return False # returns the value and suit of the Card object def __repr__(self): return self.values[self.value] + " of " + self.suits[self.suit] class Deck: def __init__(self): self.cards = [] # creates a list of cards, first loop is for each card rank, second loop is for each card suit for i in range(2, 15): for j in range(4): self.cards.append(Card(i, j)) shuffle(self.cards) # removes and returns a card from the cards list def rm_card(self): if len(self.cards) == 0: return return self.cards.pop() class Player: def __init__(self, name): self.wins = 0 self.card = None self.name = name class Game: def __init__(self): # starts game by getting player names, creating Deck object, and creating players name1 = input("Player 1 name ") name2 = input("Player 2 name ") self.deck = Deck() self.p1 = Player(name1) self.p2 = Player(name2) # prints the winner of each round of the game def wins(self, winner): w = "{} wins this round" w = w.format(winner) print(w) # prints the results the outcome of each round of card draws def draw(self, p1n, p1c, p2n, p2c): d = "{} drew {} while {} drew {}" d = d.format(p1n, p1c, p2n, p2c) print(d) # starts the game def play_game(self): cards = self.deck.cards print("Beginning War!") # continue the game as long as there are at least two or more cards left in the deck while len(cards) >= 2: m = "Press q to quit or any " + "key to play!" response = input(m) if response == "q": break p1c = self.deck.rm_card() p2c = self.deck.rm_card() p1n = self.p1.name p2n = self.p2.name self.draw(p1n, p1c, p2n, p2c) if p1c > p2c: self.p1.wins += 1 self.wins(self.p1.name) else: self.p2.wins += 1 self.wins(self.p2.name) win = self.winner(self.p1, self.p2) # print result of the game print("War is over. {} wins".format(win)) # returns the player who won the most rounds def winner(self, p1, p2): if p1.wins > p2.wins: return p1.name if p1.wins < p2.wins: return p2.name return "It was a tie!" game =Game() game.play_game()
user_number = int(input("Enter a number of three digits:")) array = list() i= 0 while user_number >= 0: array[i] = user_number%10 user_number = user_number /10 i+= 1 array.sort(reverse=True) # Lets do some sorting to get second largest temp = array[0] array[0] = array[1] array[1] = temp # now we are moving the second largest digits from the array to integer new =0 for i in range(3): new = new*10 + array[i] print("the second largest number is:"+new)
with open("Input.txt") as file: linebuffer = file.read() lines = linebuffer.split(" ") max_occurence = max(lines, key=lines.count) print("The no occured max is :", max_occurence) print("The no of time this word occured :", lines.count(max_occurence))
num1,num2 = map(int,input("Enter two numbers to find out HCF:").split()) if num1 > num2: smaller = num2 if num1 % smaller == 0: print("The HCF of both the numbers is:",smaller) else: for i in range(2,(smaller//2)+1): if num1% i == 0: print("The HCF is: ",i) break else: smaller = num1 if num2 % smaller == 0: print("The HCF of both the numbers is:",smaller) else: for i in range(2,(smaller//2)+1): if num2% i == 0: print("The HCF is: ",i) break
import unittest from queue import Queue class QueueTest(unittest.TestCase): def test_object(self): """ - test if queue object has been implemented - returns true for the correct name """ queue = Queue() self.assertEqual(type(queue).__name__, 'Queue') def test_has_list(self): """ - test if queue has internal list to store data - returns true if it variable is a list """ queue = Queue() self.assertTrue(type(queue.data) is list) def test_enqueue(self): """ - test if enqueue has been implemented correctly - returns true on checking element in self list """ queue = Queue() data1 = 'foo' queue.enqueue(data1) data2 = 'bar' queue.enqueue(data2) self.assertEqual(queue.data[0], data1) self.assertEqual(queue.data[-1], data2) def test_dequeue(self): """ self.assertEqual(queue.data[0], data1) - test if pop has been implemented correctly - returns true when data is not in list """ queue = Queue() data1 = 'foo' data2 = 'bar' queue.enqueue(data1) queue.enqueue(data2) check1 = queue.dequeue() check2 = queue.dequeue() self.assertEqual(data1, check1) self.assertEqual(data2, check2) if __name__ == '__main__': unittest.main()
#!/usr/bin/python #!encoding: UTF-8 import moduloerror import sys if((len(sys.argv)==1) or (len(sys.argv)==2)or(len(sys.argv)==3)): print ("No se han introducido los valores necesarios. Se utilizarán los valores predeterminados:") print("Intervalos= 10 Veces=10 umbral 0.1") k=10 n=10 umbral=0.1 else: n= int(sys.argv[2]) k= int(sys.argv[1]) umbral=float(sys.argv[3]) print("Nº de intervalos\tNº de veces\tUmbral de error\tPorcentaje") print " %d, %d, %g, %g" %(k, n, umbral, moduloerror.error (n, k, umbral))
# -*- coding: utf-8 -*- """ Created on Sat Jun 2 14:18:37 2018 @author: cherylK """ from matplotlib import pyplot as plt import pandas as pd import numpy as np species=pd.read_csv('species_info.csv') #print species.head() # "How many different species are in the `species` DataFrame?" 5541 num_species=species.scientific_name.nunique() print num_species #"What are the different values of `category` in `species`?" #Amphibian [Amphibian] #Bird [Bird] #Fish [Fish] #Mammal [Mammal] #Nonvascular Plant [Nonvascular Plant] #Reptile [Reptile] #Vascular Plant [Vascular Plant] category=species.groupby('category').category.unique() print category # "What are the different values of `conservation_status`?" #Endangered [Endangered] #In Recovery [In Recovery] #Species of Concern [Species of Concern] #Threatened [Threatened] conservation=species.groupby('conservation_status').conservation_status.unique() print conservation # "The column `conservation_status` has several possible values:\n", # "- `Species of Concern`: declining or appear to be in need of conservation\n", # "- `Threatened`: vulnerable to endangerment in the near future\n", # "- `Endangered`: seriously at risk of extinction\n", # "- `In Recovery`: formerly `Endangered`, but currnetly neither in danger of extinction throughout all or a significant portion of its range\n", # "\n", # "We'd like to count up how many species meet each of these criteria. Use `groupby` to count how many `scientific_name` meet each of these criteria." #0 Endangered 16 #1 In Recovery 4 #2 Species of Concern 161 #3 Threatened 10 name_counts = species.groupby('conservation_status').scientific_name.count().reset_index() print name_counts #"As we saw before, there are far more than 200 species in the `species` table. Clearly, only a small number of them are categorized as needing some sort of protection. The rest have `conservation_status` equal to `None`. Because `groupby` does not include `None`, we will need to fill in the null values. We can do this using `.fillna`. We pass in however we want to fill in our `None` values as an argument.\n", # "\n", # "Paste the following code and run it to see replace `None` with `No Intervention`:\n", # "```python\n", # "species.fillna('No Intervention', inplace=True)\n", # "```" species.fillna('No Intervention', inplace=True) # "Great! Now run the same `groupby` as before to see how many species require `No Protection`." 5633 name_counts = species.groupby('conservation_status').scientific_name.count().reset_index() print name_counts #"Let's use `plt.bar` to create a bar chart. First, let's sort the columns by how many species are in each categories. We can do this using `.sort_values`. We use the the keyword `by` to indicate which column we want to sort by.\n", # "\n", # "Paste the following code and run it to create a new DataFrame called `protection_counts`, which is sorted by `scientific_name`:\n", # "```python\n", # "protection_counts = species.groupby('conservation_status')\\\n", # " .scientific_name.count().reset_index()\\\n", # " .sort_values(by='scientific_name')\n", # "```" protection_counts = species.groupby('conservation_status').scientific_name.count().reset_index().sort_values(by='scientific_name') #"Now let's create a bar chart!\n", # "1. Start by creating a wide figure with `figsize=(10, 4)`\n", # "1. Start by creating an axes object called `ax` using `plt.subplot`.\n", # "2. Create a bar chart whose heights are equal to `scientific_name` column of `protection_counts`.\n", # "3. Create an x-tick for each of the bars.\n", # "4. Label each x-tick with the label from `conservation_status` in `protection_counts`\n", # "5. Label the y-axis `Number of Species`\n", # "6. Title the graph `Conservation Status by Species`\n", # "7. Plot the grap using `plt.show()`" plt.figure(figsize=(10,4)) ax=plt.subplot() y = protection_counts.scientific_name.values N = len(y) x = range(N) plt.bar(x, y) ax.set_xticks(range(len(y))) ax.set_xticklabels(protection_counts.conservation_status.values) plt.ylabel('Number of Species') plt.xlabel('Conservation Status') plt.title('Conservation Status by Species') plt.show() # "Are certain types of species more likely to be endangered?" # "Let's create a new column in `species` called `is_protected`, which is `True` if `conservation_status` is not equal to `No Intervention`, and `False` otherwise." species['is_protected'] = species.apply(lambda x: 'True' if x['conservation_status'] != 'No Intervention' else 'False', axis=1) print species.head(10) #"Let's group by *both* `category` and `is_protected`. Save your results to `category_counts`." category_counts=species.groupby(['category', 'is_protected']).scientific_name.nunique().reset_index() print category_counts #"It's going to be easier to view this data if we pivot it. Using `pivot`, rearange `category_counts` so that:\n", # "- `columns` is `conservation_status`\n", # "- `index` is `category`\n", # "- `values` is `scientific_name`\n", # "\n", # "Save your pivoted data to `category_pivot`. Remember to `reset_index()` at the end." #df.pivot(columns='ColumnToPivot', # index='ColumnToBeRows', # values='ColumnToBeValues') category_pivot=category_counts.pivot(columns='is_protected', index='category', values='scientific_name').reset_index() print category_pivot #"Use the `.columns` property to rename the categories `True` and `False` to something more description:\n", # "- Leave `category` as `category`\n", # "- Rename `False` to `not_protected`\n", # "- Rename `True` to `protected`" category_pivot.rename(columns={'False': 'not_protected'}, inplace=True) category_pivot.rename(columns={'True': 'protected'}, inplace=True) print category_pivot #"Let's create a new column of `category_pivot` called `percent_protected`, which is equal to `protected` (the number of species #that are protected) divided by `protected` plus `not_protected` (the total number of species)." category_pivot['percent_protected']=(category_pivot.protected/(category_pivot.protected+category_pivot.not_protected)) print category_pivot #"It looks like species in category `Mammal` are more likely to be endangered than species in `Bird`. We're going to do a significance test to see if this statement is true. Before you do the significance test, #consider the following questions:\n", # "- Is the data numerical or categorical?\n", categorical # "- How many pieces of data are you comparing?" more than 2 #"Based on those answers, you should choose to do a *chi squared test*. In order to run a chi squared test, we'll need to create a contingency table. Our contingency table should look like this:\n", # "\n", # "||protected|not protected|\n", # "|-|-|-|\n", # "|Mammal|?|?|\n", # "|Bird|?|?|\n", # "\n", # "Create a table called `contingency` and fill it in with the correct numbers" from scipy.stats import chi2_contingency # Contingency table # not_protected| protected # ----+------------------+------------ # Amphibian | 72 | 7 # Bird | 413 | 75 # Fish | 115 | 11 # Mammal | 146 | 30 # Nonvasc | 328 | 5 # Reptile | 73 | 5 # Vascular | 4216 | 46 X = [[72, 7.], [413, 75.], [115, 11.], [146, 30.], [328, 5.], [73, 5.], [4216, 46.]] contingency= [[146, 30], [413, 5]] chi2, pval, dof, expected = chi2_contingency(contingency) print pval # "It looks like this difference isn't significant!\n", # "\n", # "Let's test another. Is the difference between `Reptile` and `Mammal` significant?" Yes because pvalue is less than .05 (.038356) contingency2 = [[73, 5.], [146, 30.]] chi2, pval, dof, expected = chi2_contingency(contingency2) print pval #between amphibian and fish contingency3= [[72, 7.], [115, 11.]] chi2, pval, dof, expected = chi2_contingency(contingency3) print pval #between nonvascular and vascular plants contingency4= [[328, 5.], [4216, 46.]] chi2, pval, dof, expected = chi2_contingency(contingency4) print pval # "Conservationists have been recording sightings of different species at several national parks for the past 7 days. # They've saved sent you their observations in a file called `observations.csv`. Load `observations.csv` into a variable called `observations`, then use `head` to view the data." observations=pd.read_csv('observations.csv') print observations.head() # "Some scientists are studying the number of sheep sightings at different national parks. #There are several different scientific names for different types of sheep. We'd like to know which rows of `species` are referring to sheep. #Notice that the following code will tell us whether or not a word occurs in a string:" # "# Does \"Sheep\" occur in this string?\n", # "str1 = 'This string contains Sheep'\n", # "'Sheep' in str1" #"# Does \"Sheep\" occur in this string?\n", # "str2 = 'This string contains Cows'\n", # "'Sheep' in str2" str1 = 'This string contains Sheep' str2 = 'This string contains Cows' # "Use `apply` and a `lambda` function to create a new column in `species` called `is_sheep` which is `True` if the `common_names` contains `'Sheep'`, and `False` otherwise." species['is_sheep'] = species.common_names.apply(lambda x: 'Sheep' in x) print species.head(10) #"Select the rows of `species` where `is_sheep` is `True` and examine the results." print species[species.is_sheep] # "Many of the results are actually plants. Select the rows of `species` where `is_sheep` is `True` and `category` is `Mammal`. Save the results to the variable `sheep_species`." sheep_species=species[(species.is_sheep) & (species.category == 'Mammal')] # "Now merge `sheep_species` with `observations` to get a DataFrame with observations of sheep. Save this DataFrame as `sheep_observations`." sheep_observations = pd.merge(sheep_species, observations) print sheep_observations #"How many total sheep observations (across all three species) were made at each national park? Use `groupby` to get the `sum` of `observations` for each `park_name`. Save your answer to `obs_by_park`.\n", # "\n", # "This is the total number of sheep observed in each park over the past 7 days." obs_by_park=sheep_observations.groupby('park_name').observations.sum().reset_index() print obs_by_park # "Create a bar chart showing the different number of observations per week at each park.\n", # "\n", # "1. Start by creating a wide figure with `figsize=(16, 4)`\n", # "1. Start by creating an axes object called `ax` using `plt.subplot`.\n", # "2. Create a bar chart whose heights are equal to `observations` column of `obs_by_park`.\n", # "3. Create an x-tick for each of the bars.\n", # "4. Label each x-tick with the label from `park_name` in `obs_by_park`\n", # "5. Label the y-axis `Number of Observations`\n", # "6. Title the graph `Observations of Sheep per Week`\n", # "7. Plot the grap using `plt.show()`" plt.figure(figsize=(16,4)) ax=plt.subplot() y = obs_by_park.observations.values N = len(y) x = range(N) plt.bar(x, y) ax.set_xticks(range(len(y))) ax.set_xticklabels(obs_by_park.park_name.values) plt.ylabel('Number of Observations') plt.xlabel('Park Name') plt.title('Observations of Sheep per Week') plt.show() # "Our scientists know that 15% of sheep at Bryce National Park have foot and mouth disease. Park rangers at Yellowstone National # Park have been running a program to reduce the rate of foot and mouth disease at that park. The scientists want to test whether or not this program is working. # They want to be able to detect reductions of at least 5 percentage point. For instance, if 10% of sheep in Yellowstone have foot and mouth disease, # they'd like to be able to know this, with confidence.\n", # "\n", # "Use the sample size calculator at <a href=\"https://www.optimizely.com/sample-size-calculator/\">Optimizely</a> to # calculate the number of sheep that they would need to observe from each park. Use the default level of significance (90%).\n", # "\n", # "Remember that \"Minimum Detectable Effect\" is a percent of the baseline." # ] #sample size is 520 # "How many weeks would you need to observe sheep at Bryce National Park in order to observe enough sheep? 2.08 bryce=520/250. print bryce # How many weeks would you need to observe at Yellowstone National Park to observe enough sheep?" 1.02 yellowstone=520/507. print yellowstone yosemite=520/282. print yosemite smoky=520/149 print smoky
''' Polling places Evelyn Dang, Corry Ke Main file for polling place simulation ''' import sys import random import queue import click import util class Voter: def __init__(self, arrival_time, voting_duration): ''' Constructor for the Voter class Inputs: arrival_time: (float) time that voter arrives voting_duration: (int) number of minutes taken to vote ''' self.arrival_time = arrival_time self.voting_duration = voting_duration self.start_time = None self.departure_time = None class Precinct(object): def __init__(self, name, hours_open, max_num_voters, num_booths, arrival_rate, voting_duration_rate): ''' Constructor for the Precinct class Input: name: (str) Name of the precinct hours_open: (int) Hours the precinct will remain open max_num_voters: (int) Number of voters in the precinct num_booths: (int) Number of voting booths in the precinct arrival_rate: (float) Rate at which voters arrive voting_duration_rate: (float) Lambda for voting duration ''' self.name = name self.hours_open = hours_open self.max_num_voters = max_num_voters self.num_booths = num_booths self.arrival_rate = arrival_rate self.voting_duration_rate = voting_duration_rate def next_voter(self, time, percent_straight_ticket): ''' Returns the next voter in a precinct, with the start time and departure time set as None Inputs: time: (float) the time where the current voter has finished percent_straight_ticket: (float) percentage of voters voting a straight ticket Output: Voter class object, the next voter in the precinct ''' gap, voting_duration = util.gen_voter_parameters(self.arrival_rate, self.voting_duration_rate, percent_straight_ticket, straight_ticket_duration=2) next_voter = Voter(time + gap, voting_duration) return next_voter def simulate(self, percent_straight_ticket, straight_ticket_duration, seed): ''' Simulate a day of voting Input: percent_straight_ticket: (float) Percentage of straight-ticket voters as a decimal between 0 and 1 (inclusive) straight_ticket_duration: (float) Voting duration for straight-ticket voters seed: (int) Random seed to use in the simulation Output: List of voters who voted in the precinct ''' random.seed(seed) voters = [] booths = VotingBooths(self.num_booths) minutes_open = self.hours_open * 60 t = 0 for i in range(self.max_num_voters): gap, voting_duration = util.gen_voter_parameters(self.arrival_rate, self.voting_duration_rate, percent_straight_ticket, straight_ticket_duration=2) next_arrival = t + gap t = next_arrival if t >= minutes_open: break elif t == next_arrival: voter = Voter(t, voting_duration) if not booths.is_full(): booths.add_voter(voter, t, voting_duration) else: latest_departure = booths.remove_voter() if latest_departure > t: booths.add_voter(voter, latest_departure, voting_duration) else: booths.add_voter(voter, t, voting_duration) voters.append(voter) return voters class VotingBooths(object): ''' Voting booths in a precinct ''' def __init__(self, num_booths): ''' Constructor Input: num_booths: (int) the number of booths in a precinct ''' self.__pq = queue.PriorityQueue(maxsize = num_booths) def add_voter(self, voter, start_time, voting_duration): ''' Adds a voter to the booth Input: voter: (Voter) the new voter start_time: (float) time our new voter started voting voting_duration: (float) time it took the new voter to vote Output: None ''' voter.start_time = start_time voter.departure_time = start_time + voting_duration self.__pq.put(voter.departure_time, block = False) def remove_voter(self): ''' Removes a voter from the voting booth Input: None Output: (float) time of departure ''' departure_time = self.__pq.get(block = False) return departure_time def is_empty(self): ''' Check if voting booths are empty Input: None Output: (bool) ''' return self.__pq.empty() def is_full(self): ''' Check if voting booths are full Input: None Output: (bool) ''' return self.__pq.full() def find_avg_wait_time(precinct, percent_straight_ticket, ntrials, initial_seed = 0): ''' Simulates a precinct multiple times with a given percentage of straight-ticket voters. For each simulation, computes the average waiting time of the voters, and returns the median of those average waiting times. Input: precinct: (dictionary) A precinct dictionary percent_straight_ticket: (float) Percentage straight-ticket voters ntrials: (int) The number of trials to run initial_seed: (int) Initial seed for random number generator Output: The median of the average waiting times returned by simulating the precinct 'ntrials' times. ''' name = precinct['name'] hours_open = precinct['hours_open'] max_num_voters = precinct['num_voters'] arrival_rate = precinct['arrival_rate'] num_booths = precinct['num_booths'] voting_duration = precinct['voting_duration_rate'] straight_duration = precinct['straight_ticket_duration'] p = Precinct(name, hours_open, max_num_voters, num_booths, arrival_rate, voting_duration) seed = initial_seed avg_times = [] for i in range(ntrials): sim = p.simulate(percent_straight_ticket, straight_duration, seed) total_wait = 0 for voter in sim: total_wait += voter.start_time - voter.arrival_time avg_wait = total_wait / max_num_voters avg_times.append(avg_wait) seed += 1 sorted_times = sorted(avg_times) return sorted_times[ntrials // 2] def find_percent_split_ticket(precinct, target_wait_time, ntrials, seed=0): ''' Finds the percentage of split-ticket voters needed to bound the (average) waiting time. Input: precinct: (dictionary) A precinct dictionary target_wait_time: (float) The minimum waiting time ntrials: (int) The number of trials to run when computing the average waiting time seed: (int) A random seed Output: A tuple (percent_split_ticket, waiting_time) where: - percent_split_ticket: (float) The percentage of split-ticket voters that ensures the average waiting time is above target_waiting_time - waiting_time: (float) The actual average waiting time with that percentage of split-ticket voters If the target waiting time is infeasible, returns (0, None) ''' lst = list(range(11)) percent_split_ticket = [round(i * 0.1, 1) for i in lst] for percent in percent_split_ticket: percent_split = percent avg_wait_time = find_avg_wait_time(precinct, 1 - percent, ntrials, seed) if avg_wait_time > target_wait_time: break elif percent == 1 and avg_wait_time < target_wait_time: avg_wait_time = None return (percent_split, avg_wait_time) # DO NOT REMOVE THESE LINES OF CODE # pylint: disable-msg= invalid-name, len-as-condition, too-many-locals # pylint: disable-msg= missing-docstring, too-many-branches # pylint: disable-msg= line-too-long @click.command(name="simulate") @click.argument('precincts_file', type=click.Path(exists=True)) @click.option('--target-wait-time', type=float) @click.option('--print-voters', is_flag=True) def cmd(precincts_file, target_wait_time, print_voters): precincts, seed = util.load_precincts(precincts_file) if target_wait_time is None: voters = {} for p in precincts: precinct = Precinct(p["name"], p["hours_open"], p["num_voters"], p["num_booths"], p["arrival_rate"], p["voting_duration_rate"]) voters[p["name"]] = precinct.simulate(p["percent_straight_ticket"], p["straight_ticket_duration"], seed) print() if print_voters: for p in voters: print("PRECINCT '{}'".format(p)) util.print_voters(voters[p]) print() else: for p in precincts: pname = p["name"] if pname not in voters: print("ERROR: Precinct file specified a '{}' precinct".format(pname)) print(" But simulate_election_day returned no such precinct") print() sys.exit(-1) pvoters = voters[pname] if len(pvoters) == 0: print("Precinct '{}': No voters voted.".format(pname)) else: pl = "s" if len(pvoters) > 1 else "" closing = p["hours_open"]*60. last_depart = pvoters[-1].departure_time avg_wt = sum([v.start_time - v.arrival_time for v in pvoters]) / len(pvoters) print("PRECINCT '{}'".format(pname)) print("- {} voter{} voted.".format(len(pvoters), pl)) msg = "- Polls closed at {} and last voter departed at {:.2f}." print(msg.format(closing, last_depart)) print("- Avg wait time: {:.2f}".format(avg_wt)) print() else: precinct = precincts[0] percent, avg_wt = find_percent_split_ticket(precinct, target_wait_time, 20, seed) if percent == 0: msg = "Waiting times are always below {:.2f}" msg += " in precinct '{}'" print(msg.format(target_wait_time, precinct["name"])) else: msg = "Precinct '{}' exceeds average waiting time" msg += " of {:.2f} with {} percent split-ticket voters" print(msg.format(precinct["name"], avg_wt, percent*100)) if __name__ == "__main__": cmd() # pylint: disable=no-value-for-parameter
""" Added a store. The hero can now buy a tonic or a sword. A tonic will add 2 to the hero's health wherease a sword will add 2 power. """ import random import time class Character(object): def __init__(self): self.name = '<undefined>' self.health = 10 self.power = 5 self.coins = 20 def alive(self): return self.health > 0 def attack(self, enemy): if not self.alive(): return print "%s attacks %s" % (self.name, enemy.name) enemy.receive_damage(self.power) time.sleep(1.5) def receive_damage(self, points): self.health -= points print "%s received %d damage." % (self.name, points) if self.health <= 0: print "%s is dead." % self.name def print_status(self): print "%s has %d health and %d power." % (self.name, self.health, self.power) class Hero(Character): def __init__(self): self.name = 'hero' self.health = 10 self.power = 5 self.coins = 20 self.armor = 0 self.evade = 0 self.inventory = [] def restore(self): self.health = 10 print "Hero's heath is restored to %d!" % self.health time.sleep(1) def buy(self, item): if self.coins >= item.cost: self.coins -= item.cost #Store itself in the inventory instead of apply to hero #item.store_item(hero.inventory) self.inventory.append(item) else: print "Not enough coins" def attack(self, enemy): if not self.alive(): return print "%s attacks %s" % (self.name, enemy.name) crit_attack = random.randint(1,10) > 8 #crit_attack = 10 if crit_attack: print "Critical attack!" self.power = self.power*2 enemy.receive_damage(self.power) time.sleep(1.5) def receive_damage(self, points): #Each evade point deceases chance of being hit by 5% percent_chance = 100 - (self.evade * 5) #print "%s percent chance to be hit" % percent_chance if percent_chance > 90: percent_chance = 90 if random.randrange(0,100) < percent_chance: points = points - self.armor self.health -= points print "%s received %d damage." % (self.name, points) if self.health <= 0: print "%s is dead." % self.name def collect_bounty(self, enemy): print "%s collected %d coins" % (self.name, enemy.bounty) self.coins = self.coins + enemy.bounty # def store_item(self, item): # inventory.append(item) class Medic(Character): def __init__(self): self.name = 'medic' self.health = 6 self.power = 2 self.bounty = 5 def receive_damage(self, points): self.health -= points print "%s received %d damage." % (self.name, points) recuperate = random.randint(1,10) > 8 #recuperate = 10 if recuperate: print "%s recuperates 2 points of health!" % self.name self.health += 2 if self.health <= 0: print "%s is dead." % self.name class Shadow(Character): def __init__(self): self.name = 'shadow' self.health = 1 self.power = 2 self.bounty = 10 def receive_damage(self, points): dodge = random.randint(1,10) > 1 #dodge = 10 if dodge: print "%s evades attack" % self.name else: print "%s received %d damage." % (self.name, points) self.health -= points if self.health <= 0: print "%s is dead." % self.name class Zombie(Character): def __init__(self): self.name = 'zombie' self.health = 2 self.power = 2 self.bounty = 5 def alive(self): return True def receive_damage(self, points): self.health -= points print "%s received %d damage." % (self.name, points) if self.health <= 0: print "%s cannot die." % self.name class Rat(Character): def __init__(self): self.name = "rat" self.health = 1 self.power = 1 self.bounty = 1 class Ghost(Character): def __init__(self): self.name = "ghost" self.health = 2 self.power = 2 self.bounty = 2 def receive_damage(self, points): scary = random.randint(1,10) > 5 if scary: print "Boo!" points = 0 print "%s received %d damage." % (self.name, points) self.health -= points if self.health <= 0: print "%s is dead." % self.name class Goblin_King(Character): def __init__(self): self.name = 'goblin king' self.health = 40 self.power = 8 self.bounty = 20 class Goblin_Chief(Character): def __init__(self): self.name = 'goblin chief' self.health = 20 self.power = 4 self.bounty = 10 class Goblin(Character): def __init__(self): self.name = 'goblin' self.health = 10 self.power = 2 self.bounty = 5 class Wizard(Character): def __init__(self): self.name = 'wizard' self.health = 8 self.power = 1 self.bounty = 6 def attack(self, enemy): swap_power = random.random() > 0.5 if swap_power: print "%s swaps power with %s during attack" % (self.name, enemy.name) self.power, enemy.power = enemy.power, self.power super(Wizard, self).attack(enemy) if swap_power: self.power, enemy.power = enemy.power, self.power class Battle(object): def do_battle(self, hero, enemy): print "=====================" print "Hero faces the %s" % enemy.name print "=====================" while hero.alive() and enemy.alive(): hero.print_status() enemy.print_status() time.sleep(1.5) print "-----------------------" print "What do you want to do?" print "1. fight %s" % enemy.name print "2. do nothing" print "3. Use item" print "4. flee" print "> ", input = int(raw_input()) if input == 1: hero.attack(enemy) elif input == 2: pass elif input == 3: if len(hero.inventory): for i in xrange(len(hero.inventory)): item = hero.inventory[i] print "%d. %s" % (i + 1, item.name) item_number = int(raw_input("Which item to use?")) try : selected_item = hero.inventory[item_number -1] except: "print Invalid selection" try: selected_item = hero.inventory[item_number -1] #if selected_item >= len(hero.inventory): print "%s selected" % selected_item selected_item.apply(hero) hero.inventory.remove(selected_item) except: print "Invalid selection" else: print "Invalid input" else: print "Inventory empty" elif input == 4: print "Goodbye." exit(0) else: print "Invalid input %r" % input continue enemy.attack(hero) if hero.alive(): print "You defeated the %s" % enemy.name hero.collect_bounty(enemy) return True else: print "YOU LOSE!" return False class Tonic(object): cost = 5 name = 'tonic' def apply(self, character): character.health += 2 print "%s's health increased to %d." % (character.name, character.health) def __repr__(self): return "Tonic" class Sword(object): cost = 10 name = 'sword' def apply(self, hero): hero.power += 2 print "%s's power increased to %d." % (hero.name, hero.power) def __repr__(self): return "Sword" class Axe(object): cost = 15 name = 'axe' def apply(self, hero): hero.power += 4 print "%s's power increased to %d." % (hero.name, hero.power) def __repr__(self): return "Axe" class SuperTonic(object): cost = 10 name = 'super tonic' def apply(self, character): character.health = 10 print "%s's health is restored." % character.name def __repr__(self): return "Super Tonic" # class Poison(object): # cost = 10 # name = 'poison' # def apply(self, character): # character.health -= 10 # print "%s's health decreased to %d." % (character.name, character.health) # # def __repr__(self): # return "Poison" class Swap(object): cost = 5 name = 'swap' def apply(self, character): #remove enemey # hero_power = character.power # enemy_power = enemy.power # character.power = enemy_power # enemy.power = hero_power # print "%s's power is now %d!" % (hero.name, hero.power) # print "%s's power is now %d!" % (enemy.name, enemy.power) #Debug #Do an attack loop # print "hero power is %d" % hero.power # print "enemy power is %d" % enemy.power print "%s swaps power with %s during attack" % (self.name, enemy.name) hero.power, enemy.power = enemy.power, hero.power hero.attack(enemy) enemy.attack(hero) # print "hero power is %d" % hero.power # print "enemy power is %d" % enemy.power hero.power, enemy.power = enemy.power, hero.power #Add swap item to store def __repr__(self): return "Swap" class Armor(object): cost = 10 name = 'armor' def apply(self, character): character.armor += 2 print "%s's armor is increased by %d" % (hero.name, hero.armor) def __repr__(self): return "Armor" class Evade(object): cost = 10 name = 'evade' def apply(self, character): character.evade += 2 print "%s's evade is increased by %d" % (hero.name, hero.evade) def __repr__(self): return "Evade" class Store(object): # If you define a variable in the scope of a class: # This is a class variable and you can access it like # Store.items => [Tonic, Sword] items = [Tonic, Sword, Axe, SuperTonic, Armor, Evade, Swap] def do_shopping(self, hero): while True: print "=====================" print "Welcome to the store!" print "=====================" print "You have %d coins." % hero.coins print "What do you want to do?" for i in xrange(len(Store.items)): item = Store.items[i] print "%d. buy %s (%d)" % (i + 1, item.name, item.cost) print "8. Use Item" print "9. Check Inventory" print "10. leave" input = int(raw_input("> ")) #Use item in store if input == 8: if len(hero.inventory): #Original inventory choosing # for item in hero.inventory: # print item for i in xrange(len(hero.inventory)): item = hero.inventory[i] print "%d. %s" % (i + 1, item.name) item_number = int(raw_input("Which item to use?")) try : selected_item = hero.inventory[item_number -1] except: "print Invalid selection" try: selected_item = hero.inventory[item_number -1] #if selected_item >= len(hero.inventory): print "%s selected" % selected_item selected_item.apply(hero) hero.inventory.remove(selected_item) except: print "Invalid selection" else: print "Invalid input" else: print "Inventory empty" #Check inventory in store elif input == 9: for item in hero.inventory: print item elif input == 10: break else: ItemToBuy = Store.items[input - 1] item = ItemToBuy() hero.buy(item) hero = Hero() #enemies = [Goblin(), Wizard()] enemies = [Rat(), Goblin(), Wizard(), Medic(), Goblin_Chief(), Goblin_King()] #Inventory Checking #free_tonic = Tonic() #hero.inventory.append(free_tonic) battle_engine = Battle() shopping_engine = Store() for enemy in enemies: hero_won = battle_engine.do_battle(hero, enemy) if not hero_won: print "YOU LOSE!" exit(0) shopping_engine.do_shopping(hero) print "YOU WIN!"
# age = int(input("Enter your age: ")) # if age >= 18: # print("You are of age") # else: # print("You are a minor") # password = "456m789D123".lower() # ask_password = str(input("Enter your password: ")).lower() # if password == password1: # print("Valid password") # else: # print("Invalid password") # number_1 = float(input("Write a number: ")) # number_2 = float(input("Write another number: ")) # if number_2 == 0: # print("Error") # else: # print("The result of the division is", number_1 / number_2) # whole_number = int(input("Enter a whole number: ")) # whole: entero -> numero entero # if whole_number % 2 == 0: # print("The number " + str(whole_number) + " is even") # El numero es par # else: # print("The number " + str(whole_number) + " is odd") # El numero es impar # age = int(input("What is your age?: ")) # income = int(input("What is your income?: ")) # if age >= 16 and income >= 1000: # junto dos condiciones con and # print("You can to acces, welcome!") # else: # print("You can't to access") # name = input("What's your name? ").lower() # gender = input("What's your gender? F or M: ").lower() # gender: female(f) or male(m) # if name < "m" and gender == "f": # print("Group: A") # elif name > "n" and gender == "m": # print("Group: A") # else: # print("Group: B") # annual_rent = float(input("¿What's your annual rent?: ")) # if annual_rent < 10000: # print("Tax rate: 5%") # elif annual_rent >= 10000 and annual_rent < 20000: # print("Tax rate: 15%") # elif annual_rent >= 20000 and annual_rent < 35000: # print("Tax rate: 20%") # elif annual_rent >= 35000 and annual_rent < 60000: # print("Tax rate: 30%") # elif annual_rent >= 60000: # print("Tax rate: 45%") # else: # print("Error") # user_score = float(input("What's your score?: ")) # score: puntuacion # unacceptable = 0.0 # variables que guardan un valor # acceptable = 0.4 # meritorious = 0.6 # money = 2400 # if user_score >= unacceptable and user_score < acceptable: # print(f'The score is unacceptable and you salary is {money}') # elif user_score >= acceptable and user_score < meritorious: # print(f'The score is acceptable and you salary is {(money * acceptable) + money}') # elif user_score >= meritorious: # print(f'The score is meritorious and you salary is {(money * meritorious) + money}') # else: # print("Error") # age_user = int(input("What's your age?: ")) # if age_user < 4: # print("You can to entrance free") # Puedes entrar gratis # elif age_user >= 4 and age_user < 18: # print("You must to pay 5€") # Debes pagar 5€ # else: # print("You must to pay 10€") # Debes pagar 10€ """ Welcome to the pizza shop Bella Napoli! We have two types of pizzas: 1-Vegetarian pizza 2-Non-vegetarian pizza """ pizza = int(input("Enter an option: ") if pizza == 1: print("You chose a vegetarian pizza") ingredient = input("Enter the ingredient you want") print("")
# Task # A Node class is provided for you in the editor. A Node object has an integer data field,data, and a Node instance pointer,next , # pointing to another node (i.e.: the next node in a list). # # A removeDuplicates function is declared in your editor, which takes a pointer to the head node of a linked list as a parameter. # Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list. # # Note: The head pointer may be null, indicating that the list is empty. Be sure to reset your next pointer when performing deletions # to avoid breaking the list. # # Input Format # # You do not need to read any input from stdin. The following input is handled by the locked stub code and passed to the # removeDuplicates function: # The first line contains an integer,N , the number of nodes to be inserted. # The N subsequent lines each contain an integer describing the data value of a node being inserted at the list's tail. # # Constraints # The data elements of the linked list argument will always be in non-decreasing order. # Output Format # # Your removeDuplicates function should return the head of the updated linked list. The locked stub code in your editor will print the returned list to stdout. class Node: def __init__(self, data): self.data = data self.next = None class Solution: def insert(self, head, data): p = Node(data) if head == None: head = p elif head.next == None: head.next = p else: start = head while (start.next != None): start = start.next start.next = p return head def display(self, head): current = head while current: print(current.data, end=' ') current = current.next def removeDuplicates(self, head): # Write your code here if head == None: return head fptr = head.next sptr = head ha = {} while fptr != None: if sptr.data not in ha: ha[sptr.data] = True if fptr.data in ha: sptr.next = fptr.next fptr = fptr.next continue sptr = fptr fptr = fptr.next return head mylist = Solution() T = int(input()) head = None for i in range(T): data = int(input()) head = mylist.insert(head, data) head = mylist.removeDuplicates(head) mylist.display(head);
# Given a base-10 integer,n , convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of # consecutive 1's in n's binary representation. if __name__ == '__main__': n = int(input()) rmd = [] while n > 0: rm = n % 2 n = n // 2 rmd.append(rm) count, result = 0, 0 for i in range(0, len(rmd)): if rmd[i] == 0: count = 0 else: count += 1 result = max(result, count) print(result)
# Printing the Number of Swaps taken and also the first and last element of an array sorted using Bubble Sort. n = int(input().strip()) a = list(map(int, input().strip().split(' '))) # Write Your Code Here swaps = 0 for i in range(len(a)): for j in range(1, len(a)): if a[j - 1] > a[j]: swaps += 1 a[j - 1], a[j] = a[j], a[j - 1] print(f'Array is sorted in {swaps} swaps.') print('First Element:', a[0]) print('Last Element:', a[-1])
import sys import time import RPi.GPIO as GPIO import datetime import w1thermsensor import os os.system('modprobe w1-gpio') os.system('modprobe w1-therm') # Note GPIO module uses Physical PIN as reference. Physical PINs are numbered in order # Note Adafruit_DHT uses BCM PIN as reference. BCM PINs are the numbers on the breakout board. # Setup Sensor sensor = w1thermsensor.W1ThermSensor(w1thermsensor.W1ThermSensor.THERM_SENSOR_DS18B20, "00152213a7ee") # Create Loop to get temperature while True: # Uncomment if you want to sleep n seconds between each reading - must put value for n #time.sleep(n) # Note: The time is the time in which the Raspberry Pi receives the data. # This means there could be delay between when the data is read from the sensor and the time stamp. # For our application, this difference is negligible. temperature = sensor.get_temperature(w1thermsensor.W1ThermSensor.DEGREES_F) timeStamp = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] # Format strings print(timeStamp + ' ' + str(temperature))