text
stringlengths
37
1.41M
import math def primechecker(number): t = False for i in range(2,number): if number%i==0: t = True break if t==True: print(str(number)+" is not a prime") else: print(str(number)+" is a prime") n = int(input()) final = False for i in range(2,n): primechecker(i)
principal = float(input("Enter Principal P > ")) rate = int(input("Enter the rate R > ")) time = int(input("Enter the time T > ")) simple_interest = (principal * rate * time) / 100 print("The Simple Interest is {}".format(simple_interest))
#!/usr/bin/python # # オブジェクトとクラス # # class によるクラスの定義 class Nothing(): # 空のクラス pass someone = Nothing() # NothingPerson インスタンスの生成 class NothingToInit(): # コンストラクタをもつクラス def __init__(self): # コンストラクタ pass class Person(): def __init__(self, name): # コンストラクタで引数 name を受け取る self.name = name # self.name でこのクラスの属性 name に値を設定 hunter = Person('Elmer Fudd') # Person のインスタンス生成 print(hunter.name) # 属性 name にアクセス # 継承 class Car(): def exclaim(self): print("I'm a Car!") class Yugo(Car): # Car クラスを継承 def exclaim(self): # メソッドのオーバーライド print("I'm Yugo! Much like a Car, but more Yugo-ish.") Car().exclaim() # Car の exclaim が呼ばれる Yugo().exclaim() # Yugo の exclaim が呼ばれる class MDPerson(Person): # 医者 def __init__(self, name): # コンストラクタをオーバーライド self.name = "Doctor " + name class JDPerson(Person): # 弁護士 def __init__(self, name): # コンストラクタをオーバーライド self.name = name + ", Esquire" person = Person('Fudd') doctor = MDPerson('Fudd') lawyer = JDPerson('Fudd') print(person.name, doctor.name, lawyer.name) # メソッドの追加 class CarOfYugo(Car): def exclaim(self): print("I'm Yugo! Much like a Car, but more Yugo-ish.") def need_a_push(self): # Car クラスにはないメソッドの追加 print("A little help here?") CarOfYugo().need_a_push() # 親クラスのメソッドの呼び出し(super) class EmailPerson(Person): def __init__(self, name, email): super().__init__(name) # 親クラス(Person)のコンストラクタを呼び出す self.email = email bob = EmailPerson('Bob Frapples', '[email protected]') print(bob.name, bob.email) # プロパティによる属性値のカプセル化 class Duck(): def __init__(self, input_name): self.hidden_name = input_name def get_name(self): # ゲッターメソッド print('inside the getter') return self.hidden_name def set_name(self, input_name): # セッターメソッド print('inside the setter') self.hidden_name = input_name name = property(get_name, set_name) # name プロパティのゲッター、セッターとして定義 fowl = Duck('Howard') print(fowl.name) # get_name ゲッターメソッドを呼び出す fowl.name = 'Daffy' # set_name セッターメソッドを呼び出す print(fowl.name) # Daffy class DecoratedDuck(): def __init__(self, input_name): self.hidden_name = input_name @property # ゲッターをデコレータで定義 def name(self): print('inside the getter') return self.hidden_name @name.setter # セッターをデコレータで定義 def name(self, input_name): print('inside the setter') self.hidden_name = input_name fowl = DecoratedDuck('Howard') print(fowl.name) # ゲッターの呼び出し fowl.name = 'Donald' # セッターの呼び出し print(fowl.name) # Donald class Circle(): def __init__(self, radius): self.radius = radius @property # ゲッターをデコレータで定義 def diameter(self): return 2 * self.radius c = Circle(5) print(c.radius) # radius 値は初期化されている print(c.diameter) # diameter のゲッターが呼ばれる c.radius = 7 print(c.diameter) # diameter は radius の値によって変わる try: c.diameter = 20 # セッターは指定されてないので値は設定できない! except AttributeError as err: print("can't set attribute") # 非公開属性のための名前のマングリング class HiddenDuck(): def __init__(self, input_name): self.__name = input_name # 先頭にふたつのアンダースコア(__)を付けると非公開属性 @property # ゲッターを設定 def name(self): print('inside the getter') return self.__name @name.setter # セッターを設定 def name(self, input_name): print('inside the setter') self.__name = input_name try: HiddenDuck('Howard').__name except AttributeError as err: print('\'HiddenDuck\' object has no attribute \'__name\'') # メソッドのタイプ class A(): __count = 0 # クラス属性(かつ非公開) def __init__(self): A.__count += 1 # このクラスが生成された数を数える def exclaim(self): print("I'm an A!") @classmethod # クラスメソッド def kids(cls): print("A has", cls.__count, "little objects.") easy_a = A() breezy_a = A() Wheezy_a = A() A.kids() # 3つ生成した class CoyoteWeapon(): @staticmethod # 静的メソッド(クラスにもオブジェクトにも影響を与えない) def commercial(): print('This CoyoteWeapon has been brought to you by Acme') CoyoteWeapon.commercial() # ダックタイピング(ポリモーフィズムの緩やかな実現) class Quote(): def __init__(self, person, words): self.__person = person self.__words = words @property def person(self): return self.__person @property def words(self): return self.__words def who(self): return self.person def says(self): return self.words + '.' class QuestionQuote(Quote): # __init__がないときは親クラスのものを呼び出す def says(self): # ポリモーフィズムの実現 return self.words + '?' class ExclamationQuote(Quote): def says(self): # ポリモーフィズムの実現 return self.words + '!' def who_says(hunter): print(hunter.who(), 'says:', hunter.says()) # says() メソッドが異なる動作 who_says(Quote('Elmer Fudd', "I'm hunting wabbits")) who_says(QuestionQuote('Bugs Bunny', "What's up, doc")) who_says(ExclamationQuote('Daffy Duck', "It's rabbit season")) class BabblingBrook(): # Quote とはまるで関係ないクラス def who(self): return 'Brook' def says(self): return 'Babble' who_says(BabblingBrook()) # 共通のインターフェースなら継承すら必要ない(ダックタイピング) # 特殊メソッド class Word(): def __init__(self, text): self.text = text def __eq__(self, word2): # 2つの単語を比較する特殊メソッドの実装(==) return self.text.lower() == word2.text.lower() first = Word('ha') second = Word('HA') third = Word('eh') print(first == second) # True print(first == third) # False # 比較のための特殊メソッド equal = { '==': '__eq__(self, other)', '!=': '__ne__(self, other)', '<': '__lt__(self, other)', '>': '__qt__(self, other)', '<=': '__le__(self, other)', '>=': '__ge__(self, other)', } # 算術演算のための特殊メソッド calc = { '+': '__add__(self, other)', '-': '__sub__(self, other)', '*': '__mul__(self, other)', '//': '__floordiv(self, other)', '/': '__truediv__(self, other)', '%': '__mod__(self, other)', '**': '__pow__(self, other)', } # その他の特殊メソッド other = { 'str(self)': '__str__(self)', 'repr(self)': '__repr__(self)', 'len(self)': '__len__(self)', } class MagicWord(): def __init__(self, text): self.text = text def __eq__(self, word2): return self.text.lower() == word2.text.lower() def __str__(self): return self.text def __repr__(self): return 'Word("' + self.text + '")' first = MagicWord('ha') first # 対話型インタプリンタは __repr__ をエコー出力する print(first) # __str__ を使う # コンポジション class Bill(): # くちばし def __init__(self, description): self.description = description class Tail(): # しっぽ def __init__(self, length): self.length = length class Duck(): # アヒルはくちばしとしっぽを持つ( has-a の関係) def __init__(self, bill, tail): self.bill = bill self.tail = tail def about(self): print('This duck has a', self.bill.description, 'bill and a', self.tail.length, 'tail') tail = Tail('long') bill = Bill('wide orange') duck = Duck(bill, tail) # くちばしとしっぽをもつアヒルの生成 duck.about() # 説明を表示 # 名前付きタプル def named_tuple(): # 名前付きタプルはイミュータブルな値オブジェクトのように振る舞う from collections import namedtuple Duck = namedtuple('Duck', 'bill tail') # 名前とフィールド名(空白区切りで設定) duck = Duck('wide orange', 'long') # bill='wode orange', tail='long' print(duck) print(duck.bill) # bill フィールド print(duck.tail) # tail フィールド parts = {'bill': 'wide orange', 'tail': 'long'} duck2 = Duck(**parts) # 辞書をキーワード引数として渡せる print(duck2) duck3 = duck2._replace( tail='magnificent', bill='crushing') # フィールドを更新した別のタプルの生成 print(duck3) named_tuple()
import random chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' l=int(input("Enter password length: ")) n=int(input("Enter number of passwords: ")) for i in range(n): password='' for j in range(l): password+=random.choice(chars) print(password)
# 集合(set)是一个无序的不重复元素序列。 # 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。 # 然后 是集合之间的一些运算 # 交叉并补 # 1. 集合的基本操作 s={1,1,2,3,4,2} print(s) s.add(5) print(s) s.remove(5) print(s) s.pop() print(s) print(len(s))
# 1. 列表切片 # 2. 更新列表 # list=['Google', 'Runoob', 1997, 2000] # 2.1 更改列表某个元素 # print(list) # list[0]="baidu" # print(list) # 2.2 往列表中增加元素 # list.append("sougou") # print(list) # 2.3 删除列表中某个元素 # print(list) # del list[2] # print(list) # 3. 列表同时也支持 拼接,重复,截取 # 4. 也可嵌套 # list=[['a', 'b', 'c'], [1, 2, 3]] # print(list[0][1]) # 5. 然后常用的函数 和 内建方法 要注意一下 list=[1,2,3,3,4] # print(len(list)) # print(max(list)) # list.append(6) # print(list) # print(list.count(3)) # list2=[5,6,7,8] # list.extend(list2) # print(list) # print(list.index(3)) # list.insert(0,99) # print(list) # list.pop() # print(list)
age=int(input("请输入你家狗狗的年龄:")) # 这里 if age<=0: print("erro!") elif age==1: print("相当于 14 岁的人。") elif age==2: print("相当于 22 岁的人。") elif age>2: human=22+(age-2)*5 print("对应人类年龄: ",human) # 判断 input 默认设置的数据类型 inp=input("输入一个数,判断 input 默认设置的数据类型:") print(type(inp)) # 默认是 字符串
import os from math import factorial from itertools import permutations def borrarPantalla(): #Definimos la función estableciendo el nombre que queramos if os.name == "posix": os.system ("clear") elif os.name == "ce" or os.name == "nt" or os.name == "dos": os.system ("cls") def getFileName(): salir = False fileWithWords = '' while not salir: borrarPantalla() print("-> Santiago S.R. ([email protected]) <-") print("*** Words permutation ***\n".upper()) fileWithWords = input("Filename with words to load ? ") if fileWithWords == '' or os.path.isfile(fileWithWords): salir = True else: print("The file ["+ fileWithWords + "] NO EXISTS. Please, check!!") input("Press 'Enter', please ") return fileWithWords def main(): # info() ---> Falta sacar info de como debe ser el fichero con las palabras fileName = getFileName() if fileName == '': print("Thanks for using my program!! Bye") exit(0) print("Loading words from file [" + fileName + "]...") arrWords = [] with open(fileName) as file: arrWords = file.readline().rstrip("\n").split(' ') print("Loaded!") finalPermutations = permuteWords(arrWords) showResults(finalPermutations) print("\n*** End !! ***") def permuteWords(arrWordsToPermute): wordsToPermute = [] arrWordsBlocked = [] totError = 0 # For each word in array search and separate blocked words for word in arrWordsToPermute: if len(word) > 3: if word[0:1] == '*': # Word blocked arrWordsBlocked.append(word[1:]) else: wordsToPermute.append(word) arrWordsBlocked.append('') else: totError += 1 print("\nTotal Words\t: ", len(arrWordsToPermute)) print("Blocked\t\t: ", len(arrWordsToPermute)-len(wordsToPermute)-totError) print("To permute \t: ", len(wordsToPermute)) if totError > 0: print("Found {} wrong words".format(totError)) totPermutations = factorial(len(wordsToPermute)) if totPermutations > 700: print("\n*** With this info, will be {} permutacions!!".format(totPermutations)) resp = input("Are you sure (y/N) ? ").lower() if resp == 's' or resp == 'y': print("\n*** Calculating permutations... be patient, please!") else: print("Aborting!!, See you soon") exit(0) arrFinal = [] for permutation in permutations(wordsToPermute): i = 0 tmpArray = [] for word in arrWordsBlocked: if word== '': tmpArray.append(permutation[i]) i += 1 else: tmpArray.append(word) arrFinal.append(tmpArray) print("\n*** Calculated {} permutations with {} words permuted. Thanks for your waiting!".format(totPermutations, len(wordsToPermute))) return arrFinal def showResults(finalArray): row = 1 for combination in finalArray: print("\n#{:02d}".format(row), end='-> ') for word in combination: print("{}".format(word), end=" ") row += 1 ## MAIN function if __name__ == '__main__': main()
#coding UTF-8 #Тренировочная программа-игра для отработки навыков написания кода Python import random import sys print('Здравствуйте! Пожалуйста, отгадайте число, загаданное мной.') print('') def game_main(): a = random.randint(1, 100) def int_check(): x = int(input('Какое число я загадал? ')) if x > a: print('Меньше!') int_check() elif x < a: print('Больше!') int_check() else: print('Угадали!!!') b = input('Сыграем ещё? Y/N ') if b == 'Y': game_main() else: sys.exit() game_main() int_check() game_main()
def init(newWord): letterIn = input("Type your guess (1 letter or character): ") #ask for a letter and capture input #loop through string to see if letter is in string word = newWord["newWord"] length = newWord["numOfChar"] error = 0 for i in word: if letterIn == word[i]: index = i print(i) else: error = error + 1 if (error > 0): pointDeduct = True print("Your guess us incorrect!") else: pointDeduct = False print("Your guess is correct!") return pointDeduct
# 1. Map = fungsi map berlaku ke semua items dalam sebuah input_list # sintaks = map(function_to_apply, list_input) # contoh : # biasanya kita ingin pass semua list elemen ke sebuah fungsi satu-demi-satu dan mengambil output item = [1,2,3,4,5] square = [] for i in item: square.append(i**2) print square print '\n' # map memperbolehkan kita meng-implement fungsi ini dengan lebih mudah dan lebih baik items = [1,2,3,4,5] squared = list(map(lambda x: x**2, items)) print squared #hasil sama print '\n' # contoh untuk list_function def multiply(x): return (x*x) def add(x): return (x+x) func = [multiply, add] for a in range(5): value = list(map(lambda x:x(a), func)) print value print '\n' # 2. Filter = membuat sebuah list elemen untuk sebuah fungsi yg mengembalikan nilai True # contoh number_list = range(-5,5) less_than_zero = list(filter(lambda x:x<0, number_list)) print less_than_zero #hasil mengembalikan semua list elemen yg kurang dari 0 (True) print '\n' # 3. Reduce = fungsi yg sangat berguna untuk perform beberapa komputasi dalam sebuah list dan mengembalikan hasil. # itu berlaku perhitungan bergulir untuk pasangan nilai berurutan dalam daftar. contoh jika ingin mengkomputasi # produk dalam sebuah list integer # normal way product = 1 my_list = [1,2,3,4] for num in my_list: product *= num print product #reduce from functools import reduce product = reduce((lambda x, y: x*y), [1,2,3,4]) print product print '\n'
def add_to(num, target=[]): #ingat list harus dibelakang target.append(num) return target add_to(1) def add_to2(element, target2=None): if target2 is None: target2 = [] target2.append(element) return target2 add_to2(3)
#汉诺塔移动 #汉诺塔游戏的规则是三根柱子,其中一个柱子上有从下往上从大到小的N个罗盘,每次移动1个罗盘,其中大罗盘不能放在小罗盘之上,最后把罗盘从A柱移动B柱。 #分别用递归函数或者循环的方式去实现 #使用递归函数去解决,递归函数就是要找到逻辑关系 #1.假设有A,B,C三根柱子,罗盘初始在A柱上,最后有移动到C柱。我们首先要想办法把最下面最大的罗盘移动到C柱上,这个时候B柱上有N-1个罗盘,A柱上没有罗盘,C柱上有一个最大的罗盘。 #2.这个问题此刻又变成了将B柱上的N-1个罗盘移动到C柱,这本身就形成了一种递归。 #综合上面的分解,把汉诺塔拆解成散步,第一步将n-1个盘子移动到B柱上,第二步将A柱上的罗盘移动到C柱上,第三部将n-1个罗盘移动到C柱上 move_count = 0 def hanoi(n,a,b,c):#n表示有n个罗盘 global move_count#python由于没有变量声明,所以变量的作用于为赋值的区域,如果不加global关键字,那么move_count变量会被认为是函数内变量。 # 那么move_count = move_count + 1表达式会直接报错"reference before assigment" if n==1: move_count = move_count + 1 print(a,'->',c)#如果只有一个罗盘,那就直接从A移动到C return 'done' else: hanoi(n-1,a,c,b) hanoi(1,a,b,c) hanoi(n-1,b,a,c) hanoi(3,'A','B','C') print('移动的次数为:',move_count) #使用非递归的方式进行实现
#----------------------------------------------------------------------------- # Name: Word Guessing Game.py # Purpose: Make a hangman type game # # Author: Daniel # Created: 07-Oct-2020 # Updated: 14-Oct-2020 #----------------------------------------------------------------------------- # I think this project deserves a 4 because... # #Features Added: #Added a twist to the triditional hangman, when the user guesses a correct letter they gain back a life and the #hang man animation will lose a body part. (while I'm writting this I realized gaining body parts for losing makes no sense #I'm going to change it so they lost a body part if they guess wrong and gain back one if they are correct...makes more sense. #Played around with unicode so I didn't need to type out every letter. #Added an AI for the user to compete with (if these brackets are here I may have forgot to edit this and I have not # been able to add an AI -> if the case ignore this feature) # # WIDTH = 800 #these are constant values so we use all ca HEIGHT = 600 import random gameState = '' run = True imageStatus = 0 letter = '' guessedLetter = [] lives = 7 xDisplayWord = 80 #colors yellow = (246,255,59) purple = (169,111,224) lightgreen = (105,230,145) sand = (239,160,105) #picking a random word from my secret words lists wordList = ["laptop", "blizzard" , "galaxy", "matrix" , "sunday", "mystify", "unknown", "yummy", "saturn", "canada", "oakville", "hospital", "computer", "firetruck", "github", "binder", "python", "october", "escape", "advanced", "monday", "pygame"] #this did not work when I put it in a function #I searched it up countless times and I was wasting a lot of time #so I just left it here, out side of a function secretWord = (random.choice(wordList)) numLettersInWordList = len(secretWord) print (secretWord) print (numLettersInWordList) hangman = Actor("hangman0") hangman.pos = (600,150) hangman.frame = 0 #start button button1Draw = [300, 400, 200, 50] button1Rect = Rect(button1Draw) button1Value = False button1Color = 'green' #game page exit button button2Draw = [680, 560, 80, 30] button2Rect = Rect(button2Draw) button2Value = False button2Color = (230,187,173) #rules button button3Draw = [320, 460, 160, 40] button3Rect = Rect(button3Draw) button3Value = False button3Color = (255, 250, 205) #start-up def startUp(): '''Run this to get the program ready to run''' global gameState gameState = 'start screen' #def secretWord(): #global wordList, numLettersInWordList def updateHangman(): '''updates the hangman image''' global hangman if hangman.frame > 6: hangman.frame = 0 hangman.image = 'hangman' + str(hangman.frame) def on_key_down(unicode): global letter, numLettersInWordList, secretWord, guessedLetter, lives, gameState, hangman '''this function checks the player input (gussed letter)''' if gameState == 'game': if unicode.isalpha(): if unicode in (secretWord): if unicode in (guessedLetter): '''avoid printing the same letter twice on the list''' print("You already guessed that letter") letter = unicode else: ''' check to see if the letter chosen is in the word''' #guessedLetter = (unicode) print("correct!") guessedLetter.append(unicode) print(unicode) print(guessedLetter) letter = unicode '''gives an extra life for correct guesses, but they can't have more than 7 lives ''' if lives < 7: lives += 1 hangman.frame -= 1 updateHangman() else: if unicode in (guessedLetter): '''avoid printing the same letter twice on the list''' print("You already guessed that letter") letter = unicode else: '''finally if the letter is not in the word, we tell them to try again and we add the letter to the list aswell to avoid duplications''' print("That letter in not in the word, please try again") guessedLetter.append(unicode) letter = unicode lives -= 1 hangman.frame += 1 updateHangman() if lives == 0: gameState = 'end' else: print("Opps, numbers and symbols are not valid") #buttons def on_mouse_up(pos, button): '''Pygame Special Event Hook - Runs when the mouse button is released''' global button1Color global button1Value global button2Value global button2Color global button3Color global button3Value global gameState if button1Rect.collidepoint(pos): '''Start game button''' if button1Value == True: button1Color = 'light green' button1Value = False gameState = 'game' else: button1Color = 'green' button1Value = True gameState = 'game' elif button2Rect.collidepoint(pos): '''Exit game button''' if button2Value == True: button2Color = (230,187,173) button2Value = False gameState = 'start screen' else: button2Value = True gameState = 'start screen' elif button3Rect.collidepoint(pos): '''Rules button''' if button3Value == True: button3Color = (255, 250, 205) button3Value = False gameState = 'rules' else: button3Value = True gameState = 'rules' #Draw def draw(): global gameState, numLettersInWordList, guessedLetter, unicode, letter, yellow, lives, xDisplayWord if gameState == 'start screen': '''landing page''' if gameState == "start screen": screen.clear() screen.fill((212, 235, 250)) screen.draw.text("Hello, Welcome To My Program", center=(WIDTH/2, HEIGHT/2), color="hotpink", fontsize=45) screen.draw.text("Still In The Making Though...", center=(WIDTH/2, 330), color="red") screen.draw.filled_rect(button1Rect, button1Color) screen.draw.text("Click To Start", center=(400,425), color="blue", fontsize = 32) screen.draw.filled_rect(button3Rect, button3Color) screen.draw.text("Rules", center=(400,480), color=(255,102,102), fontsize = 32) elif gameState == 'game': letterDisplay = " " '''the actual game''' screen.clear() screen.fill((173, 230, 187)) hangman.draw() screen.draw.filled_rect(button2Rect, button2Color) screen.draw.text("Exit", center=(720,575), color="Red", fontsize = 32) screen.draw.text(numLettersInWordList*'_ ', (100,300), color="black", fontsize=80) screen.draw.text((str(guessedLetter)), center=(200,100), color="Red", fontsize = 20) screen.draw.text("Lives left: " + (str(lives)), center=(100,50), color="hotpink", fontsize = 40) '''printing correctly gussed letters on screen''' for i in range(len(secretWord)): '''displaying correctly guessed letters on screen''' if secretWord[i] in guessedLetter: #print the letter letterDisplay += secretWord[i] + " " screen.draw.text(letterDisplay , (xDisplayWord,290), color = "black", fontsize = 80) if letterDisplay == secretWord: screen.draw.text(" You Won!", (400,300), color = "black", fontsize = 80) else: screen.draw.text(" ", (100,305), color = "black", fontsize = 32) # if letter in secretWord: # if numLettersInWordList in range(len(secretWord)): # print(numLettersInWordList[i]) # screen.draw.text(letter, (100,305), color = "black", fontsize = 32) # elif lives == 0: # gameState == 'end' #images = [] #for i in range(5): #image = image.load("witch" + str(i) + ".png") #images.append(image) elif gameState == 'end': '''take users to this screen if they lost''' screen.clear() screen.fill((173, 230, 187)) screen.draw.filled_rect(button2Rect, button2Color) screen.draw.text("Exit", center=(720,575), color="Red", fontsize = 32) screen.draw.text("Oh No!", center=(400,100), color="red", fontsize = 100) screen.draw.text("Looks Like You've Run Out Of Lives", center=(400,170), color="orange", fontsize = 60) screen.draw.text("Click the exit button to restart", center=(400,250), color=(yellow), fontsize = 70) elif gameState == 'win': '''take user to this screen if they win''' screen.clear() screen.fill(lightgreen) screen.draw.filled_rect(button2Rect, button2Color) screen.draw.text("Exit", center=(720,575), color="Red", fontsize = 32) screen.draw.text("Oh No!", center=(400,100), color="red", fontsize = 100) screen.draw.text("Looks Like You've Run Out Of Lives", center=(400,170), color="orange", fontsize = 60) screen.draw.text("Click the exit button to restart", center=(400,250), color=(yellow), fontsize = 70) elif gameState == 'rules': '''rules screen''' screen.clear() screen.fill(purple) screen.draw.filled_rect(button2Rect, button2Color) screen.draw.text("Exit", center=(720,575), color="Red", fontsize = 32) screen.draw.text("The Rules Are Simple", center=(400,100), color=(yellow), fontsize = 80) screen.draw.text ("Guess The Secret Word...", center=(WIDTH/2, 200), color=(lightgreen)) screen.draw.text ("Before The AI Gusses Your Word!", center=(WIDTH/2, 230), color=(lightgreen)) screen.draw.text ("You May Use Any Word, Or Even A Mix Of Letters", center=(WIDTH/2, 260), color=(lightgreen)) screen.draw.text ("However, You Can Only Use Up To 6 Letters", center=(WIDTH/2, 290), color=(lightgreen)) screen.draw.text ("In Addition To Who Guesses The Word The Fastest", center=(WIDTH/2, 320), color=(lightgreen)) screen.draw.text ("If You Guess 5 Wrong Letters You Will Automatically Lose", center=(WIDTH/2, 350), color=(lightgreen)) screen.draw.text ("Numbers And Symbols Are Not Valid", center=(WIDTH/2, 380), color=(lightgreen)) screen.draw.text("Good Luck!", center=(400,500), color=(sand), fontsize = 80) else: '''check for errors''' screen.fill((255, 204, 203)) screen.draw.text ("Something is wrong", center=(WIDTH/2, HEIGHT/2), color="red") #need help with making the whole game into a loop print (secretWord) startUp()
# -*- coding: utf-8 -*- """ Created on Sat Jan 18 17:00:12 2020 @author: rober """ from enum import Enum class Type(Enum): INT = 'INT' STR = 'STR' BOOL = 'BOOL' class Null(Enum): NULL = 'NULL' class Node: def __init__(self, node_func, value=None, input_nodes=None, is_input=False, is_output=False): self.node_func = node_func self.input_nodes = input_nodes[:] if input_nodes else [] self.is_input = False self.is_output = False self.value = value self.has_value = self.value != None def get_value(self, force_eval=False): if self.has_value: return self.value #If every input node has its value if max([node.has_value for node in self.input_nodes]): values = [node.get_value() for node in self.input_nodes] self.value = self.node_func(*values) if self.value != None: self.has_value = True return self.value if force_eval: values = [node.get_value(force_eval=True) for node in self.input_nodes] self.value = self.node_func(*values) if self.value != None: self.has_value = True return self.value return None class NodeFunc: def __init__(self, func, symbol, in_types, out_types): self.func = func self.symbol = symbol[:] self.in_types = in_types[:] self.out_types = out_types[:]
from math import ceil, floor, sqrt def simpRootFrac(num, root, intd): # takes in a numerator, and the two parts of the irrational root # simplify by mutliplying by the conjugate # returns whole number, plus 3 parts of remaining fraction. newIntNum = -intd newDenom = root - intd * intd newDenom //= num approximation = floor((newIntNum + sqrt(root)) / newDenom) newIntNum -= approximation * newDenom return (approximation, newIntNum, newDenom) def hasOddPeriod(n): approximation = floor(sqrt(n)) newBlock, newIntNum, newIntDenom = simpRootFrac(1, n, -approximation) seen = {(newBlock, newIntNum, newIntDenom),} period = 0 while True: period += 1 seen.add((newBlock, newIntNum, newIntDenom)) newBlock, newIntNum, newIntDenom = simpRootFrac(newIntDenom, n, newIntNum) if (newBlock, newIntNum, newIntDenom) in seen: break return period % 2 == 1 if __name__ == "__main__": highest = 10_000 squares = {n * n for n in range(ceil(sqrt(highest)) + 1)} # squares are all the things to avoid because they don't give continued fractions total = 0 for n in range(2, highest + 1): if n not in squares: total += hasOddPeriod(n) print(total)
def is_sum_of_pows(num, pow): total = 0 s_num = str(num) for d in s_num: total += int(d) ** pow return total == num fith_nums = [] for n in range(10, 1000000): if is_sum_of_pows(n, 5): fith_nums.append(n) print(sum(fith_nums))
from math import sqrt def is_pent(n): N = (1 + sqrt(24 * n + 1)) / 6 return N % 1 == 0 def is_tri(n): N = (sqrt(8 * n + 1) - 1) / 2 return N % 1 == 0 h = 144 while True: H = h * (2 * h - 1) if is_tri(H) and is_pent(H): print(H) break h += 1
from functools import cache from sympy import primerange @cache def count_decreasing_prime_sums(n, max=None): if n == 1: return 0 if n == 2: return 1 max = max or n total = 0 for first_addend in primerange(2, min(max + 1, n)): total += count_decreasing_prime_sums(n - first_addend, first_addend) if n <= max > 1: return total + 1 # adds one to account for the option of not breaking up further into sums return total n = 2 while count_decreasing_prime_sums(n) <= 5001: n += 1 print(n)
'''Преобразовать IP-адрес (переменная IP) в двоичный формат и вывести вывод столбцами на стандартный поток вывода, таким образом: первой строкой должны идти десятичные значения байтов второй строкой двоичные значения Вывод должен быть упорядочен также, как в примере: столбцами ширина столбца 10 символов Пример вывода: 10 1 1 1 00001010 00000001 00000001 00000001 ''' IP = '192.168.3.1'.split('.') IP = [int(i)for i in IP] print (IP) IP_ADDR = ''' {:<10} {:<10} {:<10} {:<10} {:<10b} {:<10b} {:<10b} {:<10b} ''' print (IP_ADDR.format(IP[0], IP[1], IP[2], IP[3], IP[0], IP[1], IP[2], IP[3]))
from sys import argv import re filename, regex = argv[1:] def regex_func(filename, reg_ex): with open(filename, 'r') as text: ip_list = [] for line in text: match = re.search(reg_ex, line) if match: ip_list.append(match.group()) return ip_list print(regex_func(filename, regex))
'''6.1a Сделать копию скрипта задания 6.1. Дополнить скрипт: Добавить проверку введенного IP-адреса. Адрес считается корректно заданным, если он: состоит из 4 чисел разделенных точкой, каждое число в диапазоне от 0 до 255. Если адрес задан неправильно, выводить сообщение: 'Incorrect IPv4 address' ''' IP = input ('Enter IP:') IP_OCTETS = IP.split('.') #Split checking for '.' IP_CHECK = False if int: i = 0 while i < 4: if not len(IP_OCTETS) == 4: #Checking 4 obj in list print ('Incorrect IPv4 address') break elif not IP_OCTETS[0 + i].isdigit(): #Checking if obj is numbers print ('Incorrect IPv4 address') break elif len (IP_OCTETS[0 + i]) > 3: #Checking if number not contain more than 3 digits print ('Incorrect IPv4 address') break elif int(0) < int (IP_OCTETS[0 + i]) > int(255): #Checking if number in range 0-255 print ('Incorrect IPv4 address') break elif len(IP_OCTETS[0 + i]) == 2 or len(IP_OCTETS[0 + i]) == 3: A = IP_OCTETS[0 + i] #Checking format "000 or 001" if int(A[0]) == 0: print ('Incorrect IPv4 address') break i += 1 else: IP_CHECK = True if IP_CHECK == True: if 1 <= int(IP_OCTETS[0]) <= 126 or 128 <= int(IP_OCTETS[0]) <= 191 or 192 <= int(IP_OCTETS[0]) <= 223: print (IP + ' - ' + 'unicast') elif int(IP_OCTETS[0]) == 127: print (IP + ' - ' + 'localhost') elif 234 <= int(IP_OCTETS[0]) <= 239: print (IP + ' - ' + 'multicast') elif int (IP_OCTETS[0]) == 255 and int(IP_OCTETS[1]) == 255 and int(IP_OCTETS[2]) == 255 and int(IP_OCTETS[3]) == 255: print (IP + ' - ' + 'local broadcast') elif int (IP_OCTETS[0]) == 0 and int (IP_OCTETS[1]) == 0 and int (IP_OCTETS[2]) == 0 and int (IP_OCTETS[3]) == 0: print (IP + ' - ' + 'unassigned')
class BinaryTreeNode(): """represents a node of the tree. Leaf nodes are represented by None. You can add to this class.""" def __init__(self, key, value, left=None, right=None): self._key = key self._values = [value] self._left = left self._right = right def insert(self, key, value): if self._key > key: # insert on the left if self._left is not None: self._left.insert(key, value) else: self._left = BinaryTreeNode(key, value) elif self._key < key: # insert on the right if self._right is not None: self._right.insert(key, value) else: self._right = BinaryTreeNode(key, value) else: # same key, add to value self._values.append(value) def get(self, key): if self._key == key: return self._values elif self._key > key: #should be on the left if self._left is not None: return self._left.get(key) else: return None else: #should be on the right if self._right is not None: return self._right.get(key) else: return None class BinaryTree(): """implement the “insert” and “get” methods for a binary tree which stores data within the nodes. The “insert” method inserts a book_id (value) into the tree for a specific token (key). Note: if a key already exists, the values should be appended to a List. Make sure to update the _count variable representing the number of nodes in the tree. Other binary tree methods (e.g. delete) do not have to be implemented. """ def __init__(self): self._root = None self._count = 0 def __len__(self): return self._count def insert(self, key, value): self._count += 1 if self._count%1000 == 0: print("at: " + str(self._count)) if self._root is None: self._root = BinaryTreeNode(key, value) else: current_node = self._root found = False while not found: if key < current_node._key: if current_node._left is not None: current_node = current_node._left else: current_node._left = BinaryTreeNode(key, value) found = True elif key > current_node._key: if current_node._right is not None: current_node = current_node._right else: current_node._right = BinaryTreeNode(key, value) found = True else: current_node._values.append(value) found = True def get(self, key): if self._root is not None: node = self._root while node is not None: if node._key == key: return node._values if node._key > key: node = node._left else: node = node._right else: return None if __name__ == "__main__": print("Testing binarytree.py") root = BinaryTree() root.insert(8, "West Vlaams voor dummies") root.insert(4, "Waarom Gistel een wereldstad is") root.insert(7, "g en h wat is het verschil") root.insert(7, "weglaten die klanken") root.insert(10, "hitgub voor dummies") root.insert(2, "Het leven aan de zee") print(root.get(8)) print(root.get(4)) print(root.get(7)) print(root.get(10)) print(root.get(2)) #add breakpoint a = 5
import turtle as t import random color=["red","white","black","pink","greenyellow"] size=50 def draw_dot(x,y): t.up() t.goto(x,y) t.dot(size) def draw_triangle(x,y): t.up() t.goto(x,y) t.down() t.begin_fill() for i in range(3): t.forward(size) t.left(360/3) t.end_fill() def draw_square(x,y): t.up() t.goto(x,y) t.down() # t.setheading(random.randint(0,360)) t.begin_fill() for i in range(4): t.forward(size) t.left(360/4) t.end_fill() def rand_color(): t.color(random.choice(color)) def size_up(): global size size+=10 def size_down(): global size size-=10 def clean(): t.clear() t.bgcolor("lightblue") t.speed(0) t.onscreenclick(draw_dot,1) t.onscreenclick(draw_triangle,2) t.onscreenclick(draw_square,3) t.onkeypress(rand_color,"space") t.onkeypress(size_up,"Up") t.onkeypress(size_down,"Down") t.onkeypress(clean,"d") t.listen() t.done()
# -*- coding: utf8 -*- ''' This module takes a collection as input, and builds a "reversed index": word -> items There are then 3 ways to search: exact=True -> finds all items containing the exact term exact=False -> finds all items containing the prefix (slower) TODO!!! onlyin=[keys] -> returns only the items where the term/prefix is contained in one of the keys weights={key1:weight1,...} -> retrieves all items matching, score them and sort them. It's slower since all items have to be retrieved and sorted first. Three find/search methods: - find the "exact" content - find the "token" inside (default) - find the "prefix" inside - case sensitive / insensitive (default) ''' import sys if sys.version_info < (3, 0): print('Sorry, requires Python 3.x') sys.exit(1) import string import pysos import re import bisect import os.path import heapq from collections import namedtuple Hit = namedtuple('Hit', 'key, value, score') # small words like "a", "the", etc. are usually associated with so many items that the cost overweights the benefits. # for small words, you can as well iterate over all values. # in the ideal case, it should depend on the frequency of the word rather than the length. # However, doing that adds complexity, slowness and non-determinism: # depending on the order in which you update entries, a word might still be contained ...or not. MIN_TOKEN_LENGTH = 3 # this limit is used in order to avoid giant tokens due to binary/encoded data items TOKEN_SIZE_LIMIT = 20 def _walk(obj): if not obj: return if isinstance(obj,dict): for child in obj.values(): for leaf in _walk(child): yield leaf elif isinstance(obj,list): for child in obj: for leaf in _walk(child): yield leaf else: yield obj # We split whitespaces including bordering punctuation, as well as apostrophes # The reason not to split punctuation as a whole is to keep things like 2016-07-11, 14:02:11, 123.456 or CODED-ID/123.xyz as a whole token _splitter = re.compile("\W*\s+\W*|'|’") def tokenize(val): tokens = _splitter.split(str(val).strip().lower()) tokens = [ t[:TOKEN_SIZE_LIMIT] for t in tokens ] # avoid giant tokens return tokens def iterate(obj): if isinstance(obj, dict): return obj.keys() if isinstance(obj, list): return range(len(obj)) raise Exception("Can only iterate over lists or dicts.") def index(collection, keys=None): '''Returns an index: word -> ["key1","key2",...]''' indexes = {} i = 0 for key in iterate(collection): i += 1 if i % 1000 == 0: print('%12d' % i) item = collection[key] unique = set() for val in _walk(item): tokens = tokenize(val) for t in tokens: if len(t) < MIN_TOKEN_LENGTH: continue unique.add(t) for u in unique: if u in indexes: indexes[u].append(key) #hits = indexes[t] #if hits: # hits.append(key) # if len(hits) > 10000: # indexes[t] = False # print('Too big: ' + t) else: indexes[u] = [key] #import pysos.pysos as pysos #d = pysos.Dict('temp.index.sos') #for k,v in indexes.items(): # d[k] = v #d.close() return indexes def score(obj, word, weights={}, exact=True): s = 0 if not weights: tokens = [] for val in _walk(obj): tokens += tokenize(val) if exact: s = tokens.count(word) / len(tokens) else: n = 0 for t in tokens: if t.startswith(word): n += 1 s = n / len(tokens) else: for (key, weight) in weights.items(): if not weight: continue if isinstance(obj, list): key = int(key) if key >= len(obj): continue else: if key not in obj: continue val = obj[key] tokens = tokenize(val) if exact: s += weight * tokens.count(word) / len(tokens) else: n = 0 for t in tokens: if t.startswith(word): n += 1 s += weight * n / len(tokens) return s def filt(obj, word, keys): if not keys: raise Exception('No keys provided!') class Finder: def __init__(self, collection, index_file=None, keys=None): self._collection = collection self._keys = keys if index_file: if os.path.exists(index_file): # load it from file print('loading it') self._index = pysos.Dict(index_file) else: # create it print('creating it') self._index = pysos.Dict(index_file) for k,v in index(collection, keys).items(): self._index[k] = v else: # use an in-memory one self._index = index(collection, keys) self._voc = sorted(self._index.keys()) def words(self, prefix): '''Returns all words in the vocabulary starting with prefix''' i = bisect.bisect_left( self._voc, prefix ) j = bisect.bisect_right( self._voc, prefix + 'z' ) return self._voc[i:j] def search_keys(self, word, exact=True): word = tokenize(word)[0] if exact: if word not in self._index: return for key in self._index[word]: yield key else: for w in self.words(word): for key in self._index[w]: yield key def search_values(self, word, exact=True): for key in self.search_keys(word, exact): yield self._collection[key] def search_weighted(self, word, exact=True, weights={}): for key in self.search_keys(word, exact): val = self._collection[key] s = score(val, word, weights, exact) assert weights or s > 0 if s > 0: yield Hit(key, val, s) def find(self, word, exact=True, weights={}, limit=100): word = tokenize(word)[0] if limit > 0: results = heapq.nlargest(limit, self.search_weighted(word, exact, weights), key=lambda hit: hit.score) else: results = sorted(self.search_weighted(word, exact, weights), key=lambda hit: -hit.score) return results def update(self, key, val, old): assert val != None or old != None if old == None: # a new value idx = index({key: val}, self._keys) for word, k in idx.items(): assert [key] == k if word in self._index: self._index[word].append(key) else: self._index[word] = [key] bisect.insort(self._voc, word) elif val == None: # a deleted value idx = index({key: old}, self._keys) for word, k in idx.items(): assert [key] == k assert (word in self._index) self._index[word].remove(key) if not self._index[word]: del self._index[word] i = bisect.bisect_left(self._voc, word) del self._voc[ i ] else: # an updated value #idx_old = index({key: old}, self._keys) #idx_val = index({key: val}, self._keys) # TODO: optimize this quick and dirty trick by comparing the two outputs # delete it first self.update(key, None, old) # add the new one afterwards self.update(key, val, None) def predicate(self, where, negate=False): tokens = _tokenize(where) pred = _buildAnd(tokens) if not negate: return pred else: return lambda obj: not pred(obj) _operators = set(['<','<=','==','!=','~=','>=','>']) def _tokenize(where): tokens = [] s = 0 e = 0 while s < len(where): if where[s] == ',': e += 1 elif where[s] == '"': e += 1 while where[e] != '"': e += 1 if e == len(where): raise Exception("Unterminated string: " + where[s:]) e += 1 elif where[s] == "'": e += 1 while where[e] != "'": e += 1 if e == len(where): raise Exception("Unterminated string: " + where[s:]) e += 1 elif where[s] in '<>=!~': if where[s+1] == '=': e += 2 else: e += 1 elif where[s] == '|': if where[s+1] != '|': raise Exception("Double || should be used for 'or'") else: e += 2 else: while e < len(where) and where[e] not in '<>=!~|"': e += 1 tok = where[s:e] tokens.append( tok ) s = e def _buildAnd(tokens): if ',' not in tokens: return _buildOr(tokens) conditions = [] while ',' in tokens: i = tokens.index(',') conditions.append( tokens[:i] ) tokens = tokens[i+1:] predicates = map(_buildOr, conditions) def doAnd(obj, predicates): for p in predicates: if p(obj) == False: return False return True return doAnd def _buildOr(tokens): if '||' not in tokens: return _buildComp(tokens) conditions = [] while '||' in tokens: i = tokens.index('||') conditions.append( tokens[:i] ) tokens = tokens[i+1:] predicates = map(_buildComp, conditions) def doOr(obj): for p in predicates: if p(obj) == True: return True return False return doOr def _buildComp(tokens): if len(tokens) < 3 or len(tokens) % 2 != 1: raise Exception("Invalid 'where' clause: " + "".join(tokens)) (left, op, right) = tokens[0:3] if left[0] == '"' or left[0] == "'": pass
#Advanced Loops def function(rows,columns): for row in range(6): #0,1,2,3,4 if row % 2 != 0: #0 for column in range(1,6): if column % 2 == 1: if column != 5: print("",end = "") else: print(" ") else: print(" | ",end = "") print("| ",end = "") # print(" | | ") else: print(" -----","----") print(" -----","----") print("",True) function(6,6)
# Animals - Part A, B class Pet: def __init__(self,n,a,h,p): self.name = n self.age = a self.hunger = h self.playful = p #getters def getName(self): return self.name def getAge(self): return self.age def getHunger(self): return self.hunger def getPlayful(self): return self.playful #setters def setname(self,name): self.name = name def setAge(self,age): self.age = age def setHunger(self,hunger): self.hunger = hunger def setPlayful(self,playful): self.playful = playful def __str__(self): return (self.name + " is "+ str(self.age) + " years old") # Pet1 = Pet("Rocko",4.5,False,True) # print(Pet1.getName()) # print(Pet1.getAge()) # print(Pet1.getHunger()) # print(Pet1.getPlayful()) # Pet1.setname("Peluche") # print(Pet1.getName()) class Dog(Pet): def __init__(self,Breed,FToy,name,age,hunger,playful): Pet.__init__(self,name,age,hunger,playful) self.Breed = Breed self.FavoriteToy = FToy def wantToPlay(self): if self.playful == True: return ("Dog wants to play with "+ self.FavoriteToy) else: return ("Dog doesn't wants to play") class Cat(Pet): def __init__(self, name, age, hunger, playful,FP): Pet.__init__(self,name,age,hunger,playful) self.FavoritePlaceToSit = FP def wantToSit(self): if self.playful == False: print("The cat wants to sit in "+ self.FavoritePlaceToSit) else: print("The cat wants to play") def __str__(self): return (self.name + " likes to sit in " + self.FavoritePlaceToSit) class Human: def __init__(self, name, pets): self.name = name self.pets = pets def hasPet(self): if len(self.pets) != 0: return "yes" else: return "no" PitbullDog = Dog("Pitbull","Ball","Rocko",4.5,False,False) Play = PitbullDog.wantToPlay() print([PitbullDog.Breed,PitbullDog.FavoriteToy,PitbullDog.name,PitbullDog.hunger,Play]) Cat1 = Cat("BolaDePelo",2,False,False,"BedsCat") print(Cat1.name) print(Cat1.age) print(Cat1.hunger) print(Cat1.playful) print(Cat1.FavoritePlaceToSit) Cat1.wantToSit() print(Cat1) print(PitbullDog) Human1 = Human("alvarod",[PitbullDog]) print("-----------------") # hasPet = Human1.hasPet() print(Human1.hasPet()) print(Human1.pets[0].name)
#Class 7 #breaking n continuing in loops #Participants = ["Alvaro","Sebastian","Johnny","Esmeralda","Dayanna"] # Position = 1 # for name in Participants: # if name == "Esmeralda": # break # Position += 1 # print(name) # print(Position) # #other-------------------------------------------- # for currentIndex in range(len(Participants)): # print(currentIndex) # if Participants[currentIndex] == "Johnny": # print("have a breaked") # break # print("Not breaked") # print(currentIndex + 1) #other-------------------------------------------- for num in range(10): if num % 3 == 0: print(num) print("Its divisible by 3") continue if num % 4 == 0: print(num) print("Its divisible by 4") continue print(num) print("Not divisible by 3") """ code quiz Word = "Hello" Letters = [] for w in Word: Letters.append(w) print(Letters) #another i = 1 while True: if i%3 == 0: break print(i) i += 1 #another for i in range(2.0): print(i) #error decimal no puede ser interpretado por entero #another X = "abcd" for i in range(len(X)): print(i) """
# Part A # from random import randint # randVal = randint(1,100) # while(True): # while(True==True): # guess = int(input("Input a number: ")) # if guess == randVal: # print("Ganaste") # break # elif guess < randVal: # print("Tu numero debe ser mas alto") # else: # print("Tu numero debe ser mas bajo") # print("La respuesta correcta es: ", randVal) # Part B from random import random from time import clock randVal = random() print(randVal) upper = 1.0 lower = 0.0 guess = 0.5 startTime = clock() while(True): guess = (lower + upper) / 2 if guess == randVal: break elif guess < randVal: lower = guess else: upper = guess endTime = clock() print(guess) print("Tomó: ",endTime-startTime," seconds")
class Employee: def __init__ (self,name, surname): self.name = name self.surname = surname self.position = type(self).__name__ def print_init(self): print(self.name, self.surname, self.position) class Programmer(Employee): pass class Manager(Employee): "this is description of the class" pass class Base: __private = "PRIVATE" def print_method(self): return self.__private class Child(Base): def __init__(self,argument): self.baby = argument class ErrCantEmploy: def name_of_instance(instance): check_name = instance.name check_surname = instance.surname if type(check_name) != str: raise TypeError("{0} is not a string".format(check_name)) elif type(check_surname) != str: raise TypeError("{0} is not a string".format(check_surname)) Kuba = Programmer("Kuba","gorzedow") Bartek = Employee("Bartek", "Barcikowski") Hania_1 = Manager("Hania",5) if __name__ == "__main__": ErrCantEmploy.name_of_instance(Hania_1)
#Programa que convierte dolares a pesos. class Convertor(): def __init__(self, dolares): #definicion de propiedades de clase. self.dolares = dolares self.costoDolar = 3600 def ConvertirPesos(self): resultado = self.dolares * self.costoDolar return resultado def MostrarMensaje(self): return f"{self.dolares} es equivalente a {self.ConvertirPesos()} pesos" moneda = Convertor(float(input("Escribe el monto en dolares: "))) print(moneda.MostrarMensaje())
from pet import Pet class Program: def __init__(this): this.vacOptions = ("Vacunas: ", "1.Antirrabica", "2.Antipulgas", "3.Purgatoria") this.response = "" this.__afirmativeResponses = ["s", "si", "sii", "yes", "claro", "por supuesto", "obviamente", "siza", "siza pai"] this.option = "1" this.menu = ["\nMenú: \n", "1. Registrar datos de la mascota", "2. Mostrar información de la mascota"] this.__menuOptions = { "1": ["primera", "la primera", "1"], "2": ["segunda", "la segunda", "2"], } def Menu(this): pet = Pet() sequence = "" for option in this.vacOptions: sequence = f"{sequence} {option}" for menu in this.menu: print(f"{menu}") print(f"{sequence}") while(this.response != this.__afirmativeResponses): if(this.option in this.__menuOptions["1"]): print(f"\n{this.menu[1]}\n") pet.SetData(name=input("Nombre de la mascota: "), age=input("Edad de la mascota: "), sort=input("¿Perro o Gato?: "), raza=input("Raza de la mascota: ")) this.option = input("\n¿Qué opción del menú desea ejecutar? ").lower() elif(this.option in this.__menuOptions["2"]): print(f"\n{this.menu[2]}\n") print(pet.GetData()) this.option = input("\n¿Qué opción del menú desea ejecutar? ").lower() else: print(f"{this.option} no es una opción correcta.") this.response = input("¿Quieres terminar con la ejecución del programa?").lower() this.option = input("\n¿Qué opción del menú desea ejecutar? ").lower()
class Pay: def __init__(self): self.rango = "" self.horas = 0 trabajador = { "horas": 0, "rangos": ['bajo', 'medio', 'alto'] } def main(self): while True: try: horas = int(input("¿Cuántas horas trabajó?: ")) self.horas = horas if(horas < 10): print("No trabajó las horas suficientes.") break rango = input("¿Cuál es su rango? (bajo, medio, alto): ").lower() self.establecerRango(rango) break except ValueError as e: print("El valor escrito es incorrecto. Reintente.") except TypeError as e: print(e) def establecerRango(self, rango): if(rango in self.trabajador['rangos']): self.rango = rango self.calcularHoras(self.horas) else: print("El rango escrito no es correcto") def calcularHoras(self, horas:int): if(self.rango == "bajo"): costoHora = 20000 auxilio = self.horas * costoHora / 100 print(f"\n Su sueldo es de: {self.horas * costoHora} \n Auxilio: {auxilio} \n Total: {self.horas * costoHora + auxilio}") horasAdicionales = self.horasAdicionales() if(horasAdicionales > 0): print(f"Horas adicionales: {horasAdicionales}. Total: {self.horas * costoHora + auxilio + (horasAdicionales*25000)}") elif(self.rango == "medio"): costoHora = 40000 descuento = 1.5 * self.horas / 100 print(f"\n Su sueldo es de: {self.horas * costoHora} \n Descuento: {descuento} \n Total: {self.horas * costoHora + descuento}") horasAdicionales = self.horasAdicionales() if(horasAdicionales > 0): print(f"Horas adicionales: {horasAdicionales}. Total: {self.horas * costoHora + descuento + (horasAdicionales*25000)}") elif(self.rango == "alto"): print(f"Su rango es {self.rango}") costoHora = 60000 descuento = 1.5 * self.horas / 100 print(f"\n Su sueldo es de: {self.horas * costoHora} \n Descuento: {descuento} \n Total: {self.horas * costoHora + descuento}") horasAdicionales = self.horasAdicionales() if(horasAdicionales > 0): print(f"Horas adicionales: {horasAdicionales}. Total: {self.horas * costoHora + descuento + (horasAdicionales*25000)}") else: print("El rango es inválido") def horasAdicionales(self): horaAdicional = 0 if(self.horas > 50): for i in range(50, self.horas): horaAdicional += 1 return horaAdicional return horaAdicional empleador = Pay() empleador.main()
from src.Carrito import Carrito class Program: def __init__(self): self.mensaje = "no" self.respuestas = ["s", "si", "sii", "yes", "claro", "por supuesto", "asi es", "siza pai"] self.opcionesRespuesta = { "primera": ["primera", "la uno", "la primera", "1"], "segunda": ["segunda", "la dos", "la segunda", "2"], "tercera": ["tercera", "la tres", "la tercera", "3"], "cuarta": ["cuarta", "la cuatro", "la cuarta", "4"], "quinta": ["quinta", "la quinta", "la cinco", "5"] } self.carrito = Carrito() def Main(self): opciones = ("Menú:\n", "1. Insertar producto", "2. Mostrar productos", "3. Eliminar producto", "4. Editar producto", "5. Salir del programa \n") for i in opciones: print(f"{i}") while(self.mensaje != self.respuestas): opcion = input("¿Qué opción desea ver? ").lower() if(opcion in self.opcionesRespuesta["primera"]): print(f"\n{opciones[1]}\n") try: self.carrito.agregar(input("Nombre del producto: "), float(input("Valor del producto: ")), int(input("Cantidad del producto: "))) except: print("El valor que escribió es incorrecto.") elif(opcion in self.opcionesRespuesta["segunda"]): print(f"\n{opciones[2]}\n") self.carrito.mostrar() elif(opcion in self.opcionesRespuesta["tercera"]): print(f"\n{opciones[3]}\n") try: self.carrito.eliminar(input("Nombre del producto a eliminar: ")) except: print("Valor incorrecto") elif(opcion in self.opcionesRespuesta["cuarta"]): print(f"\n{opciones[4]}\n") self.carrito.editar(input("Nombre del producto a editar: ")) elif(opcion in self.opcionesRespuesta["quinta"]): print(f"\n{opciones[5]}\n") print("El programa se cerrará") break else: print("Opción incorrecta")
class Persona: def __init__(self, nombre): self.__nombre = nombre def __add__(self, este): return f"{self.__nombre} {este.__nombre}" p1 = Persona(5) p2 = Persona(5) p3 = Persona(5) print(p1 + p2)
def misDatos(): preguntas = ["Nombre", "Apellido", "Edad", "Tarjeta de Identidad"] respuestas = ["Brian", "Castro", "16", "1098306124"] for pregunta, respuesta in zip(preguntas, respuestas): print(f"¿Cual es tu {pregunta}? La respuesta es: {respuesta}") misDatos()
class Recarga: def __init__(self, cantidadMins: int): self.cantidadMins = cantidadMins self.valorMins = 100 self.__adicion = self.cantidadMins * 2 def Main(self): print(self.__str__()) def __HacerRecarga(self): recarga = self.cantidadMins * self.valorMins return recarga def __str__(self): if self.cantidadMins > 50: return f"La recarga de {self.cantidadMins} minutos, se ha realizado. Costo: {self.__HacerRecarga()} + Adición: {self.__adicion} minutos" elif self.cantidadMins <= 0: return "No introdujo una cantidad válida" else: return f"La recarga de {self.cantidadMins} minutos, se ha realizado. Costo: {self.__HacerRecarga()}" #Instanciando objeto: celular celular = Recarga(int(input("Escriba la cantidad de minutos: "))) celular.Main()
import math class Triangle(): def __init__(this): this.side = { "a": 0, "b": 0 } this.__hypotenuse = 0 def hypotenuse(this, a, b): this.side["a"] = a this.side["b"] = b this.__hypotenuse = this.side["a"]**2 + this.side["b"]**2 this.result = math.sqrt(this.__hypotenuse).__round__() print(f"El resultado de la hipotenusa del cateto: {a} y cateto: {b} es igual a = {this.result}")
class Sumatoria: def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def sumar(self): return self.num1 + self.num2 suma = Sumatoria(float(input("Numero 1: ")), float(input("Numero 2: "))) print(f"El resultado de la suma de Num1 + Num2 es: {suma.sumar()}")
from tkinter import * from tkinter.messagebox import * import sqlite3 def login_user(username,password): con=sqlite3.connect("createuser.db") cur=con.cursor() cur.execute("select * from user") row=cur.fetchall() for i in row: if(i[0]==username and i[3]==password): showinfo("Login","You have been successfully logged in") available_books() break else: showinfo("Login","Invalid Details") break def create_user(name,gender,email,password): con=sqlite3.connect("createuser.db") cur=con.cursor() if(name=='' or gender=='' or email=='' or password==''): showinfo("New User","Fill all the details") new_user() else: cur.execute("create table if not exists user(name varchar(20),gender number(2),email varchar(20),password varchar(20))") if(gender==1): cur.execute("insert into user values(?,?,?,?)",(name,"Male",email,password)) else: cur.execute("insert into user values(?,?,?,?)",(name,"Female",email,password)) con.commit() con.close() showinfo("New User","Registration Successful") def rbook(username,bookname,price): if(username=='' or bookname=='' or price==''): showinfo("Request Book","Please fill all the details") else: con=sqlite3.connect("createuser.db") cur=con.cursor() cur.execute("select * from user") row=cur.fetchall() for i in row: if(i[0]==username): cur.execute("create table if not exists request(username varchar(20),bookname varchar(20),price number(10))") cur.execute("insert into request values(?,?,?)",(username,bookname,price)) con.commit() con.close() showinfo("Request Book","Pay the money and Collect the book from counter") break else: showinfo("Request Book","User doesn't exist") break def sbook(username,bookname,price): if(username=='' or bookname=='' or price==''): showinfo("Submit Book","Please fill all the details") else: con=sqlite3.connect("createuser.db") cur=con.cursor() cur.execute("select * from request") row=cur.fetchall() for i in row: if(i[0]==username and i[1]==bookname): cur.execute("delete from request where username=?",(username,)) con.commit() con.close() showinfo("Submit Book","Submit the book and Collect the money from counter") break elif(i[0]=='' or i[1]==''): showinfo("Submit Book","No Records found") break else: showinfo("Request Book","No book records exists on your username") break def login(): frame = Frame(window) Frame.tkraise(frame) frame=Toplevel() frame.geometry("500x400") #Frame.title("Login") d = Canvas(frame, height=190, width=460, bg="green") username=StringVar() l1=Label(frame,text="Username",bg="brown") l1.place(x=150,y=150) e1=Entry(frame,bd=5,textvariable=username) e1.place(x=230,y=150) password=StringVar() l2=Label(frame,text="Password",bg="brown") l2.place(x=150,y=200) e2=Entry(frame,bd=5,textvariable=password,show='*') e2.place(x=230,y=200) b4=Button(frame,text="Login",bg="Skyblue",command=lambda:login_user(username.get(),password.get())) b4.place(x=150,y=250,height=40,width=70) b5=Button(frame,text="New User",bg="Skyblue",command=new_user) b5.place(x=250,y=250,height=40,width=70) d.pack(side="top",fill="both",expand=True) def new_user(): frame = Frame(window) Frame.tkraise(frame) frame=Toplevel() frame.geometry("450x350") e = Canvas(frame, height=190, width=460, bg="Yellow") e3_value=StringVar() l3=Label(frame,text="Name",bg="Yellow") l3.place(x=100,y=100) e3=Entry(frame,bd=4,textvariable=e3_value) e3.place(x=170,y=100) c1_value=IntVar() l4=Label(frame,text="Gender",bg="Yellow") l4.place(x=100,y=140) c1=Radiobutton(frame,text="Male",value=1,variable=c1_value,bg="Yellow") c1.place(x=170,y=140) c2=Radiobutton(frame,text="Female",value=2,variable=c1_value,bg="Yellow") c2.place(x=240,y=140) e5_value=StringVar() l5=Label(frame,text="Email",bg="Yellow") l5.place(x=100,y=180) e5=Entry(frame,bd=4,textvariable=e5_value) e5.place(x=170,y=180) e6_value=StringVar() l6=Label(frame,text="Password",bg="Yellow") l6.place(x=100,y=220) e6=Entry(frame,bd=4,textvariable=e6_value,show='*') e6.place(x=170,y=220) b6=Button(frame,text="Submit",bg="Skyblue",command=lambda:create_user(e3_value.get(),c1_value.get(),e5_value.get(),e6_value.get())) b6.place(x=150,y=260,height=40,width=70) e.pack(side="top",fill="both",expand=True) def submit_book(): frame = Frame(window) Frame.tkraise(frame) frame=Toplevel() frame.geometry("450x350") e = Canvas(frame, height=190, width=460, bg="Violet") e7_value=StringVar() l7=Label(frame,bg="Violet",text="Username") l7.place(x=150,y=130) e7=Entry(frame,bd=5,textvariable=e7_value) e7.place(x=230,y=130) e8_value=StringVar() l8=Label(frame,bg="Violet",text="Bookname") l8.place(x=150,y=180) e8=Entry(frame,bd=5,textvariable=e8_value) e8.place(x=230,y=180) e9_value=StringVar() l9=Label(frame,bg="Violet",text="Price") l9.place(x=150,y=230) e9=Entry(frame,bd=5,textvariable=e9_value) e9.place(x=230,y=230) b6=Button(frame,text="Submit",bg="Skyblue",command=lambda:sbook(e7_value.get(),e8_value.get(),e9_value.get())) b6.place(x=195,y=260,height=40,width=70) e.pack(side="top",fill="both",expand=True) def request_book(): frame = Frame(window) Frame.tkraise(frame) frame=Toplevel() frame.geometry("450x350") e = Canvas(frame, height=190, width=460, bg="Orange") e10_value=StringVar() l10=Label(frame,bg="Orange",text="Username") l10.place(x=100,y=100) e10=Entry(frame,bd=4,textvariable=e10_value) e10.place(x=170,y=100) c3_value=StringVar() l11=Label(frame,bg="Orange",text="Bookname") l11.place(x=100,y=140) c3=Entry(frame,textvariable=c3_value,bd=4) c3.place(x=170,y=140) e12_value=StringVar() l12=Label(frame,bg="Orange",text="Price") l12.place(x=100,y=180) e12=Entry(frame,bd=4,textvariable=e12_value) e12.place(x=170,y=180) b7=Button(frame,text="Submit",bg="Skyblue",command=lambda:rbook(e10_value.get(),c3_value.get(),e12_value.get())) b7.place(x=195,y=220,height=40,width=70) e.pack(side="top",fill="both",expand=True) def available_books(): frame = Frame(window) Frame.tkraise(frame) frame=Toplevel() frame.geometry("470x350") e = Canvas(frame, height=190, width=460, bg="Red") a1=Label(frame,text="Available Books",bg="Red") a1.place(x=200,y=4) b8=Button(frame,text="Request Book",command=request_book,bg="Skyblue") b8.place(x=100,y=40,height=40,width=90) b9=Button(frame,text="Submit Book",command=submit_book,bg="Skyblue") b9.place(x=300,y=40,height=40,width=90) e.pack(side="top",fill="both",expand=True) #window.geometry("500x200") window=Tk() window.title("BMS") C = Canvas(window, height=190, width=460, bg="light green") C.pack(side="top",fill="both",expand=True) b1=Button(window,text="Login",bg="green",command=login) b1.place(x=70,y=70,height=40,width=70) b2=Button(window,text="Sign Up",bg="green",command=new_user) b2.place(x=180,y=70,height=40,width=80) b3=Button(window,text="Available Books",bg="green",command=available_books) b3.place(x=300,y=70,height=40,width=95) window.mainloop()
""" My Relational Operators Program """ __author__ = "730250025" left_hand_side: str = input("Left-hand side ") right_hand_side: str = input("Right-hand side ") first_number: int = int(left_hand_side) second_number: int = int(right_hand_side) less_than_number: int = int(first_number < second_number) bool_less_than_number: bool = bool(less_than_number) str_less_than_number: str = str(bool_less_than_number) print(left_hand_side + " < " + right_hand_side + " is " + str_less_than_number) at_least_number: int = int(first_number >= second_number) bool_at_least_number: bool = bool(at_least_number) str_at_least_number: str = str(bool_at_least_number) print(left_hand_side + " >= " + right_hand_side + " is " + str_at_least_number) equal_to_number: int = int(first_number == second_number) bool_equal_to_number: bool = bool(equal_to_number) str_equal_to_number: str = str(bool_equal_to_number) print(left_hand_side + " == " + right_hand_side + " is " + str_equal_to_number) not_equal_to_number: int = int(first_number != second_number) bool_not_equal_to_number: bool = bool(not_equal_to_number) str_not_equal_to_number: str = str(bool_not_equal_to_number) print(left_hand_side + " != " + right_hand_side + " is " + str_not_equal_to_number)
#!/usr/bin/python3 import os ROOT = input("What is the directory to be scanned? ") filesToRead = os.listdir(ROOT) writAble = [] for i in range(len(filesToRead)): print(filesToRead[i]) if filesToRead[i][0] == 't' and filesToRead[i][0] != '_': with open (ROOT + "/" + filesToRead[i], 'r', encoding='utf-8') as checking: saveFile = open(ROOT + "/_" + filesToRead[i], 'w+', encoding='utf-8') for line in checking: if line == "\n": print("newline found") continue elif line == " ": print("Space found") continue elif line == " ||| ": print("Empty line in combine file") continue else: writAble.append(line) saveFile.close()h
#elif= arias condiciones #ejemplo convertidor de numeros a letras de 1 a 5 print( "convertidor de numeros a letras") num= int(input("agrega un valor ")) if num==1: print("es el numero uno ") elif num==2: print("el numero es dos") elif num ==3: print("es el tres") elif num==4: print("es el cuatro") elif num==5: print("es el 5") else: print("solo conbvertimos de 1 a 5 sorry")
#operadores relacionales print("comparacion de dos numeros") num1= int(input("ingrese numero 1 :")) num2=int(input("ingrese numero 2 :")) print("numeros a comparar " , str(num1) + "y" , str(num2)) if num1<num2: print("el" , str(num1) , "es menos que" , str(num2)) if num1>num2: print("el", str(num1), "es mayor que", str(num2)) if num1==num2: print("el", str(num1), "es igual que", str(num2)) if num1!=num2: print("el", str(num1), "es diferente a ", str(num2)) if num1<=num2: print("el", str(num1), "es menor o igual", str(num2)) if num1>=num2: print("el", str(num1), "mayor o igual", str(num2)) else: print("nose")
def add(a, b): """Function to add two numbers.""" c = a+b return f'Sum = {c}.' def fibonacci(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result
# -*- coding: utf-8 -*- """The attribute container interface.""" class AttributeContainer(object): """Class that defines the attribute container interface. This is the the base class for those object that exists primarily as a container of attributes with basic accessors and mutators. The CONTAINER_TYPE class attribute contains a string that identifies the container type e.g. the container type "event" identifiers an event object. """ CONTAINER_TYPE = None def CopyToDict(self): """Copies the attribute container to a dictionary. Returns: A dictionary containing the attribute container attributes. """ dictionary = {} for attribute_name in iter(self.__dict__.keys()): attribute_value = getattr(self, attribute_name, None) if attribute_value is not None: dictionary[attribute_name] = attribute_value return dictionary def GetAttributes(self): """Retrieves the attributes from the attribute container. Attributes that are set to None are ignored. Yields: A tuple containing the attribute container attribute name and value. """ for attribute_name in iter(self.__dict__.keys()): attribute_value = getattr(self, attribute_name, None) if attribute_value is not None: yield attribute_name, attribute_value
def expansion(current_path, successors): new = [] successors_names = [i[0] for i in successors] current_path_names = [i[0] for i in current_path] # print('successors:', successors) # search if in successors we have a node that has # already been visited on the current_path, so we # search by the name of the nodes for i in range(len(successors_names)): if successors_names[i] not in current_path_names: new.append([successors[i]] + current_path) # print('successors_new:', new) return new
# start: node name # end: node name # conn: all the connections import elements.Connections as Connections import elements.Nodes as Nodes from algorithms.get_node_heuristic import get_node_heuristic def expansion_heuristic(current_path, successors, nodes: Nodes): new = [] successors_names = [i[0] for i in successors] current_path_names = [i[0] for i in current_path] # print('successors:', successors) # search if in successors we have a node that has been # already visited on the current_path, so we search # by the names of the nodes for i in range(len(successors_names)): if successors_names[i] not in current_path_names: heuristic = get_node_heuristic(successors_names[i], nodes) new.append([(successors[i][0], heuristic, successors[i][1])] + current_path) if new: new_path = [] # [position, heuristic] heuristic = [(i, float(new[i][0][1])) for i in range(len(new))] # print('(position, heuristic)', heuristic) heuristic.sort(key=lambda x: x[1]) # sort by heuristic sort for i in range(len(heuristic)): new_path.append(new[heuristic[i][0]]) # print(new) # print('new_path:', new_path) return new_path return new # hill_climbing is an algorithm that uses heuristics and # takes the path which has the less heuristic node. For example: # Node, heuristic: (1,0.3) (2, 1) (3, 0.2) # 1 -> 2 (heuristic of 2 is 1) # 1 -> 3 (heuristic of 3 is 0.2) # since 0.2 < 1 the path is going to be updated as: # [(3, 1), (2, 1)] always the node with the less heuristic near # is going to be the first path, and so on. # problems of this algorithm: # - sensibility to heuristic (depends on the heuristic) # - sensibility to locals minimum (it search for minimum heuristic) # more info found in README.md on utility def hill_climbing(start, end, conn: Connections, nodes: Nodes): # new_path is a list where all the paths will be stored type of the node: (node_name, heuristic, weight) paths = [[(start, get_node_heuristic(start, nodes), 0)]] total_weight = 0 total_heuristic = 0 while paths != [] and paths[0][0][0] != end: # print('paths:', paths) exp = expansion_heuristic(paths[0], conn.successors(paths[0][0][0]), nodes) paths = exp + paths[1:] if paths: for i in paths[0]: total_weight += float(i[2]) total_heuristic += float(i[1]) return (list(reversed(paths[0])), total_weight, total_heuristic) if paths != [] else None
al = 0 gas = 0 di = 0 while (True): n = int(input()) if (n == 1): al+=1 if (n == 2): gas+=1 if (n == 3): di+=1 if (n == 4): break print('MUITO OBRIGADO') print(f'Alcool: {al}\nGasolina: {gas}\nDiesel: {di}')
import math a, b, c = input().split() a = float(a) b = float(b) c = float(c) delta = (b*b) - (4 * (a) * (c)) if (delta <= 0): print('Impossivel calcular') else: x1 = -b + math.sqrt(delta) x2 = -b - math.sqrt(delta) if ((x1 == 0) or (x2 == 0)): print('Impossivel calcular') else: x1 = x1 / (2*a) print(f'R1 = {x1:.5f}') x2 = x2 / (2*a) print(f'R2 = {x2:.5f}')
cod1, num1, val1 = input().split() cod2, num2, val2 = input().split() cod1 = int(cod1) cod2 = int(cod2) num1 = int(num1) num2 = int(num2) val1 = float(val1) val2 = float(val2) val = (int(num1) * float(val1)) + (int(num2) * float(val2)) print('VALOR A PAGAR: R$ %0.2f'%val)
import constants as c from pprint import pprint from card import Card from player import BridgePlayer class BridgeHuman(BridgePlayer): ''' A human bridge player class which inherits from Player. ''' def __init__(self, dealt, num, name=None): ''' dealt: a Deck of cards dealt to this player num: this player's player number name: an optional name field that defaults to f'Player {num}' ''' super().__init__(dealt, num, name) def play_card(self, round_suit=None): ''' Takes user input to play a card. round_suit is None if starting the round. ''' if round_suit is not None and round_suit.upper() not in c.SUITS: raise ValueError(c.red(c.SUIT_ERR)) # show user's cards on the screen (a dict of suits to cards) print('\nYour hand:\n') pprint(self.hand) # prompt user for input while True: user_input = input(c.USER_PROMPT).upper() # check input for type errors if not isinstance(user_input, str) or len(user_input) < 2: print(c.red(c.USER_INPUT_ERR)) continue user_rank = user_input[:-1] user_suit = user_input[-1] # check if inputs are valid ranks and suits if user_rank not in c.RANKS or user_suit not in c.SUITS: print(c.red(c.RANK_ERR)) print(c.red(c.SUIT_ERR)) continue # selected card card = Card(user_rank, user_suit) # error if user does not have that card if card not in self.hand[card.suit]: print(c.red(c.USER_NO_CARD_ERR)) continue # if user is starting the round if round_suit is None: # error if user is playing a trump card when not c.TRUMP_STARTED if card.suit == c.TRUMP_SUIT and not c.TRUMP_STARTED: print(c.red(c.USER_TRUMP_NOT_STARTED_ERR)) continue # if user is not starting the round and card.suit != round_suit if round_suit is not None and card.suit != round_suit: # error if user still has a card in round_suit if len(self.hand[round_suit]) > 0: print(c.red(c.USER_ROUND_SUIT_ERR)) print(c.red(f'Round suit: {c.SUITS[round_suit]}')) continue # if user plays a trump card, c.TRUMP_STARTED = True if card.suit == c.TRUMP_SUIT and not c.TRUMP_STARTED: c.TRUMP_STARTED = True # checks complete and chosen card is valid break # remove card from user's hand self.hand[card.suit].remove(card) print(c.yellow(f'\n{self.name} plays {card}')) return card
from art import logo # Calculator def add(a, b): return a + b def multiply(a, b): return a * b def subtract(a, b): return a - b def divide(a, b): if b == 0: return "invalid input" return a / b operations = { # key: symbol, value: method "+": add, "-": subtract, "*": multiply, "/": divide } def calculator(): # print(logo) num1 = float(input("What is the first number? \n")) for ops in operations: print(ops) should_continue = True while should_continue: operation_symbol = input("Pick an operation from the line above: ") num2 = float(input("What is the second number? \n")) required_function = operations[operation_symbol] # print(f"The required_function is {required_function.__name__}") answer = required_function(num1, num2) print(f"{num1} {operation_symbol} {num2} = {answer}") response = input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: \n") if response == 'y': num1 = answer if response == 'n': should_continue = False calculator() calculator() # operations[operation_symbol] gives the method value itself without calling it # to call the method, pass in the params # The Complete JavaScript Course 2021: From Zero to Expert! # Section 10, 130. Higher order and callback
# Code Exercise: Write a program that adds the digits in a 2 digit number. e.g. if the input was 35, then the output should be 3 + 5 = 8 two_digit_number = input("Type a two digit number: ") #################################### #Write your code below this line 👇 sum = 0; for d in two_digit_number: sum += int(d) print(sum) # Code Exercise: BMI Calculator height = input("enter your height in m: ") weight = input("enter your weight in kg: ") fWeight = float(weight) fHeight = float(height) bmi = fWeight / (fHeight ** 2) bmi_as_int = int(bmi) print(bmi_as_int) # Day 2 Project: Tip Calculator print("Welcome to the tip calculator") bill = input("What was the total bill?\n") tip = input("What percentage tip would you like to give? 10, 12, or 15?\n") num_of_ppl = input("How many people to split the bill?\n") tip_num = (int(tip)/100 + 1) result = (float(bill) / int(num_of_ppl)) * tip_num print(f"Each person should pay: ${round(result, 2)}")
##################### Extra Hard Starting Project ###################### import datetime as dt import pandas import random import os import smtplib # 1. Update the birthdays.csv NAME = "[NAME]" def send_email(content): my_email = "[email protected]" password = "1234abcd()" with smtplib.SMTP("smtp.gmail.com") as connection: connection.starttls() connection.login(user=my_email, password=password) connection.sendmail( from_addr=my_email, to_addrs=my_email, msg=f"Subject:Happy birthday!\n\n{content}") # 2. Check if today matches a birthday in the birthdays.csv now = dt.datetime.now() month = now.month day = now.day data = pandas.read_csv("birthdays.csv") data_dict = data.to_dict(orient="records") # 3. If step 2 is true, pick a random letter from letter templates and replace the [NAME] with the person's actual name from birthdays.csv # 4. Send the letter generated in step 3 to that person's email address. for data in data_dict: if data['month'] == month and data['day'] == day: random_file = random.choice(os.listdir("letter_templates")) # file_path = f"letter_templates/letter_{random.randint(1, 3)}.txt" # can use the file path to open as well with open(f"letter_templates/{random_file}") as file: letter = file.read() # produce a new string letter = letter.replace(NAME, f"{data['name']}") send_email(letter)
from tkinter import * def button_clicked(): text = input.get() if text != "": my_label.config(text=text) window = Tk() window.title("My First GUI Program") window.minsize(width=500, height=300) # Add paddings among widgets window.config(padx=20, pady=20) # Label my_label = Label(text="I Am a Label", font=("Arial", 24, "bold")) my_label.config(text="new text") my_label.pack() # my_label.place(x=100, y=200) my_label.grid(column=0, row=0) # add paddings for one widget my_label.config(padx=50, pady=50) # Button another_button = Button(text="New Button") # button.pack() # x: 2, y:0 another_button.grid(column=2, row=0) button = Button(text="Click Me", command=button_clicked) # button.pack() button.grid(column=1, row=1) # Entry input = Entry(width=10) # input.pack() input.grid(column=3, row=2) # keep window on screen # must be at the end of the program window.mainloop() # tkinter layout manager: # any widgets/components must use one of the following three in order for the item to show on screen # Pack: # by default, position each component as top down # can specify side # Place: # precise positioning # component.place(x=0, y=0) # Grid: preferred # rows: horizontal, columns: vertical # relative to other items, if there are no other grid, even specified as column=5, it will still place as 0 # can't mix up grid and pack in the same program # error: slaves managed by grid
from turtle import Screen, Turtle import time from snake import Snake # https://docs.python.org/3/library/turtle.html screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") # animate snake segments: turn animation off, screen will refresh when .update() screen.tracer(0) # create snake body snake = Snake() # control snake with a key press screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") is_game_on = True while is_game_on: # animate snake segments: update screen screen.update() time.sleep(0.5) # get snake to move snake.move() screen.exitonclick()
from turtle import Turtle MOVING_DISTANCE = 20 class Ball(Turtle): def __init__(self): super().__init__() self.penup() self.shape("circle") self.color("white") self.x_move = 10 self.y_move = 10 # initial. speed self.move_speed = 0.1 def move(self): new_x_cor = self.xcor() + self.x_move new_y_cor = self.ycor() + self.y_move self.goto((new_x_cor, new_y_cor)) # detect ball bounding at upper and lower wall def bounce_y(self): # move the y coordinate to be minus # then in while loop, move() will execute self.y_move *= -1 # bounce at the paddle def bounce_x(self): self.x_move *= -1 # increase speed when ball hits at the paddle self.move_speed *= 0.9 def reset_position(self): self.goto((self.x_move, self.y_move )) self.bounce_x() self.move_speed = 0.1
class Animal: def __init__(self): self.num_eyes = 2 self.legs = 4 def breathe(self): print("Inhale, exhale") # inheritance class Fish(Animal): def __init__(self): # inherit all attributes and methods from Animal class # The call to super() in the initialiser is recommended, but not strictly required. # as if the Animal object is already created but can be further modified super().__init__() self.skin = "blue" self.legs = 0 def swim(self): print("moving in water") def breathe(self): # do everything from the parent breath class super().breathe() print("doing this under water") nemo = Fish() nemo.swim() nemo.breathe() print(nemo.num_eyes) print(nemo.skin) print(nemo.legs)
class User: def __init__(self, name): self.name = name self.is_logged_in = False def is_authenticated_decorator(function): def wrapper(*args, **kwargs): if args[0].is_logged_in == True: # the function here refers to create_blog_post a function(args[0]) return wrapper @is_authenticated_decorator def create_blog_post(user): print(f"This is {user.name}'s new blog post.") new_user = User("angela") # without changing it to true, line 20 won't run new_user.is_logged_in = True new_user.create_blog_post(new_user) def logging_decorator(function): def wrapper(*args): print(f"the name of the function is {(function).__name__} with input of {args[0]}, {args[1]}, {args[2]} and tuple input of {args}") result = function(args[0], args[1], args[2]) print(f"The output is {result}") return wrapper @logging_decorator def guess_the_name(a, b, c): return a * b * c guess_the_name(1, 2, 3)
# -*- coding: cp1252 -*- #Importar el mdulo socket para abrir el canal de comunicacin import socket #Funcin principal def main(): localIP = "127.0.0.1" #Direccin IP del servidor localPort = 20001 #Puerto del servidor bufferSize = 1024 #Tamao del buffer msgFromServer = "Hola Cliente UDP :)" #Mensaje que enviar de respuesta bytesToSend = str.encode(msgFromServer) #Pasar el mensaje a bytes #Crear un Datagrama Socket UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) #Bind con la direccin y puerto UDPServerSocket.bind((localIP, localPort)) print("El servidor UDP est escuchando...") #Ciclo para que el servidor est "escuchando" while(True): bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)#RECVFROM: Recibe una peticin message = bytesAddressPair[0] #Mensaje del Cliente (Bytes) address = bytesAddressPair[1] #Direccin IP del Cliente (Bytes) clientMsg = "Mensaje del cliente:{}".format(message) clientIP = "Direcci IP del cliente:{}".format(address) #Mostrar mensaje y direcin IP print(".................................................") print(clientMsg) print(clientIP) print(".................................................") # Sending a reply to client UDPServerSocket.sendto(bytesToSend, address) #BYTESTOSEND: Lo que regresa al cliente #Sentencia para que cargue alguna funcin (MAIN) if __name__ == "__main__": main()
#!/usr/bin/env python # coding: utf-8 import re import sys sys.path.insert(0,'..') from advent_lib import * PATH = 'input.txt' def process_line(line): data = re.split('\s|-', line.replace(':', ''))[:-1] data[0] = int(data[0]) data[1] = int(data[1]) return data def check_1(minn, maxx, key, password): count = password.count(key) return 1 if (count >= minn and count <= maxx) else 0 def check_2(minn, maxx, key, password): check = sum([password[minn-1] == key, password[maxx-1] == key]) return 1 if check == 1 else 0 def solve(check): lines = read_file(PATH, dtype=str) count = 0 for idx, line in enumerate(lines): count += check(*process_line(line)) return count if __name__ == "__main__": print(solve(check_1)) print(solve(check_2))
import turtle from random import * t = turtle.Turtle() # turtle객체를 t로 지정한다. t.speed(0) def circleDraw(t, r, f, n) : # 원을 그리는 함수 정의 시작. circleDraw(터틀객체, 반지름, forward이동거리, 원의 수) turtle.colormode(255) for i in range(1, n+1) : # 1부터 매개변수 n까지 반복하는 반복문 시작 t.pencolor(randint(0,255), randint(0,255), randint(0,255)) t.circle(r) # 반지름 r의 원 그리기 t.forward(f) # f만큼 이동 while True: # 무한 반복 r = input("반지름 입력: ") # r만 따로 입력받는다. q입력을 통해 반복을 종료할 것이기 때문 if(r == "q"): # r에 q가 입력되었을 경우 break # 반복문 탈출 circleDraw(t, int(r), int(input("이동 거리 입력: ")), int(input("원의 갯수 입력: "))) # 지시한 만큼 circleDraw 실행
import turtle t = turtle.Turtle() # turtle객체를 t로 지정한다. def circleDraw(t, r, f, n) : # 원을 그리는 함수 정의 시작. circleDraw(터틀객체, 반지름, forward이동거리, 원의 수) for i in range(1, n+1) : # 1부터 매개변수 n까지 반복하는 반복문 시작 t.circle(r) # 반지름 r의 원 그리기 t.forward(f) # f만큼 이동 circleDraw(t, 50, 40, 4) # Test case 1 t.penup() t.goto(-200, 0) t.pendown() circleDraw(t, 60, 60, 3) # Test case 2 turtle.mainloop()
string=str(input()) words=string.split(' ') print(words) arr=[] for i in words: p=i[::-1] arr.append(p) print(*arr)
def distance(s1, s2): ''' >>> distance("cheese", "cheeso") 1 >>> distance("kitten", "sitting") 3 >>> distance("coffee", "coffee") 0 >>> distance("foo", "bar") 3 >>> distance("robot", "robotnik") 3 ''' if len(s1) == 0: return len(s2) if len(s2) == 0: return len(s1) if s1[-1] == s2[-1]: cost = 0 else: cost = 1 return min( distance(s1[:-1], s2) + 1, distance(s1, s2[:-1]) + 1, distance(s1[:-1], s2[:-1]) + cost )
# TIme complexity --> O(n logk) where n is the length of the nums #space complexity --> O(k) // Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : None Description: we create a minheap with k elements and then try to insert the other elements if they are greater than least element in the minheap.In this way traverse thorugh the whole loop and then at the end of the given list we end up with only three largest elements in the array. import heapq class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if nums==None or len(nums)==0: return 0 h=[] #convert the list to a heap heapq.heapify(h) #create a hep of k elements for i in range(k): heapq.heappush(h,nums[i]) #make the heap contain the three greatest numbers in the list for i in range(k,len(nums)): if nums[i]>h[0]: heapq.heappop(h) heapq.heappush(h,nums[i]) return heapq.heappop(h)
def LongSubstr(st): if len(st)==0: return 0 max_lst=[] s=set() # s={} this notation creates an empty dictionary # Be cautious of sets and dict for char in st: s.add(char) for i in range(0,len(st)-len(s)): x=set() x.update(st[i:i+len(s)]) max_lst.append(len(x)) return max(max_lst) print(LongSubstr('abcdabc')) print(LongSubstr('')) print(LongSubstr('aaanbfdfedd')) # time complexity of O(n) # expected output: in terms of length # 4 0 5
"""Customer Class""" import random import pandas as pd class Customer: """a single customer that moves through the supermarket in a MCMC simulation.""" STATES = ['checkout', 'dairy', 'drinks', 'entrance', 'fruit', 'spices'] TPM = pd.read_csv('tpm.csv', index_col=[0]) def __init__(self, name, state, budget=100): self.name = name self.state = state self.budget = budget def __repr__(self): return f'<Customer {self.name} in {self.state}>' def is_active(self): """returns True if the customer has not reached the checkout yet.""" return self.state != 'checkout' def next_state(self): """propagates the customer to the next state.""" transition_probs = Customer.TPM.loc[Customer.TPM.index==self.state].values[0] self.state = random.choices(Customer.STATES, weights=transition_probs)[0]
#!/usr/local/bin/python #Do a 1-D random walk and print the simple random walk #resulting from keeping a running sum of the value #of a random variable Z that is -1 or +1 with equal #probability. # Random walk: random variable Z is -1 with P = 0.5 # 1 with P = 0.5 # Simple random walk: random variable Sn = \sum_{i=1}^{n} Z_i # so that <S_n> = 0 # <S_n^2> = n import random import qchem as qc import cProfile NTrial = 10000 NStep = 5000 myFileName = "randomWalk.txt" getNewData = True #Print Sn to a file delimeted by carriage returns. def writeNewData(fileName,NStep,NTrial): outputFile = open(fileName,"w") iTrial = 0 outString = "" for iTrial in range(NTrial): myS = 0 for iStep in range(NStep): myS += 2*random.randint(0,1) -1 outString += str(myS)+"\n" if (iTrial%50==0): outputFile.write(outString) outString = "" outputFile.write(outString) outputFile.close() #Read and analyze the data def analyzeData(fileName): expectS = qc.coarseGrainAverage() expectS2 = qc.coarseGrainAverage() dataFile = open(fileName,"r") for myLine,line in enumerate(dataFile): myS = int(line) expectS.addQuantity(myS) expectS2.addQuantity(myS*myS) if (myLine%10000==0): expectS.consolidateBins() expectS2.consolidateBins() print "myLine = {}".format(myLine) ES = expectS.getAverage() ES2 = expectS2.getAverage() print "ES = {}, ES2 = {}".format(ES,ES2) if (getNewData): writeProfile = cProfile.Profile() writeProfile.enable() writeNewData(myFileName,NStep,NTrial) writeProfile.disable() writeProfile.print_stats() #cProfile.run(writeNewData(NStep,myFileName)) #cProfile.run(analyzeData(myFileName)) analyzeProfile = cProfile.Profile() analyzeProfile.enable() analyzeData(myFileName) analyzeProfile.disable() analyzeProfile.print_stats()
#!/usr/bin/python """ This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. Use a Naive Bayes Classifier to identify emails by their authors authors and labels: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("..\\tools") from email_preprocess import preprocess import numpy as np from sklearn.naive_bayes import GaussianNB ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() print 'features_train:', features_train print len(features_train) print 'features_test:', features_test print len(features_test) print 'labels_train:', labels_train print len(labels_train) print 'labels_test:', labels_test print len(labels_test) ######################################################### ### your code goes here ### X = np.array(features_train) Y = np.array(labels_train) clf = GaussianNB() clf.fit(features_train, labels_train) pred = clf.predict(features_test) assert len(pred) == len(labels_test) total = 0 for i in range(len(pred)): if pred[i] == labels_test[i]: total += 1 accuracy = float(total) / len(labels_test) print accuracy #########################################################
print("Everyone loves baseball! Go blue jays!") print("Welcome to the slugging percentage calculator!") name = raw_input("Enter the player's name: ") singles = float(input("Enter the number of singles " + name + " has hit: ")) doubles = float(input("Enter the number of doubles " + name + " has hit: ")) triples = float(input("Enter the number of triples " + name + " has hit: ")) homers = float(input("Enter the number of home runs " + name + " has hit: ")) ab = float(input("Enter the number of at bats " + name + " has had: ")) slug = float((singles + (2*doubles) + (3*triples) + (4*homers))/ab) print (name + "'s slugging percentage is " + str(slug))
def is_cross(a, b): return (a[1] < b[3] and a[3] > b[1] and a[2] < b[0] and a[0] > b[2]) result = is_cross([-5, 2, 3,-2], [2, 6, 5, 1]) print(result)
import math def jump_search(arr, n, x): step = math.sqrt(n) prev = 0 while (arr[min(step, n) < x]): prev = step; step += math.sqrt(n) if (prev >= n): return False while (arr[prev] < x): prev = prev + 1 if (prev == min(step, n)): return False if (arr[prev] == x): return True return False arr = [23,512,214,12,5,67,1,4,65] arr.sort(); result = jump_search(arr, len(arr), 1) print('Search Element is found', result)
''' class Myclass: x = 5 p1 = Myclass() print(p1.x) class Person: def __init__(self, name, age): self.name = name self.age = age def myfunction(self): print("My name is ", self.name + " and I am ", self.age,".") p1 = Person ("Jhon",38) p1.myfunction() p2 = Person ("sam",42) p2.myfunction() p1.age = 47 p1.myfunction() del p1 p2.myfunction() class Robot: def __init__(self, n, c, w): self.name = n self.color = c self.weight = w def introduce_self(self): print("My name is ",self.name, " and I like ", self.color) r1= Robot("Tom","red",38) r2= Robot("Jerry","blue",42) class Person: def __init__(self, n, p, i): self.name = n self.personality = p self.issitting = i def sit_down(self): self.issitting = True def Stand_up(self): self.issitting = False p1 = Person("alice", "aggresive", True) p2 = Person("becky", "talkitive", False) p1.Robot_owned = r2 p2.Robot_owned = r1 p1.Robot_owned.introduce_self() p2.Robot_owned.introduce_self() r1.introduce_self() r2.introduce_self() ''' # print("Hello, I am " , p1.name + " and I am ", p1.age ) # INHERITANCE : ''' class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def Printname(self): print(self.firstname, self.lastname) x = Person("Jhon","Doe") x.Printname() class Student(Person): pass x = Student("Mike","Olesn") x.Printname() class Student(Person): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.graduationyear = year def Printname(self): print("Welcome",self.firstname, self.lastname, "to the class of ", self.graduationyear ) x = Student("Sam", "Michel",2019) x.Printname() ''' # ITERATORS ''' my_tuple = ("apple", "banana", "cherry", "peach", "grapes") my_it = iter(my_tuple) for x in my_it: print(x) my_str = "banana" my_it = iter(my_str) for x in my_str: print(x) # create Iterator class Mynumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: b = self.a self.a += 1 return b else: raise StopIteration Myclass = Mynumbers() myiter = iter(Myclass) for x in myiter: print(x) ''' #SCOPE :- #LOCAL SCOPE def myfunc(): x = 300 print(x) myfunc() #FUNCTION INSIDE FUNCTION:- def myfunc(): x = 600 def myinnerfunc(): print(x) myinnerfunc() myfunc() #GLOBAL SCOPE & NAMING VARIABLES :- x = 700 def myfunc(): x = 900 print(x) myfunc() print(x) #GLOBAL KEYWORD def myfunc(): global x x = 500 myfunc() print(x) #CHANGE THE VALUE OF GLOAL VARIABLE INSIDE A FUNCTION: x = 200 def myfunc(): global x x = 1200 myfunc() print(x)
import tkinter as tk class Calculator(tk.Tk): def __init__(self): super().__init__() self.final_value = 'h' self.label_text = tk.StringVar() self.label_text.set('hello') self.label = tk.Label(self, textvariable=self.label_text, bg='white', fg='black', font=('arial', 25), relief='solid') self.plus_button = tk.Button(self, text='Plus(+)', command=lambda: self.plus_button_pressed()) self.minus_button = tk.Button(self, text='Minus(-)', command=lambda: self.minus_button_pressed()) self.multiply_button = tk.Button(self, text='Multiply(x,*)', command=lambda: self.multiply_button_pressed()) self.divide_button = tk.Button(self, text='Divide(/)', command=lambda: self.divide_button_pressed()) self.value_one = tk.Entry(self) self.value_two = tk.Entry(self) self.label.place(relx=0.1, rely=0.7, relwidth=0.8, relheight=0.2) #self.label.place(x=100, y=125) self.plus_button.place(x=0, y=75) self.minus_button.place(x=125, y=75) self.multiply_button.place(x=250, y=75) self.divide_button.place(x=375, y=75) self.value_one.place(x=50, y=25) self.value_two.place(x=250, y=25) def plus_button_pressed(self): text_in_text_field_one = self.value_one.get() text_in_text_field_two = self.value_two.get() value_one_float = float(text_in_text_field_one) value_two_float = float(text_in_text_field_two) final_float_value = value_one_float+value_two_float print(value_one_float+value_two_float) # Update the text in the label self.label_text.set(final_float_value) def minus_button_pressed(self): text_in_text_field_one = self.value_one.get() text_in_text_field_two = self.value_two.get() value_one_float = float(text_in_text_field_one) value_two_float = float(text_in_text_field_two) final_float_value = value_one_float-value_two_float print(value_one_float+value_two_float) # Update the text in the label self.label_text.set(final_float_value) def multiply_button_pressed(self): text_in_text_field_one = self.value_one.get() text_in_text_field_two = self.value_two.get() value_one_float = float(text_in_text_field_one) value_two_float = float(text_in_text_field_two) final_float_value = value_one_float * value_two_float print(value_one_float * value_two_float) #Update the text in the label self.label_text.set(final_float_value) def divide_button_pressed(self): text_in_text_field_one = self.value_one.get() text_in_text_field_two = self.value_two.get() value_one_float = float(text_in_text_field_one) value_two_float = float(text_in_text_field_two) final_float_value = value_one_float / value_two_float print(value_one_float / value_two_float) # Update the text in the label self.label_text.set(final_float_value) if __name__ == '__main__': app = Calculator() app.title('Calculator') app.geometry('500x200') # Make a calculator app like the one shown in the calculator.png image # HINT: you'll need: # 1. a new class # 2. a StringVar variable # 3. Two tk.Entry widgets, four tk.Button widgets, and one tl.Label widget app.mainloop() pass
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2, c = 0): result = None while l1 and l2: l3 = ListNode((l1.val + l2.val + c) % 10) c = int((l1.val + l2.val + c) / 10) if result == None: result = l3; else: temp.next = l3; temp = l3; l1 = l1.next l2 = l2.next return result l1 = ListNode(2) l1.next = ListNode(4) l1.next.next = ListNode(3) l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(4) result = Solution().addTwoNumbers(l1, l2) while result: print(result.val) result = result.next # 7 0 8
q = 0 while q < 10: q = q + 1 print(q) if q == 6: continue
names = [ 'John', 'Jack', 'Jimmy', 'V', 'Chinu', 'Wosimosi' ] print( names ) print( names[3] ) names[3] = 'Diana' print( names ) #-------------For loop-------------- for name in names: print(name) for name in names: greeting = 'Hi ' + name print(greeting) for name in names: if len(name)>7: print(name)
''' Cities on a map are connected by a number of roads. The number of roads between each city is in an array and city is the starting location. The number of roads from city to city is the first value in the array, from city to city is the second, and so on. How many paths are there from city to the last city in the list, modulo ? Example There are roads to city , roads to city and roads to city . The total number of roads is . Note Pass all the towns Ti for i=1 to n-1 in numerical order to reach Tn. Function Description Complete the connectingTowns function in the editor below. connectingTowns has the following parameters: int n: the number of towns int routes[n-1]: the number of routes between towns Returns int: the total number of routes, modulo 1234567. Input Format The first line contains an integer T, T test-cases follow. Each test-case has 2 lines. The first line contains an integer N (the number of towns). The second line contains N - 1 space separated integers where the ith integer denotes the number of routes, Ni, from the town Ti to Ti+1 Constraints 1 <= T<=1000 2< N <=100 1 <= routes[i] <=1000 ''' #!/bin/python3 import os import sys # # Complete the connectingTowns function below. # def connectingTowns(n, routes): # # Write your code here. # from functools import reduce totalRoutes = reduce(lambda x, y: x * y % 1234567, routes) # totalRoutes = 1 # for i in routes: # totalRoutes = (totalRoutes * i) % 1234567 return totalRoutes if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) routes = list(map(int, input().rstrip().split())) result = connectingTowns(n, routes) fptr.write(str(result) + '\n') fptr.close()
# Reads CityPop, stores it in dictionaries, finds the population of a city # at a specific year import csv import os.path filename = 'CityPop.csv' # Make city_data into list city_data = [] # If filename is bad, tell the user if not os.path.isfile(filename): print("File does not exist.") # Open CityPop using DictReader, which stores each row as a dictionary with open(filename, 'r') as f: reader = csv.DictReader(f) # Make each row into a separate dictionary for row in reader: city_data.append(row) # Ask for city name city_input = input("Enter the city name. ") # Assume city not found as default city_found = False for row in city_data: # If city input matches a city in a dictionary, continue asking for input if city_input == row['label']: yr_input = input("Enter the year. ") yr_input = 'yr' + yr_input # Change city to found city_found = True # If year input doesn't match a dictionary key, announce fail if yr_input not in row: print("Year not in data.") # If year input matches a dictionary key, print result if yr_input in row: print("The population in", yr_input, "was", row[yr_input], "million.") # If city still not found, announce fail if not city_found: print("City name not found in data.")
""" A multiclass classification CNN model in tensorflow-2 using Dropout and BatchNormalization. Also data augmentation is used here. """ #Import libraies.............. import tensorflow as tf import numpy as np from sklearn.metrics import confusion_matrix import itertools import matplotlib.pyplot as plt from tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, Dropout, GlobalAveragePooling2D, MaxPooling2D, BatchNormalization from tensorflow.keras.models import Model #Load the data and scale it................. cifar = tf.keras.datasets.cifar10 (x_train, y_train), (x_test, y_test) = cifar.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 y_train, y_test = y_train.flatten(), y_test.flatten() print("x_train shape....", x_train.shape) print("y_train shape....", y_train.shape) #Number of classes................... K = len(set(y_train)) print("Number of classes........",K) #Build the CNN using functional API................... #comment layers are used in first time training (without data augmentation). i = Input(shape = x_train[0].shape) x = Conv2D(32, (3,3), activation = 'relu', padding = 'same')(i) x = BatchNormalization()(x) x = Conv2D(32, (3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2))(x) #x = Dropout(0.2)(x) x = Conv2D(64, (3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = Conv2D(64, (3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2))(x) #x = Dropout(0.2)(x) x = Conv2D(128, (3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = Conv2D(128, (3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2))(x) #x = Dropout(0.2)(x) #x = GlobalAveragePooling2D()(x) x = Flatten()(x) x = Dropout(0.2)(x) x = Dense(1024, activation = 'relu')(x) x = Dropout(0.2)(x) x = Dense(K, activation = 'softmax')(x) model = Model(i, x) print(model.summary()) #Compile and fit the model..................... model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy']) r = model.fit(x_train, y_train, validation_data = (x_test, y_test), epochs = 10) #Plot the loss........... plt.plot(r.history['loss'], label = 'loss') plt.plot(r.history['val_loss'], label = 'val_loss') plt.legend() plt.show() #Plot the accuracy............... plt.plot(r.history['accuracy'], label = 'accuracy') plt.plot(r.history['val_accuracy'], label = 'val_accuracy') plt.legend() plt.show() #Fit the model with data augmentation #Remember:: If you run this after first fit, it will continue training where it left off. batch_size = 32 data_generator = tf.keras.preprocessing.image.ImageDataGenerator(width_shift_range = 0.1, height_shift_range = 0.1, horizontal_flip = True) train_generator = data_generator.flow(x_train, y_train, batch_size) steps_per_epochs = x_train.shape[0] // batch_size r = model.fit_generator(train_generator, validation_data = (x_test, y_test), steps_per_epoch = steps_per_epochs, epochs = 7) #Plot the loss........... plt.plot(r.history['loss'], label = 'loss') plt.plot(r.history['val_loss'], label = 'val_loss') plt.legend() plt.show() #Plot the accuracy............ plt.plot(r.history['accuracy'], label = 'accuracy') plt.plot(r.history['val_accuracy'], label = 'val_accuracy') plt.legend() plt.show() #Plot the confusion matrix............. def plot_confusion_matrix(cm, classes, normalize = False, title = 'ConfusionMatrix',cmap = plt.cm.Blues): if normalize: cm = cm.astype('float') / cm.sum(axis = 1)[:, np.newaxis] print("with normalization........") else: print("without normalization") print(cm) plt.imshow(cm, interpolation = 'nearest', cmap = cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation = 45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i,j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i,j], fmt), horizontalalignment = 'center', color = 'white' if cm[i,j] > thresh else 'black') plt.tight_layout() plt.ylabel("True Label") plt.xlabel("Predicted Label") plt.show() p_test = model.predict(x_test).argmax(axis = 1) cm = confusion_matrix(y_test, p_test) plot_confusion_matrix(cm, list(range(10))) #Show some misclassified examples................... mis = np.where(p_test != y_test)[0] i = np.random.choice(mis) plt.imshow(x_test[i], cmap = 'gray') plt.title("True label: %s Predicted label: %s" %(y_test[i], p_test[i])) plt.show()
#sudo pip install Theano import theano import theano.tensor as T import numpy from theano import function #Variables 'x' and 'y' are defined x = T.dscalar('x') # dscalar : Theano datatype y = T.dscalar('y') # 'x' and 'y' are instances of TensorVariable, and are of dscalar theano type print(type(x)) print(x.type) print(T.dscalar) # 'z' represents the sum of 'x' and 'y' variables. Theano's pp function, pretty-print out, is used to display the computation of the variable 'z' z = x + y from theano import pp print(pp(z))
# Tuples = Lists ; but in tupe it can't be changed like how we can in lists... It is a sequence of Immutable Python objects. # Tuples use Parentheses (or comma), whereas lists use square-brackets. num_list=[1,3,6,8,4] print(num_list) num_list[1] = 2 print(num_list) print (len(num_list)) num_tuple= 1,3,6,8,4 print(num_tuple) num_list[1] = 2 print(num_tuple) print (len(num_tuple))
# Count the number of prime numbers less than 2000 and time it. import time as t start = t.clock() primes = [2,3,5,7] for num in xrange(2,200000): if all(num%x != 0 for x in primes): primes.append(num) print primes print (t.clock() - start, "Seconds.") print (len(primes), "Primes") print (sum(primes), "is the sum of all these prime numbers.") # # Count the number of prime numbers less than 2000 and time it. # # from time import clock # from math import sqrt # # count = 0 # def count_primes(n): # ''' # Generates all the primes from 2 to n-1' # n-1 is the largest potential prime considered. # ''' # # start = clock() # Record Start time. # # count = 0 # for val in range(2, n): # result = True # Provisionally, n is prime. # root = int(sqrt(val) + 1) # # trial_factor = 2 # while result and trial_factor <= root: # result = (val % trial_factor != 0) # trial_factor += 1 # if result: # count += 1 # # # stop = clock() # Stop the Clock. # print("Count = ", count, "Elapsed Time:", stop - start, "seconds") # # # def lol(n): # start = clock() # # nonprimes = n * [False] # # count = 0 # # nonprimes[0] = nonprimes[1] = True # # for i in range(2, n): # if not nonprimes[i]: # count += 1 # for j in range(2 * i, n, i): # nonprimes[j] = True # # stop = clock() # print("Count = ", count, "Elapsed Time:", stop - start, "seconds") # # # def main(): # count_primes(2000) # lol(2000) # # # main()
# Implement a tuple of elements of all the 4 different data types, 3 examples of each type :- # str # bool # int # float int_tuple= 1,2,6,8,4 print(int_tuple) str_tuple= "lively","alone","friends","enemies" print(str_tuple) bool_tuple = True,False,None print(bool_tuple) float_tuple = 2.04,42.2006,1.7,12.12,26.8,27.5 print(float_tuple)
# Dictionary is a set of key-value pairs. # It is enclosed in curly braces (or flower brackets). a = {1:'number one', 22 : 'number twenty-two'} # Here 1 and 22 are keys and 'number one' and 'number twenty-two' are their values respectively. print(a) print(a[1]) print(a[22]) dict_employee = {"Employee_name": "Ravi", "Designation":"Vice President", "Age" : "34"} print (dict_employee) # Updating the dictionary. dict_employee ["Employee_name"] = "Ravi Chandra" dict_employee ["Designation"] = "CEO" print (dict_employee) del dict_employee["Age"] # comment this if you want to see "clear" work and then uncomment the clear. print(dict_employee) # dict_employee.clear() # print(dict_employee) print(dict_employee) dict_employee.update({"Hometown":"Hyderabad"}) print(dict_employee) print (dict_employee.keys()) print (dict_employee.values())
# concept - Loops => 1.While loop count=0 while count <= 100: # Condition if count%10==0 : print (count) count = count + 1 print ("\n") count=0 while count <= 100: # Condition if count%20==2 : print (count) count = count + 1 else: print ("not divided") k = (int(input("Give a number :"))) if k==100: print("(: A Century!!...") else: print ("Not a century :(.")
""" email_alerts.py Eva Grench, 22 February 2018 Sends an html email from the server with a table of all the rules that had anomalous values, the number of anomalous values under that rule, and a link to view the results on the anomalies dashboard. It is sent to a google group. """ import os from email.mime.text import MIMEText from email.message import EmailMessage import requests import datetime import time BACKEND_URL = os.environ.get("BASE_URL") or 'http://energycomps.its.carleton.edu/api/' FRONTEND_URL = 'http://energycomps.its.carleton.edu/' TO_EMAIL = os.environ.get("TO_EMAIL") or '[email protected]' def get_date(num_days_before_today): """ Calculates what yesterday's date was using today's date (this is under the assumption we are sending it the next morning. :return: Yesterday's day as a string in the format year-month-day """ current_date = datetime.datetime.now().date() # Change the int timedelta takes in to change how many days we want to subtract timedelta = datetime.timedelta(num_days_before_today) return str(current_date - timedelta) def get_date_url(): """ Encodes the date range so that when the user clicks the link they are taken to the relevant results page. Currently this is manually done which is not great, but is because they do it differently in Python. :return: The (javascript style) encoded date range as a string """ current_time = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) # Change the int timedelta takes in to change how many days we want to subtract timedelta = datetime.timedelta(days=1) start_date = str(int(time.mktime((current_time - timedelta).timetuple())) * 1000) end_date = str(int(time.mktime((current_time).timetuple())) * 1000) date_as_javascript_ecoded_url = '&date_range%5BstartDate%5D=' + start_date +\ '&date_range%5BendDate%5D=' + end_date return date_as_javascript_ecoded_url def get_anomalous_rules(): """ Gets all the rules and then finds all the rules for which a value flagged that rule and puts it in a list. :return: The list of rules that were broken yesterday """ rules = requests.get(BACKEND_URL + 'rules').json() anomalous_rules = [] for rule in rules: response = requests.get(BACKEND_URL + 'rule/' + str(rule['rule_id']) + '/count') # This is case where the values haven't been imported into the database yet. if response.status_code == 404: exit(1) # Error on the backend, so we will tell them that there was an error. if response.status_code == 500: rule['num_anomalies'] = 0 anomalous_rules.append(rule) break num_anomalies = response.json() if num_anomalies > 0: rule['num_anomalies'] = num_anomalies anomalous_rules.append(rule) return anomalous_rules def construct_anomalies_table(anomalous_rules): """ Gets all the relevant information for constructing the table in the message by getting the rule name, count, and link for each rule. :param anomalous_rules: The list of rules that actually have anomalies associated with them. :return: The html codes that will be the table (and main sources of information) in the email. """ anomalies_table = '' for rule in anomalous_rules: anomalies_table += '<tr>\n<td>' + rule['rule_name'] + '</td>' if rule['num_anomalies'] == 0: anomalies_table += '<td>Error occurred in the database</td>' else: anomalies_table += '<td>' + str(rule['num_anomalies']) + '</td> ' url = FRONTEND_URL[:-1] + str(rule['url']) + get_date_url() link = '<td><a href="' + url + '">view more</a></td>' anomalies_table += link + '</tr>\n' return anomalies_table def construct_msg_body_as_html(): """ Makes the body of the email sent to facilities. Lists out all the rules, the number of values that broke that rule, and the link to see the rule in greater context. :return: A string that will be the body of the email. """ anomalous_rules = get_anomalous_rules() # This is the case were no anomalies were sent. if len(anomalous_rules) == 0: return '' anomalies_table = construct_anomalies_table(anomalous_rules) html = """ <html> <head></head> <body> <p>The rules broken yesterday, the number of values that flagged that rule, and the link to view more are as follows.<br><br> <table border="1" cellspacing="0" cellpadding="5"> <tr> <th>Rule Name</th> <th>Number of Anomalous Values</th> <th>Link to Dashboard</th> </tr> {code} </table> </p> </body> </html> """.format(code=anomalies_table) html_email = MIMEText(html, 'html') return html_email def send_email(msg_body): """ Sends the email if there is something in the body. The email is sent from the energy-comps email and to a google group with relevant people in facilities. (NOT CURRENTLY HOW IT IS DONE) :param msg_body: A string that will be the body of the email. """ # In this case, no anomalies were found, so we should not send the email. if msg_body == '': print('No email was sent because there were no anomalies.') return message = EmailMessage() message['Subject'] = 'Anomalies detected on ' + get_date(1) message.set_content(msg_body) # pipe the mail to sendmail sendmail = os.popen('/usr/sbin/sendmail ' + TO_EMAIL, 'w') sendmail.write(message.as_string()) if sendmail.close() is not None: print('Error: Failed to send email.') def main(): send_email(construct_msg_body_as_html()) if __name__ == '__main__': main()
a = int(input()) print(a >= 10 and a <100) print(10 <= a < 100)
a = int(input()) b = int(input()) c = int(input()) if a > b and a > c: max = a if b > c: mid = b min = c else: mid = c min = b print(max) print(min) print(mid) elif b > a and b > c: max = b if a > c: mid = a min = c else: mid = c min = a print(max) print(min) print(mid) elif c > a and c > b: max = c if a > b: mid = a min = b else: mid = b min = a print(max) print(min) print(mid) elif a == c and b == c: max = a min = b mid = c print(max) print(min) print(mid) elif a == b and (c < a or c < b): max = a min = c mid = b print(max) print(min) print(mid) elif a == b and (c > a or c > b): max = c min = a mid = b print(max) print(min) print(mid) elif a == c and (b < a or b < c): max = a min = b mid = c print(max) print(min) print(mid) elif a == c and (b > a or b > c): max = b min = a mid = c print(max) print(min) print(mid) elif b == c and (a < b or a < c): max = b min = a mid = c print(max) print(min) print(mid) elif b == c and (a > b or a > c): max = a min = b mid = c print(max) print(min) print(mid)
x=str(input("enter the char : ")) i=( x>='a' and x<'z')or(x>='A' and x<='Z') if(i): print("alphabet") else: print("no")
from tkinter import * from tkinter import ttk import tkinter.font as tkFont import time class SampleTkinterLoop: def __init__(self, master): # Initialize master as the Tk() instance self.master = master master.title("Loop Tests") master.config(background="#e8ecf2") master.geometry("568x480") # Create main frame as app self.app = ttk.Frame(self.master) self.app.pack(fill=X) # Create a custom font self.mainFont = tkFont.Font( family="Helvetica", size=14, weight=tkFont.NORMAL) self.boldFont = tkFont.Font( family="Helvetica", size=14, weight=tkFont.BOLD) # Initialize flags for background of the labels change self.bgCounter = 0 def test1(self): x = Label( self.app, text=f'Test case 1', background=self.bgChooser(), foreground="#a5120d", font=self.boldFont) x.pack(fill=X) self.bgCounter += 1 self.master.update() # allow window to catch up time.sleep(2) x.config(foreground="#000", font=self.mainFont) def test2(self): x = Label( self.app, text=f'Test case 1', background=self.bgChooser(), foreground="#a5120d", font=self.boldFont) x.pack(fill=X) self.bgCounter += 1 self.master.update() # allow window to catch up time.sleep(2) x.config(foreground="#000", font=self.mainFont) def test3(self): x = Label( self.app, text=f'Test case 1', background=self.bgChooser(), foreground="#a5120d", font=self.boldFont) x.pack(fill=X) self.bgCounter += 1 self.master.update() # allow window to catch up time.sleep(2) x.config(foreground="#000", font=self.mainFont) def test4(self): x = Label( self.app, text=f'Test case 1', background=self.bgChooser(), foreground="#a5120d", font=self.boldFont) x.pack(fill=X) self.bgCounter += 1 self.master.update() # allow window to catch up time.sleep(2) x.config(foreground="#000", font=self.mainFont) def test5(self): x = Label( self.app, text=f'Test case 1', background=self.bgChooser(), foreground="#a5120d", font=self.boldFont) x.pack(fill=X) self.bgCounter += 1 self.master.update() # allow window to catch up time.sleep(2) x.config(foreground="#000", font=self.mainFont) def repeatIt(self): for i in range(0, 5): # self.anotherLoop() self.test1() self.test2() self.test3() self.test4() self.test5() self.reset() self.master.update() time.sleep(1) print(i) def bgChooser(self): if (self.bgCounter % 2) == 0: return str("#fff") return str("#e8ecf2") def reset(self): for child in self.app.winfo_children(): child.destroy() root = Tk() LoopTest = SampleTkinterLoop(root) LoopTest.repeatIt() root.mainloop()
import RPi.GPIO as GPIO ## Import GPIO library import time ## Import 'time' library. Allows us to use 'sleep' GPIO.setmode(GPIO.BOARD) ## Use board pin numbering GPIO.setup(7, GPIO.IN) ## Setup GPIO Pin 7 to OUT inp = GPIO.input(7) while True: if GPIO.input(17): print "button pressed"
# ----------------------------------------------------------- # prompts a user to input their specification and returns the object of their input. # (C) 2020 Mahmudul Alam # Released under Colorado State University-Global Campus # email [email protected] # ----------------------------------------------------------- def userInput(): # Calls for an infinite loop that keeps executing # until an exception occurs while True: name = input("What's your name? ") describe=input('Describe the specification you want to look into: ') try: rate = int(input("From 0 to 4, how important would you rate it: " )) # If something else that is not the string # version of a number is introduced, the # ValueError exception will be called. except ValueError: # The cycle will go on until validation print("Error! This is not a number. Try again.") # the loop will end. else: rate_all=['Easy','Medium','Hard','Difficult','Extremely Difficult'] print("Impressive,", name, "You have mentioned:",describe,".We will further take a look into this request.---", rate_all [rate] ) break userInput() # ----------------------END-----------------------#
# coding: utf-8 # In[95]: import csv import pprint import re import codecs import xml.etree.cElementTree as ET import json from collections import defaultdict import unicodedata # In[96]: # the OSM data file OSM_FILE = "hochiminh_city.osm" # the JSON file JSON_FILE = "hochiminh_city.json" # In[97]: ''' Function insert_space_between_words() is written to fix this issue, it will add a space character next to a LOWERCASE letter which is followed by an UPPERCASE letter. We expect insert_space_between_words("ThuDuc") = "Thu Duc" ''' def insert_space_between_words(text): if text != None: # convert text into a list chars = list(text.strip()) # loop through each character of text # if there is any UPPERCASE character is next to a LOWERCASE character --> add index of LOWER character into a list ls_indexes = [] for i in range(len(chars) -1): if chars[i].islower() and chars[i+1].isupper(): ls_indexes.append(i+1) # now we have a list of indexes # we need to add a space character at each index in the list if len(ls_indexes) > 0: for index in reversed(ls_indexes): chars.insert(index, " ") # join all item of character list, we will have a string, then return it return ''.join(chars) else: return "" # In[98]: ''' Function to convert the accented characters to unaccented characters. ''' def replace_accented_characters(text): accent_chars = "ŠŽšžŸÀÁÂÃÄÅẤẦẨẪẬĂẶẲẰẮÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáãạảẵặằắăâậẫẩầấãäåçẻẽẹèéệễểềếểêëịĩỉìíîïðñọõỏòóộôõồöỗổốợỡởờớơủũụùúựữửứừưûüỹỵỳýÿĐđ" non_accent_chars = "SZszYAAAAAAAAAAAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaaaaaaaaaaaaaaceeeeeeeeeeeeeiiiiiiidnooooooooooooooooooouuuuuuuuuuuuuyyyyyDd" for char in text: if char in accent_chars: text = text.replace(char, non_accent_chars[accent_chars.index(char)]) return text # In[99]: ''' It will get v value of an element which has k value is k_name. It will find the tag has k value is k_name, then return the v value of that tag if it existing. ''' def get_value_of_k(element, k_name): result = None tag = element.find("tag[@k='" + k_name + "']") if tag != None: result = tag.get('v') return result # In[100]: ''' Purpose: This function is used for auditing data of a k value. This function will loop through each element and call function get_value_of_k() to get v value of k. The outcome would be the list of unique values of those v values ''' def audit_data_of_k(file_in, k_name): data = [] for element in get_element(file_in, tags=('node', 'way')): v = get_value_of_k(element, k_name) if v != None: data.append(v) return sorted(list(set(data))) # In[101]: ''' This function will create a regular expression for a string. We will use this function to create regular expression for a PROVINCE or a CITY name. ''' def create_regex(text): reg = '' if text != None and text != "": reg = "\w*.*\s*" + text + "\s*.*\w*" return reg # In[102]: ''' This function will create a list regular expression for a list of strings. It will loop through each string in the list, call function create_regex_for_text() to create regular expression for that string. All regular expressions created will be store in another list. ''' def create_list_regex(list_text): regex = [] if len(list_text) > 0: for item in list_text: regex.append(create_regex(item.lower())) return regex # In[103]: ''' Purpose: will replace a existing name with a expected name. Input parameters: - requires 3 input parameters: + name: string type. + list_regex: is a list regular expression created from the list of variants. + list_expected_names: is a list expected names created from the list of variants and would be used to replace. *Note: before process the name, need to fix the problems of 1.1 and 1.2. ''' def replace_name_with_expected_name(name, list_regex, list_expected_names): result = None for regex in list_regex: match = re.match(regex, replace_accented_characters(insert_space_between_words(name)), re.IGNORECASE) if match != None: result = list_expected_names[list_regex.index(regex)] break return result # In[105]: ''' This function just be used to create a regular expression for DISTRICTS since DISTRICT has some specific prefixes which are different from PROVINCE or CITY. Following are all prefixes would be used for DISTRICT: ["quan", "quan ", "district ", "d.", "d. ", "d ", "d", "q.", "q. ", "q", "qan ", "huyen " , "^"] ''' DISTRICT_PREFIXES = ["quan", "quan ", "district ", "d.", "d. ", "d ", "d", "q.", "q. ", "q", "qan ", "huyen " , "^"] def create_reg_for_a_district(text, prefixes): reg = [] for item in prefixes: reg.append(item + text) return '|'.join(reg) ''' This function will create a list of regular expressions for a list of DISTRICTS. It will call the function make_reg_for_district() to create regular expression for each DISTRICT in list_districts, then output are stored in another list. ''' def create_list_regex_for_districts(list_districts, dist_prefixes): result = [] district_lowercase = [ item.lower().strip() for item in list_districts ] for district in district_lowercase: reg = create_reg_for_a_district(district, dist_prefixes) reg += "|" + create_regex("quan " + district) reg += "|" + create_regex("huyen " + district) result.append(reg) return result # In[84]: ''' This function will display a location name in the pretty format like 'Ho Chi Minh City', 'District 1', 'Dong Nai Province'... It requires 2 input parameters: - name: the name of location. - unit_type: the type of location, it would be "district" or "city" or "province". If the name is a numeric value, the output would be: name + unit_type If not, the output would be: unit_type + name''' def format_name(name, unit_type): result = "" if name != None and name != "": if unit_type.lower() in ("district", "city", "province"): if name.isnumeric(): result = (unit_type + " " + name).title() else: if name.lower() == "ho chi minh": unit_type = "city" result = (name + " " + unit_type).title() return result # In[85]: ''' Purpose: This function will correct the "v" value in <tag> which has "k" = key_name. Input parameters: - element: the focusing element. - key_name: the value of "k" atribute in a <tag> of element - list_regex: list regular expression would be used for function replace_name_with_expected_name() - list_expected_text: list expected text would be used for function replace_name_with_expected_name() What it is going to do is actually call all above function. - if there is any <tag> existing: + if <tag> has k value is the key_name: + unit_type = key_name[5:] since we are focusing on 3 keys ["addr:province", "addr:city", "addr:district"] so unit_type would be "province" or "city" or "district". + call function replace_variant_with_expected_name() to replace with the expected name. + format name in the pretty format. + update the attribute "v" the formatted name. ''' def correct_addr_parts_name(element, k_value, list_regex, list_expected_names): tag = element.find("tag[@k='" + k_value + "']") if tag != None: # get the unit_type unit_type = k_value[5:] # get the expected name of item expected_name = replace_name_with_expected_name(tag.attrib['v'], list_regex, list_expected_names) # format the expected name in the pretty format pretty_name = format_name(expected_name, unit_type) # update the value of v the pretty_name tag.set('v', pretty_name) # In[86]: # postcodes of PROVINCES POSTCODES_PROVINCE = {'Ho Chi Minh City' : '700000', 'Vung Tau Province' : '790000', 'Dong Nai Province' : '810000', 'Binh Duong Province' : '590000', 'Tien Giang Province' : '860000', 'Long An Province' : '850000' } # postcodes of CITIES POSTCODES_CITY = {'Ho Chi Minh City' : '700000', 'Vung Tau City' : '790000', 'Bien Hoa City' : '810000', 'Thu Dau Mot City' : '590000', 'My Tho City' : '860000', 'Tan An City' : '850000' } # postcodes of Ho Chi Minh's DISTRICTS POSTCODES_HCM_DISTRICT = { 'Binh Chanh District' : '709000', 'Binh Tan District' : '709300', 'Binh Thanh District' : '704000', 'Can Gio District' : '709500', 'Cu Chi District' : '707000', 'Go Vap District' : '705500', 'Hoc Mon District' : '707500', 'Nha Be District' : '708500', 'Phu Nhuan District' : '704500', 'District 1' : '701000', 'District 10' : '703500', 'District 11' : '706500', 'District 12' : '707800', 'District 2' : '708300', 'District 3' : '701500', 'District 4' : '702000', 'District 5' : '702500', 'District 6' : '703000', 'District 7' : '708800', 'District 8' : '706000', 'District 9' : '708400', 'Tan Binh District' : '705000', 'Tan Phu District' : '705800', 'Thu Duc District' : '708000' } # In[87]: # set v=v_value for the tag which has k=k_value def update_v_for_k(element, k_value, v_value): tag = element.find("tag[@k='" + k_value + " ']") if tag != None: tag.set('v', v_value) # insert a new <tag k=k_value v=v_value> for an element def insert_new_tag(element, k_value, v_value): new_tag = ET.Element('tag') if element.find("tag[@k='" + k_value + " ']") == None: new_tag.attrib['k'] = k_value new_tag.attrib['v'] = v_value element.insert(0, new_tag) # delete a tag which has k=k_value from an element def delete_a_tag(element, k_value): tag = element.find("tag[@k='" + k_value + "']") if tag != None: element.remove(tag) ''' Function to correct POSTCODE value for an element. The idea here is we are just focusing on elements which has tag of "addr:province" or "addr:city" or "addr:district" or "addr:postcode". Then we will do: - Step 1: get the POSTCODE value by PROVINCE or CITY or DISTRICT name. + if the element has tag of DISTRICT, the POSTCODE would be taken from dictionary POSTCODES_HCM_DISTRICT. + if the element has tag of CITY, the POSTCODE would be taken from dictionary POSTCODES_CITY. + if the element has tag of PROVINCE, the POSTCODE would be taken from dictionary POSTCODES_PROVINCE. so result of this step is a POSTCODE value. It would be a value of one of above dictionaries or None. - Step 2: check whether this element has tag of POSTCODE. + if it has and: - POSTCODE value of Step 1 is None, then we will delete that tag. - POSTCODE value of Step 1 is NOT None, then we will update the POSTCODE value into the "v" attribute of the tag. + if it does NOT and POSTCODE value of Step 1 is NOT None, we will add a new tag for POSTCODE with the value of Step 1. ''' def correct_postcode_for_element(element, hcm_district_postcodes, city_postcodes, province_postcodes): postcode = None # list of k values of all tags that element has. # we are just focusing on values of "addr:province", "addr:city", "addr:district", "addr:postcode" k = [ tag.attrib['k'] for tag in element.findall("tag") if tag.attrib['k'] in ("addr:province", "addr:city", "addr:district", "addr:postcode")] #################################### START STEP 1 #################################### # if element has at least one of those values if len(k) > 0: # get the POSTCODE by DISTRICT if tag of "addr:district" available in the node if "addr:district" in k: district = get_value_of_k(element, "addr:district") if district in hcm_district_postcodes: postcode = hcm_district_postcodes[district] else: # get the POSTCODE by CITY if tag of "addr:city" available in the node if "addr:city" in k: city = get_value_of_k(element, "addr:city") if city in city_postcodes: postcode = city_postcodes[city] else: # get the POSTCODE by PROVINCE if tag of "addr:province" available in the node if "addr:province" in k: province = get_value_of_k(element, "addr:province") if province in province_postcodes: postcode = province_postcodes[province] #################################### END STEP 1 #################################### # so now we have a POSTCODE value, it would be None or NOT None. #################################### START STEP 2 #################################### #### decide to insert or update or delete the tag of POSTCODE if "addr:postcode" in k and postcode == None: # if element has tag of POSTCODE and postcode value = None --> delete the tag delete_a_tag(element, "addr:postcode") elif "addr:postcode" in k and postcode != None: # if element has tag of POSTCODE and postcode value not None --> update the tag update_v_for_k(element, "addr:postcode", postcode) elif "addr:postcode" not in k and postcode != None: # if element does not has tag of POSTCODE and postcode value not None --> add new tag for POSTCODE insert_new_tag(element, 'addr:postcode', postcode) #################################### END STEP 2 #################################### # In[107]: ''' this function will convert the v value from string to a list ''' def value_to_list(element, k_name): result = [] v = get_value_of_k(element, k_name) if v != None: if ";" in v: result = v.split(";") else: result.append(v) return result ''' The idea is one element should have only one tag for CUISINE and the k value would be 'cuisine' and v value would be a list. Here are steps which I will follow: - Step 1: check whether element has tag for "cuisine" and "cuisine_1" - Step 2: + if element has tag for "cuisine", convert v value into a list. + if element has tag for "cuisine_1", convert v value into a list. + adding 2 above lists then we will have the result for this step. - Step 3: update v value for tag of "cuisine". - Step 4: delete the tag of "cuisine_1" if the element has. ''' def correct_cuisine_for_element(element): # get list k values of tags that element has # we are just focusing on the k values of "cuisine" and "cuisine_1" k1 = [ tag.attrib['k'] for tag in element.findall("tag") if tag.attrib['k'] in ("cuisine" ,"cuisine_1")] # if the element has at least one of those k values if len(k1) > 0: values = [] if 'cuisine' in k1: values = value_to_list(element, 'cuisine') if 'cuisine_1' in k1: values += value_to_list(element, 'cuisine_1') # update values for tag of 'cuisine' update_v_for_k(element, 'cuisine', values) # remove the tag of 'cuisine_1' delete_a_tag(element, 'cuisine_1') # In[89]: ''' SHAPING NODE ELEMENT. The result of one NODE would be a dictionary which has: - keys: are attributes of the node and the 'k' values of all tags - values: are the attributes' values and the 'v' values of all tags. Since the element is a NODE, so the result should have "type": "node". Ex: the result of the following node: <node id="1001114531" lat="10.8035794" lon="106.7021517" version="3" timestamp="2016-12-05T01:00:20Z" changeset="44169736" uid="4923449" user="Eddy Thiện"> <tag k="tourism" v="guest_house"/> <tag k="internet_access" v="wlan"/> </node> should be: { 'changeset': '44169736', 'id': '1001114531', 'internet_access': 'wlan', 'lat': '10.8035794', 'lon': '106.7021517', 'timestamp': '2016-12-05T01:00:20Z', 'tourism': 'guest_house', 'uid': '4923449', 'user': 'Eddy Thiện', 'version': '3', 'type': 'node' } Below is the function to extract the data of an element into a dictionary. ''' def extract_element_data_to_dict(element): result = defaultdict() if element != None: # get data of all attributes result = element.attrib # get v values of all the <tag> which element has if element.findall("tag") != None: for tag in element.findall("tag"): result[tag.attrib['k']] = tag.attrib['v'] # get tag name of the element result['type'] = element.tag return result # In[90]: ''' SHAPING WAY ELEMENT. The result of one WAY would be a dictionary which has: - keys: are attributes of the node and the 'k' values of all tags - values: are the attributes' values and the 'v' values of all tags. Since the element is a NODE, so the result should have "type": "node". The difference of WAY from the NODE is WAY has number of tags <nd>, each tag <nd> is a NODE ID which related to the WAY. The result should have "nodes" : [....] Ex: the result of the following WAY <way id="311787604" version="1" timestamp="2014-11-08T16:50:29Z" changeset="26646253" uid="509465" user="Dymo12"> <nd ref="2339295659"/> <nd ref="2339295662"/> <nd ref="2339295673"/> <nd ref="2339295675"/> <nd ref="2339295678"/> <nd ref="2339295679"/> <nd ref="2339332736"/> <nd ref="2339295680"/> <nd ref="2339332752"/> <nd ref="2339295685"/> <nd ref="2339332759"/> <nd ref="2339295689"/> <nd ref="2339332766"/> <nd ref="2339332772"/> <nd ref="2339332776"/> <tag k="highway" v="residential"/> </way> should be: { 'id': '311787604', 'version': '1', 'timestamp': '2014-11-08T16:50:29Z', 'changeset': '26646253', 'uid': '509465', 'user': 'Dymo12', 'highway': 'residential', 'nodes': ['2339295659', '2339295662', '2339295673', '2339295675', '2339295678', '2339295679', '2339332736', '2339295680', '2339332752', '2339295685', '2339332759', '2339295689', '2339332766', '2339332772', '2339332776'], 'type': 'way' } ''' def extract_way_data_to_dict(way): # reuse the function used for NODE to extract data of WAY result = extract_element_data_to_dict(way) # since WAY element might have number of <nd> # if element has any <nd>, get ref values and store them in a list if way.findall("nd") != None: list_ref = [nd.attrib['ref'] for nd in way.findall("nd")] result['nodes'] = list_ref return result # In[91]: def shape_element(element, province_regex, city_regex, district_regex, province_expected, city_expected, district_expected, province_postcodes, city_postcodes, hcm_district_postcodes): # correct the PROVINCE names correct_addr_parts_name(element, "addr:province", province_regex, province_expected) # correct the CITY names correct_addr_parts_name(element, "addr:city", city_regex, city_expected) # correct the DISTRICT names correct_addr_parts_name(element, "addr:district", district_regex, district_expected) # correct POSTCODE correct_postcode_for_element(element, hcm_district_postcodes, city_postcodes, province_postcodes) # correct CUISINE correct_cuisine_for_element(element) # shape element data if element.tag == "node": return extract_element_data_to_dict(element) elif element.tag == "way": return extract_way_data_to_dict(element) # In[92]: #################################### CASE STUDY's FUNCTION #################################### def get_element(osm_file, tags=('node', 'way')): """Yield element if it is the right type of tag""" context = ET.iterparse(osm_file, events=('start', 'end')) _, root = next(context) for event, elem in context: if event == 'end' and elem.tag in tags: yield elem root.clear() # In[106]: # list variant names of PROVINCE PROVINCE_VARIANTS = ['binh duong', 'vung tau', 'ho chi minh', 'hcm', 'long an', 'tien giang', 'dong nai'] # list expected names of PROVINCE PROVINCE_EXPECTED = ['Binh Duong', 'Vung Tau', 'Ho Chi Minh', 'Ho Chi Minh', 'Long An', 'Tien Giang', 'Dong Nai'] # list variant names of CITY CITY_VARIANTS = ['vung tau', 'ho chi minh', 'saigon','hcm','hcmc', 'ho chi min', 'bien hoa', 'thu dau mot', 'my tho', 'tan an'] # list expected names of CITY CITY_EXPECTED = ['Vung Tau', 'Ho Chi Minh', 'Ho Chi Minh', 'Ho Chi Minh', 'Ho Chi Minh', 'Ho Chi Minh', 'Bien Hoa', 'Thu Dau Mot', 'My Tho', 'Tan An'] # list expected names of DISTRICT DISTRICT_EXPECTED = ['1', '10', '11', '12', '2', '3', '4', '5', '6', '7', '8', '9', 'Binh Chanh', 'Binh Tan', 'Binh Thanh', 'Can Gio', 'Cu Chi', 'Go Vap', 'Hoc Mon', 'Nha Be', 'Phu Nhuan', 'Tan Binh', 'Tan Phu', 'Thu Duc'] ''' Before shaping element data, we need to create the list of regular expressions which will be use to correct values of PROVINCE, CITY and DISTRICT. ''' #################################### CASE STUDY's FUNCTION #################################### def process_map(file_in): # create list of regular expressions for PROVINCES province_regex = create_list_regex(PROVINCE_VARIANTS) # create list of regular expressions for CITIES city_regex = create_list_regex(CITY_VARIANTS) # create list of regular expressions for DISTRICTS district_regex = create_list_regex_for_districts(DISTRICT_EXPECTED, DISTRICT_PREFIXES) # list data of all elements data = [] # open JSON file for writting data with codecs.open(JSON_FILE, encoding='utf-8', mode='w') as file: for element in get_element(file_in, tags=('node', 'way')): el = shape_element(element, province_regex, city_regex, district_regex, PROVINCE_EXPECTED, CITY_EXPECTED, DISTRICT_EXPECTED, POSTCODES_PROVINCE, POSTCODES_CITY, POSTCODES_HCM_DISTRICT) # add data of each element into list data.append(el) # writting data into JSON file file.write(json.dumps(data, indent=2)) # In[94]: if __name__ == '__main__': # Note: Validation is ~ 10X slower. For the project consider using a small # sample of the map when validating. process_map(OSM_FILE) # In[ ]:
import turtle from random import * s=1 while (s>0): turtle.forward(20) turtle.left(randint(0, 360))
#!/usr/bin/env python def calc_birthday_prob(n): ''' Calculates the probability of at least two people in a group of size n having the same birthday. INPUTS: n (integer): number of people in the group OUTPUTS: p (float): probability of matching birthday ''' prob = 1 for x in range(1, n): prob *= (365 - x)/365 return 1 - prob if __name__ == '__main__': for x in range(60): print(x, calc_birthday_prob(x))
def is_permutation(str1, str2): if len(str1) != len(str2): return False myList1 = [] myList2 = [] for i in range(0, len(str1)): myList1.append(str1[i]) myList2.append(str2[i]) myList1.sort() myList2.sort() if myList1 == myList2: return True return False word1 = "ass" word3 = "ssa" print(is_permutation(word1, word3))
numberOfPeople = raw_input("How many people are coming: ") pizzaPrice = 10 juicePrice = 10 costPerPerson = pizzaPrice + juicePrice totalCost = int(numberOfPeople) * costPerPerson print totalCost