text
stringlengths
37
1.41M
# master_02.py # coding: utf-8 ''' itertools - 标准库之一 1. 创建无限迭代器 itertools.count(1),以1为间隔的等差数列 2. 创建无限迭代器 itertools.cycle('ABC'), 以ABC为循环的数列 3. 创建有限迭代器 itertools.repeat('A',10), 循环A 10次 4. 可以通过takewhile截取 比如 n= itertools.count(1) ns = itertools.takewhile(lambda x: x<10, n) 5. chain()可以将2个迭代器连起来: n1 = itertools.cycle('ABC') n2 = itertools.cycle('XYZ') itertools.chain(n1, n2) 6. 注意:迭代器定义的时候是不产生无限个迭代元素的,只有在for语句中才产生。 7. groupby可以把迭代器中相邻的重复元素挑出来放在一起 8. itertools的使用示例: 可以用简单的一句话做成4个元素的排列组合 races = itertools.permutations(horse) ''' import itertools def test1(): n = itertools.count(1) for i in n: print i # will create an inf list def raceHorse(): horse =['a','b','c','d'] races = itertools.permutations(horse) print races print list(races) print type(list(races)) def raceNumber(): print list(itertools.permutations([1,2,3,4],2)) if __name__ == '__main__': raceHorse() raceNumber()
# tips_08.py # coding: utf-8 ''' time.time() ''' import time start = time.time() for i in range(3000): print i end = time.time() print start,end print end - start
# test_lintcode_easy_02.py # coding: utf-8 ''' 给一个整数 c, 你需要判断是否存在两个整数 a 和 b 使得 a^2 + b^2 = c. 样例 给出 n = 5 返回 true // 1 * 1 + 2 * 2 = 5 给出 n = -5 返回 false ''' def checkTriage(n): for i in range(n): for j in range(n): if i**2 + j**2 == n: return True return False if __name__ == '__main__': n = 5 if checkTriage(n) == True: print 'PASS' else: print 'Fail' if checkTriage(9) == False: print 'PASS' else: print 'Fail'
# test_lintcode_easy_03.py # coding: utf-8 ''' 给出两个字符串,你需要找到缺少的字符串 样例 给一个字符串 str1 = This is an example, 给出另一个字符串 str2 = is example 返回 ["This", "an"] ''' def findMissString(str1,str2): l1 = str1.split(' ') l2 = str2.split(' ') result_list = [] if len(l1) > len(l2): for item in l1: if item not in l2: result_list.append(item) else: for item in l2: if item not in l1: result_list.append(item) return result_list if __name__ == '__main__': str1 = 'This is an example' str2 = 'is example' if findMissString(str1, str2 ) == ['This','an']: print 'Pass' else: print 'Fail'
# test_4.py # coding: utf-8 ''' 从终端读入一个整数n,随机一个输入一个0 或1 判断连续是0 或1 的最大次数。如: 输入 0 0 0 1 1 1 1 0 1 0 1在连续输入中,出现4次 利用之前分解数组的知识。。。 ''' class Stack: def __init__(self,yourstring): self.items = [] for item in yourstring: self.items.append(item) self.items.reverse() def push(self,data): self.items.append(data) def pop(self): self.items.pop() def onTop(self): return self.items[-1] def __len__(self): return len(self.items) def __getitem__(self,index): return self.items[index] def max_count(yourstring): s1 = Stack(yourstring) print s1.items temp = 0 maxcount = 0 start = s1.onTop() print start while len(s1) > 1: s1.pop() if s1.onTop() == start: temp += 1 else: start = s1.onTop() print 'temp', temp if temp>maxcount: maxcount = temp return maxcount # test13.py # coding: utf-8 ''' 比如列表[0,0,0,1,1,2,3,3,3,2,3,3,0,0]分割成[0,0,0],[1,1],[2],[3,3,3],[2],[3,3],[0,0] ''' ''' 思路: 1. 取出第一组相同元素,返回相同元素组成的数组,和pos 2. 去掉第一组元素,从pos开始 yourlist[pos:] 3. 循环取出第一组相同元素,直到len(yourlist)>1 (还有数组) ''' def parse_list(yourlist): result_list = [] def get_first_list(yourlist): new_list = [] for i in range(0,len(yourlist)): if yourlist[i] == yourlist[0]: new_list.append(yourlist[i]) else: return new_list, i return new_list,i pos=1 while not pos==0: result,pos= get_first_list(yourlist) result_list.append(result) yourlist = yourlist[pos:] if result_list[-1]==[0]: return result_list[:-1] else: return result_list ''' 最后连续2个相同元素的还需要再调下。思路不太清楚了。 ''' def test_parse_list(): yourlist = [0,0,0,1,1,2,3,3,3,2,3,3,0,0,5] max_count = 0 def get_max_count(yourlist): max_count = 0 for item in parse_list(yourlist): if len(item) > max_count: max_count = len(item) print 'max_count is ', max_count if __name__ == '__main__': print 'Give your 01 string' str1 = raw_input() yourlist = [] for item in str1: yourlist.append(item) get_max_count(yourlist) # if __name__ == '__main__': #
# test_class.py # coding: utf-8 ''' 类,多态,继承 定义一个Point类 - 各种方法,+ ''' class Point: def __init__(self,x,y): self.x, self.y = x, y def set(self,x,y): self.x, self.y = x,y def __f(): pass def __str__(self): return 'I am a Point, x is {0}, y is {1}'.format(self.x, self.y) def __add__(self,other): return Point(self.x+other.x, self.y+other.y) # 重载了+运算符 # print type(Point) # print dir(Point) #['__doc__', '__init__', '__module__', 'set'] # p = Point(10,10) # print type(p) # print dir(p) # print p # t = Point(20,20) # print p+t import math class Shape: def area(self): return 0.0 class Circle(Shape): def __init__(self, r=0.0): self.r = r def area(self): return math.pi*self.r*self.r # 一旦 Circle 定义了自己的 area,从 Shape 继承而来的那个 area 就被重写(overwrite) class Rectangle(Shape): def __init__(self, w=0.0, h=0.0): self.w = w self.h = h # def area(self): # # return self.w * self.h # pass def area(self): return self.w * self.h if __name__ == '__main__': c1 = Circle(10) print c1.area() rect1 = Rectangle(4,5) print rect1.area() print Shape.__dict__['area'] # 三个地址不同 print Circle.__dict__['area'] print Rectangle.__dict__['area']# 如果Rectangle不重写父类的方法,则地址一致
#!/usr/bin/env python #coding:utf8 import sys def addr2dec(addr): items = [int(x) for x in addr.split('.')] return sum([items[i] << [24, 16, 8, 0][i] for i in range(4)]) def dec2addr(dec): return '.'.join([str(dec >> x & 0xff) for x in [24, 16, 8, 0]]) if __name__ == '__main__': if len(sys.argv) == 3: if sys.argv[1] == 'addr': print addr2dec(sys.argv[2]) elif sys.argv[1] == 'dec': print dec2addr(int(sys.argv[2])) else: print "Usage: %s [addr|dec] ip|num" else: print "Usage: %s [addr|dec] ip|num"
print("Welcome to your life decider") print("***********") progress_count = 0 trailer_count = 0 retreiver_count = 0 excluded_count = 0 # creating cells def create_cells(count_type): print(" ", end=" ") if row<(count_type): print("*", end=" ") else: print(" ", end=" ") print(" ",end = " ") # arguements to take the inputs done=False # The boolean flag that indicates if we are finished with the work. This will help us loop the program till we are finished with the work. try: while done==False: Pass = int(input("Please enter your credit at pass: ")) while Pass not in [0, 20, 40, 60, 80, 100, 120]: # https://stackoverflow.com/questions/12553609/how-to-test-that-variable-is-not-equal-to-multiple-things - this is how I created this code. print("Out of range!") Pass = int(input("RETRY! It should be in 0,20,40,60,80,100,120 range.\nPlease enter your credit at pass: ")) Defer = int(input("Please enter your credit at defer: ")) while Defer not in [0, 20, 40, 60, 80, 100, 120]: print("Out of range!") Defer = int(input("RETRY! It should be in 0,20,40,60,80,100,120 range.\nPlease enter your credit at defer: ")) Fail = int(input("Please enter your credit at fail: ")) while Fail not in [0, 20, 40, 60, 80, 100, 120]: print("Out of range!") Fail = int(input("RETRY! It should be in 0,20,40,60,80,100,120 range.\nPlease enter your credit at fail: ")) total_marks = Pass + Defer + Fail if total_marks != 120: print("Total incorrect! Please try again.") else: #logics to sort out the progression outcome. if Fail + Defer <= 20: if Fail + Defer == 0: print("Progress") progress_count=progress_count+1 else: print("Progress(module trailer)") trailer_count=trailer_count+1 elif Fail >= 80: print("Exclude") excluded_count=excluded_count+1 else: print("Do not progress - module retriever") retreiver_count=retreiver_count+1 runAgain =input("Enter y to continue. Enter q to quit and view results: ") while runAgain!="y" or runAgain!="q": if runAgain == "y": done=False break elif runAgain=="q": done=True print("Thank you for using the program") break else: print("Wrong input. check again.") runAgain = input("Enter y to continue. Enter q to quit and view results: ") except ValueError: print("integer rquired! Please try again.") print("_____________________________________________") print("") print("_____________________________________________") print("") h = max(progress_count, excluded_count, retreiver_count, trailer_count) total_count=progress_count+trailer_count+retreiver_count+excluded_count print("Progress",progress_count,"Trailer",trailer_count,"Retreiver",trailer_count,"Excluded",trailer_count) #looping row by row for row in range(h): #printing a cells in a row create_cells(progress_count) create_cells(trailer_count) create_cells(retreiver_count) create_cells(excluded_count) print("",end="\n") #breaking the line so the loop can start in a new row. print("Total count is ",total_count)
# Name : Md Ashiqur Rahman # Student Number : 998419242 #Look for <<<...>>> tags in this file. These tags indicate changes in the #file to implement the required routines. Some mods have been made some others #you have to make. Don't miss addressing each <<<...>>> tag in the file! ''' 8-Puzzle STATESPACE State Space Representation: <<<8-Puzzle: Give a brief description of the state space representation you have choosen in your implementation >>>8-Puzzle: ''' from search import * class eightPuzzle(StateSpace): StateSpace.n = 0 def __init__(self, action, gval, state, parent = None): """state is supplied as a list of 9 numbers in the range [0-8] generate an eightPuzzle state. Create an eightPuzzle state object. The 9 numbers in state specify the position of the tiles in the puzzle from the top left corner, row by row, to the bottom right corner. E.g.: [2, 4, 5, 0, 6, 7, 8, 1, 3] represents the puzzle configuration |-----------| | 2 | 4 | 5 | |-----------| | | 6 | 7 | |-----------| | 8 | 1 | 3 | |-----------| """ StateSpace.__init__(self, action, gval, parent) #<<<8-Puzzle: build your state representation from the passed data below self.state = state #>>>8-Puzzle: build your state representation from the passed data above def successors(self) : """Implement the actions of the 8-puzzle search space.""" #<<<8-Puzzle: Your successor state function code below # IMPORTANT. The list of successor states returned must be in the ORDER # Move blank down move, move blank up, move blank right, move blank left # (with some successors perhaps missing if they are not available # moves from the current state, but the remaining ones in this # order!) #>>>8-Puzzle: Your successor state function code above States = [] i = self.state.index(0) # check for down if i + 3 < 9: new_state = self.state[0:i] + [self.state[i+3]] + self.state[i+1:i+3] + [self.state[i]] + self.state[i+4:] States.append(eightPuzzle('Move blank down', self.gval+1, new_state, self)) # check for up if i - 3 > -1: new_state = self.state[0:i-3] + [self.state[i]] + self.state[i-2:i] + [self.state[i-3]] + self.state[i+1:] States.append(eightPuzzle('Move blank up', self.gval+1, new_state, self)) # check for right: if (i % 3) + 1 < 3: new_state = self.state[0:i] + [self.state[i+1]] + [self.state[i]] + self.state[i+2:] States.append(eightPuzzle('Move blank right', self.gval+1, new_state, self)) # check for left if (i % 3) - 1 > -1: new_state = self.state[0:i-1] + [self.state[i]] + [self.state[i-1]] + self.state[i+1:] States.append(eightPuzzle('Move blank left', self.gval+1, new_state, self)) return States def hashable_state(self) : #<<<8-Puzzle: your hashable_state implementation below return tuple(self.state) #>>>8-Puzzle: your hashable_state implementation above def print_state(self): if self.parent: print "Action= \"{}\", S{}, g-value = {}, (From S{})".format(self.action, self.index, self.gval, self.parent.index) else: print "Action= \"{}\", S{}, g-value = {}, (Initial State)".format(self.action, self.index, self.gval) #<<<8-Puzzle: print the state in an informative way below #>>>8-Puzzle: print the state in an informative way above #<<<8-Puzzle: below you will place your implementation of the misplaced #tiles heuristic and the manhattan distance heuristic #You can alter any of the routines below to aid in your implementation. #However, mark all changes between #<<<8-Puzzle ... and >>>8-Puzzle tags. #>>>8-Puzzle eightPuzzle.goal_state = False def eightPuzzle_set_goal(state): '''set the goal state to be state. Here state is a list of 9 numbers in the same format as eightPuzzle.___init___''' eightPuzzle.goal_state = state #<<<8-Puzzle: store additional information if wanted below #>>>8-Puzzle: store additional information if wanted above def eightPuzzle_goal_fn(state): #Assume that the goal is a fully specified state. #<<<8-Puzzle: your implementation of the goal test function below return state.state == eightPuzzle.goal_state #>>>8-Puzzle: your implementation of the goal test function above def h0(state): #a null heuristic (always returns zero) return 0 def h_misplacedTiles(state): #return a heurstic function that given as state returns the number of #tiles (NOT INCLUDING THE BLANK!) in that state that are #not in their goal position #<<<8-Puzzle: your implementation of this function below misplaced_tiles = 0 for i in range(0,9): if (state.state[i] != eightPuzzle.goal_state[i] and state.state[i] != 0): misplaced_tiles += 1 return misplaced_tiles #>>>8-Puzzle: your implementation of this function above def h_MHDist(state): #return a heurstic function that given as state returns #the sum of the manhattan distances each tile (NOT INCLUDING #THE BLANK) is from its goal configuration. #The manhattan distance of a tile that is currently in row i column j #and that has to be in row i" j" in the goal is defined to be # abs(i - i") + abs(j - j") #<<<8-Puzzle: your implementation of this function below index_to_cordinate = [[1,1], [1,2], [1,3], [2,1], [2,2], [2,3], [3,1], [3,2], [3,3]] distance = 0 for i in range(0,9): index_actual = eightPuzzle.goal_state.index(state.state[i]) if (index_actual != i and state.state[i] != 0): distance += abs(index_to_cordinate[i][0] - index_to_cordinate[index_actual][0]) + abs(index_to_cordinate[i][1] - index_to_cordinate[index_actual][1]) return distance #>>>8-Puzzle: your implementation of this function above #<<<8-Puzzle: Make sure the sample code below works when it is uncommented #se = SearchEngine('astar', 'none') #s0 = eightPuzzle("START", 0, [1, 0, 2, 3, 4, 5, 6, 7, 8]) #eightPuzzle_set_goal([0, 1, 2, 3, 4, 5, 6, 7, 8]) #se.trace_on(1) #print '1' #se.search(s0, eightPuzzle_goal_fn, h0) #print '2' #se.search(s0, eightPuzzle_goal_fn, h_misplacedTiles) #print '3' #s1 = eightPuzzle("START", 0, [8, 7, 6, 0, 4, 1, 2, 5, 3]) #se.search(s1, eightPuzzle_goal_fn, h_MHDist) #print '4' #se.set_strategy('astar', 'full') #se.search(s1, eightPuzzle_goal_fn, h_MHDist) ## Note that this problem can take a long time...30 seconds of CPU on my mac-mini. #print '5' #se.search(s1, eightPuzzle_goal_fn, h_misplacedTiles) #>>>8-Puzzle: Make sure the sample code above works when it is uncommented
a= 3 if a < 5: print("less than 5") elif a == 5 : print("equal to 5") else: print ("greter than 5") def age_foo(age): new_age = age+ 50 return new_age age = int(input("enter you age: ")) if age < 150: print(age_foo(age)) else: print("how is that possible?")
# Dependencies import string import sys import re # Files to load and output input_file = "paragraph_1.txt" output_file = "paragraph_analysis.txt" # Read text file paragraph_text = open(input_file, 'r') paragraph_data = paragraph_text.read() # Find the number of words in the text file character_count = len(paragraph_data) spaces = paragraph_data.count(' ') character_count_no_spaces = character_count - spaces word_count = len(paragraph_data.split()) # Find the number of sentences by feeding text into findall(); it returns a list of all the found strings sentence_count = len(re.findall(r'\.', paragraph_data)) # Find the average letter count average_letter_count = character_count_no_spaces/word_count # Find average sentence length average_sentence_len = word_count/sentence_count # Store paragraph analysis as variable, round down results to 3 decimal places, and print to terminal paragraph_analysis = ( f"\nParagraph Analysis\n" f"--------------------\n" f"Approximate word count is: {word_count}\n" f"Approximate sentence count is: {sentence_count}\n" f"Average letter count (per word) is: {average_letter_count:.3f}\n" f"Average sentence length is: {average_sentence_len:.0f} words \n") print(paragraph_analysis, end="") # Export the paragraph analysis to a text file sys.stdout = open(output_file, 'w') print(paragraph_analysis)
# -*- coding: utf-8 -*- from pila import Pila operadores=['*','+','-','/','='] #Pruebas de validacion de carácteres def esVariable (caracter): if caracter.isupper(): if caracter.isalpha(): return True return False def esNumero (caracter): try: caracter = int(caracter) return True except ValueError: return False def esOperador(caracter): for x in operadores: if caracter == x: return True return False #Inicio del proceso class Elemento: pilaC = Pila() dic = [] listaC = [y.split(' ') for y in [x.strip('\n') for x in open("caracteres.txt", 'r').readlines()]] f = False for x in listaC: for element in x: if esVariable(element) == True or esNumero(element) == True or esOperador(element) == True: for s in dic: for y in s: if y == element: element = s[1] if (element == '+' or element == '-' or element == '*' or element == '/'): if pilaC.es_vacia()==False: puntderecho=(pilaC.desapilar()) else: print "Error de sintaxis" f=True break if pilaC.es_vacia()==False: puntizquierdo=(pilaC.desapilar()) else: print "Error de sintaxis" f=True break if (esNumero(puntderecho)==True and esNumero(puntizquierdo)==True): puntder=int(puntderecho) puntizq=int(puntizquierdo) else: print ("Variable No definida") f=True break if element=='+': pilaC.apilar(puntizq + puntder) if element=='-': pilaC.apilar(puntizq - puntder) if element=='*': pilaC.apilar(puntizq * puntder) if element=='/': if(puntder == 0): print("Error de compilacion: Division por 0") f=True break else: pilaC.apilar(puntizq / puntder) else: if(element == '='): if pilaC.es_vacia()==False: m = pilaC.desapilar() else: print "Error de sintaxis " f=True break if pilaC.es_vacia()==False: n = pilaC.desapilar() else: print "Error de sintaxis " f=True break if(pilaC.es_vacia() == False): print "Error de sintaxis " f=True break dic.append([m,n]) if(element != '='): pilaC.apilar(element) else: print "El caracter (", element , ") No se reconoce" f = True break else: if(pilaC.es_vacia() == False): print "Error de sintaxis" f=True break continue break if f == False: for x, y in dic: print x ,"=", y
N=int(input()) for c in range(2,N): if(N%c==0): print("no") break else: print("yes")
a=int(input()) sum=0 for c in range(1,a+1): sum=sum+c print(sum)
age = int(input("What is your age? ")) if age >=18: print("Your age is {:d}". format(age)) print("Adult!") elif age >=6: print("Your age is {:d}". format(age)) print("Teenager!") else: print("Your age is {:d}".format(age)) print("Baby!") ###################### BMI CALCULATOR ##################### weight = float(input("What is your weight in kg? ")) height = float(input("What is your height in cm? ")) def bmi_calc(weight, height): bmi = weight/((height/100)**2) if bmi >=30: print("Your BMI is {}.".format(bmi)) print("Go run! You're obese ") elif bmi >=25: print("Your BMI is {}.".format(bmi)) print("You are overweight!") elif bmi >=18.5: print("Your BMI is {}.".format(bmi)) print("You are normal!") elif bmi <18.5: print("Your BMI is {}.".format(bmi)) print("Eat more!") bmi_calc(weight, height) ### Prof. Solution ### # if bmi <= 18.5: # print("your bmi is {:f}. Underweight".format(bmi)) # elif bmi > 18.5 and bmi <= 25: # print("your bmi is {:f}. normal".format(bmi)) # elif 25 < bmi <= 29.9: # print("your bmi is {:f}. overweight".format(bmi)) # else: # print("your bmi is {:f}. obese".format(bmi)) ########################## RECURSION ########################
# fin = open('words.txt') # line = fin.readline() # print(line) # print(repr(line)) #prints the /n after the word. fin = open('C:/Users/jboenawan1/Documents/Fall 2017/Problem Solving & Design/Python-Programming-MIS3640/session10-dictionary_exercise/words.txt') for line in fin: word = line.strip() # print (word) ############ EXERCISE 1 ############ def findlongwords(): """ prints only the words with more than 20 characters """ fin = open("words.txt") for line in fin: word = line.strip() if len(word) > 20: return word, len(word) # print(findlongwords()) def has_no_e(word): """ returns true if the given word doesn't have the letter "e" in it """ word = str(word) # for letter in word: # if letter.lower() != "e": # return True # return False return not "e" in word.lower() # print(has_no_e("Babson")) # print(has_no_e("College")) def find_words_no_e(): fin = open("words.txt") counter_no_e = 0 counter_total = 0 for line in fin: counter_total +=1 word = line.strip() if has_no_e(word): # print(word) counter_no_e += 1 return (counter_no_e/counter_total)*100 # print("The percentage of the words with no 'e' is {.2f}%.".format(find_words_no_e())) def avoids(word, forbidden): for letter in word: if letter.lower() in forbidden: return False return True forbidden = input("Enter a string of forbidden words: ") print(avoids("string babble", forbidden)) # print(avoids("Babson", "ab")) # print(avoids("College", "ab")) def find_words_no_vowel(): fin = open("words.txt") counter_no_vowel = 0 counter_total = 0 for line in fin: counter_total +=1 word = line.strip() if avoids(word, "aeiou"): # print(word) counter_no_vowel += 1 return (counter_no_vowel/counter_total)*100 # print("The percentage of the words with no vowel is {.2f}%.".format(find_words_no_vowel())) ############## EXERCISE 2 ############### def is_abecedarian(word): previous = word[0] for c in word: if c < previous: return False previous = c return True def is_abecedarian(word): if len(word) <=1: return True if word[0] > word[1]: return False return is_abecedarian(word[1:]) def is_abecedarian(word): the = 0 while the < len(word)-1: if word[the+1] < word[the]: return False the += 1 return True print(is_abecedarian("idkwhatthisis")) print(is_abecedarian("abcdef"))
Python3基础知识9(模块与包简单概念) (1)模块 #简单来讲:一个.py文件就称之为模块(Module)   注意:模块名就是py文件名(不包括.py) 比如test.py 模块化的好处: #1、以库(比如selenium库)形式封装功能,方便给别的代码调用;     库其实就是模块和包     可以使用自己写的库,Python标准库,第三方库 #2、避免变量名冲突(包括函数名)   如果一个代码文件特别的大,变量的名字容易发生重复   需要想出不同的变量名或者函数名   如果采用模块分割代码,每个模块文件代码都不是很多,就可以大大的缓解这个问题   每个模块中的变量名作用域只在本模块中 (2)函数的调用 #不同模块之间的调用 #mathFunction.py模块中的内容 print('***begin mathFunction!***') VERSION = 0.1 BUILDOATA = '2018.02.08' def sumFun(a,b):   print('%d + %d = %d' %(a, b, a+b)) def difFun(a,b):   print('%d - %d = %d' %(a, b, a-b)) print('***end mathFunction***') ---------------------------------------------下面的为导入模块的方法一 #statTest.py模块中的内容 print('this is starts!') #strrTest模块中调用mathFunction模块中的函数 import mathFunction #导入了模块 #导入后就可执行里面的函数求和 mathFunction.sumFun(1, 2) #求差 mathFunction.difFun(3, 4) #调用mathFunction.py模块中的属性 print(mathFunction.VERSION) 注意:此方法缺点是调用时需要写模块名 -------------------------------------------下面是调用多个模块方法(用逗号分隔即可) import mathFunction,moudule1,moudule2,moudule3 #导入多个模块 ------------------------------------------给模块取别名,防止同名以及方便记忆(使用as) import mathFunction as fun #起别名(注意:后面调用就要使用别名,否则会报错) ---------------------------------------------下面为导入模块的方法二 #明确的导入模块中指定的函数方法 from mathFunction import sumFun,difFun #不需要写前缀mathFunction模块名 sumFun(34, 5) difFun(33, 6) #同样的针对性导入属性也一样 from mathFunction import VERSION print(VERSION) 注意:此方法的缺点是当被调用的模块中方法名改动了,就会报错,比如说sumFun改为sumF就会报错; 注意:如果在一个模块中从调用了两个模块中的方法,但是方法名是一样的,会导致后面的覆盖前面,所以使用别名可以减少这种情况出现) ----------------------------------------全部导入(不建议使用,潜在的污染名字空间的危险) from module import * (3)自定义包 #简单来讲:组织存放模块文件的目录就称之为包(Package) #包的结构如下 Phone/ #顶层的包   _init_.py #可以初始化文件,也可以是空文件(Python3.3之前必须添加)   commom_util.py   Voicedta/ #子包     _init_.py     Pots.py     Isdn.py   Fax/ #子包     _init_.py     G3.py   Mobile/ #子包     _init_.py     Analog.py     Digital.py -------------------------------------------------------------调用包内模块的方法 目录结果如下: > Phone   ﹀Mobile     _init_.py     mobile.py 注:mobile.py文件中存在若干方法, 比如mobilefun()、dial() ----------------------------------------------------------------- 方法一: import Phone.Mobile.mobile as mFun mFun.mobilefun() 方法二: from Phone.Mobile import mobile mobile.dial() 方法三: from Phone.Mobile.mobile import dial dial()
#This project trains a model with LSTM and 30-day rolling basis data to forecast future 5 days stock prices. #import packages used in this project import math import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM from pandas_datareader import data as pdr from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt plt.style.use ('fivethirtyeight') stockid = input('Please Input a FORMAL Stock ID: ') #obtain a certain stock historical data after financial crisis df = pdr.get_data_yahoo(stockid, start='2009-01-01') #select 'Close' price column in df as data data = df.filter(['Close']) #transfer to array (numbers only) dataset = data.values #set training data, say, the first 80% of the sample (no decimals) train_data_len = len(dataset) #Scale the data to [0,1] with MiniMaxScaler scaler = MinMaxScaler(feature_range=(0,1)) scaled_dataset = scaler.fit_transform(dataset) #create train data train_data = scaled_dataset[0:train_data_len,:] x_train = [] y_train = [] #use 30-day rolling basis to forecast future 5day prices for i in range(30,train_data_len-5): x_train.append(train_data[i-30:i,0]) y_train.append(train_data[i:i+5,0]) #transfer x and y train data to array x_train, y_train = np.array(x_train), np.array(y_train) #reshape x train data x_train=np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1)) #LSTM Model model = Sequential() model.add(LSTM(64,return_sequences=True,input_shape=(x_train.shape[1],x_train.shape[2]))) model.add(LSTM(50,return_sequences=False)) model.add(Dense(25)) model.add(Dense(5)) model.compile(optimizer='adam', loss='mse') #Trian!!! model.fit(x_train, y_train, batch_size=1, epochs=1) #ytest = model.predict(x_train) #create test data predict_data = scaled_dataset[len(dataset)-51:len(dataset)-1, :] #transfer and reshape x test data predict_data = np.array(predict_data) predict_data = np.reshape(predict_data,(1,predict_data.shape[0],1)) #Forecast predictions = model.predict(predict_data) #transfer prediction to normal value predictions = scaler.inverse_transform(predictions) #print forecast result print(stockid + ' Future 5 days Close Prcies '+str(predictions))
class Graph: def __init__(self, n = None, e = None): self._nodedict = {} if not n else n self._nodelist = [] self._edgedict = {} if not n else e self._edgelist = [] @property def node(self): return self._nodedict @property def edge(self): return self._edgedict def nodes(self): return self._nodelist def edges(self): return self._edgelist def add_node(self, node, attr_dict=None): if(attr_dict==None): self._nodedict[node] = {} else: self._nodedict[node] = attr_dict if(node not in self._nodelist): self._nodelist.append(node) def add_edge(self, node1, node2, attr_dict=None): if node1 not in self.node.keys(): self.add_node(node1) if node2 not in self.node.keys(): self.add_node(node2) if attr_dict: self.edge.setdefault(node1,{})[node2] = attr_dict self.edge.setdefault(node2,{})[node1] = attr_dict else: self.edge.setdefault(node1,{})[node2] = {} self.edge.setdefault(node2,{})[node1] = {} if (node1,node2) not in self._edgelist or (node1,node2) not in self._edgelist: self._edgelist.append((node1,node2)) self._edgelist.append((node2,node1)) """if((node1,node2) in self._edgelist or (node2,node1) in self._edgelist): print("L' aresta (node1,node2) ja existeix!") else: if node1 not in self._nodelist: self.add_node(node1) if node2 not in self._nodelist: self.add_node(node2) if(node1 in self._edgedict): if(attr_dict==None): temp = self._edgedict[node1] temp[node2] = {} temp2 = {node1 : {}} self._edgedict[node1] = temp self._edgedict[node2] = temp2 else: temp = self._edgedict[node1] temp[node2] = attr_dict temp2 = {node1 : attr_dict} self._edgedict[node1] = temp self._edgedict[node2] = temp2 else: if(attr_dict==None): temp = {node2 : {}} temp2 = {node1 : {}} self._edgedict[node1] = temp self._edgedict[node2] = temp2 else: temp = {node2 : attr_dict} temp2 = {node1 : attr_dict} self._edgedict[node1] = temp self._edgedict[node2] = temp2 self._edgelist.append((node1,node2))""" def add_nodes_from(self, node_list, attr_dict=None): for i in node_list: self.add_node(i,attr_dict) def add_edges_from(self, edge_list, attr_dict=None): for n in edge_list: self.add_edge(n[0],n[1],attr_dict) def degree(self,n): return len(self.edge[n]) def __getitem__(self, node): res = {} for k in self._nodedict: if(k!=node): res[k] = self.node[k] return res def __len__(self): return len(self.nodes()) def neighbors(self, node): res = [] for n in self._edgedict[node]: res.append(n) return res def remove_node(self, node1): if(node1 in self._nodelist): for v in self._edgedict: if(v in self.neighbors(node1)): self._edgedict.get(v).pop(node1) try: self._edgelist.remove((node1,v)) except: self._edgelist.remove((v,node1)) self._edgedict.pop(node1) self._nodedict.pop(node1) self._nodelist.remove(node1) print("Node",node1,"successfully removed.") else: print("Node",node1,"doesn't exist in this Graph.") def remove_edge(self, node1, node2): if((node1,node2) in self._edgelist): self._edgedict[node1].pop(node2) self._edgedict[node2].pop(node1) self._edgelist.remove((node1,node2)) def remove_nodes_from(self, node_list): for node in node_list: self.remove_node(node) def remove_edges_from(self, edge_list): for pair in edge_list: self.remove_edge(pair[0],pair[1])
def find_short(s): srted = sorted(s.split(' '), cmp=lambda x,y: len(x)-len(y)) return len(srted[0]) import unittest class TestShortestWord(unittest.TestCase): def test_shortest_word(self): self.assertEquals(find_short("bitcoin take over the world maybe who knows perhaps"), 3) self.assertEquals(find_short("turns out random test cases are easier than writing out basic ones"), 3) self.assertEquals(find_short("lets talk about javascript the best language"), 3) self.assertEquals(find_short("i want to travel the world writing code one day"), 1) self.assertEquals(find_short("Lets all go on holiday somewhere very cold"), 2) if __name__ == '__main__': unittest.main()
#cording: utf-8 print('3つの数値を入力してください.') a,b,c=input().split() print(str(a)+','+str(b)+','+str(c)+'が入力されました.') list=[int(a),int(b),int(c)] d=sorted(list) print("元のリスト",list) print("ソート後",d) print('output: '+str(d[0])+" "+str(d[1])+" "+str(d[2]))
for i in range(6): a,op,b=input().split() a=int(a) b=int(b) if(op=='?'): break if(op=='+'): print(a+b) if(op=='-'): print(a-b) if(op=='*'): print(a*b) if(op=='/'): print(a//b)
""" Example of a competing program. Please read the doc and the comments. """ """ playerinterface provides the functions to generate valid return values. You do need this one. Do not delete. """ from playerinterface import spawn_into, move_from_to, fire_at, do_pass from random import randint """ You have to provide a class Player implementing 3 methods as below (start_game, next_move, moves_in_last_round). You can add state and helpers. But you cannot communicate with the external world, nor persist anything between games. Use a web service if you want to. """ class Player: def start_game(self, boardCols, boardRows, numPlayers, playerId): """ boardCols, boardRows - int, columns and rows of the board. numPlayers - int, the number of players in the game. playerId - int, your player. See moves_in_last_round. """ self.boardCols = boardCols self.boardRows = boardRows col = randint(0, self.boardCols-1) row = randint(0, self.boardRows-1) """ If the return is not a spawn, you lose instantly. """ return spawn_into(col, row); def next_move(self): """ Warning: May shoot myself. """ col = randint(0, self.boardCols-1) row = randint(0, self.boardRows-1) """ Alternatives """ """ return pass() """ """ return spawn_into(col, row) """ """ move_from_to(fromCol, fromRow, toCol, toRow) You need to know your current pos!""" return fire_at(col, row) def moves_in_last_round(self, moveList): """ Example of a moveList (only one row shown): [ { actorId : 0, victimId : 1, row : 0, col : 0, boxWidth : 10, boxHeight : 10, isHit : true, isDestroyed : false } ] See the doc for details. Note: the box changes depending on th actual move. For misses, you'll get a box of 1, precise position. Everything indicating the position of an oponent is blurred. Use row, col as base and box as max. """ pass
#!/usr/bin/env python2 # taks8/mapper1.py import sys from collections import defaultdict def map_function(line): """For a given record emits (key, value) pair where key = title id and value = either title rating or title release year Parameters ---------- line : String type A line from the input stream Returns ------- (key, value) : Tuple Title id and year or rating """ splittedLine = line.split("\t") numberOfFields = len(splittedLine) if (numberOfFields == 9): titleId = splittedLine[0] releaseYear = splittedLine[5] if "\N" not in releaseYear: yield titleId, releaseYear else: titleId = splittedLine[0] rating = splittedLine[1] if "\N" not in rating: yield titleId, rating for line in sys.stdin: for key, value in map_function(line): print(key + "\t" + value)
#!/usr/bin/env python2 # task5/mapper.py import sys from collections import defaultdict earliestYear = sys.maxint latestYear = -sys.maxint -1 def map_function(line): """For a given record emit its release year Parameters ---------- line : String type A line from the input stream Returns ------- releaseYear : Integer The releaseYear of the record """ releaseYear = line.split("\t")[5].strip() if "\N" not in releaseYear: # Skip this value yield int(releaseYear) for line in sys.stdin: for year in map_function(line): # Check whether the releaseYear is smaller than the min of greater than the max if year < earliestYear: earliestYear = year if year > latestYear: latestYear = year print(str(earliestYear) + "\t" + str(latestYear))
#Gabriel Daniels #PSID: 1856516 # Prompt the user for the number of cups of lemon juice, water, and agave nectar needed to make lemonade. # Prompt the user to specify the number of servings the recipe yields. Output the ingredients and serving size lemoncups = float(input('Enter amount of lemon juice (in cups):''\n')) watercups = float(input('Enter amount of water (in cups):''\n')) agavecups = float(input('Enter amount of agave nectar (in cups):''\n')) servings = float(input('How many servings does this make?''\n')) print('') print('Lemonade ingredients - yields', '{:.2f}'.format(servings), 'servings') print('{:.2f}'.format(lemoncups), 'cup(s) lemon juice') print('{:.2f}'.format(watercups), 'cup(s) water') print('{:.2f}'.format(agavecups), 'cup(s) agave nectar') print('') #Asking for serving size servings1 = float(input('How many servings would you like to make?''\n')) print('') lemoncups = servings1 / 3 watercups = servings1 * 2.66667 agavecups = servings1 / 2.4 print('Lemonade ingredients - yields', '{:.2f}'.format(servings1), 'servings') print('{:.2f}'.format(lemoncups), 'cup(s) lemon juice') print('{:.2f}'.format(watercups), 'cup(s) water') print('{:.2f}'.format(agavecups), 'cup(s) agave nectar') print('') print('Lemonade ingredients - yields', '{:.2f}'.format(servings1), 'servings') lemoncups = lemoncups / 16 watercups = watercups / 16 agavecups = agavecups / 16 print('{:.2f}'.format(lemoncups), 'gallon(s) lemon juice') print('{:.2f}'.format(watercups), 'gallon(s) water') print('{:.2f}'.format(agavecups), 'gallon(s) agave nectar')
# Gabriel Daniels # PSID 1856516 class ItemToPurchase: # Parameter Constructor def __init__(self, item_name='none', item_price=0, item_quantity=0, item_description='none'): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity self.item_description = item_description # Implement the method def print_item_cost(self): # print the output in a specifed format string = '{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price, (self.item_quantity * self.item_price)) cost = self.item_quantity * self.item_price return string, cost # Implement the method print_item_description def print_item_description(self): string = '{}: {}'.format(self.item_name, self.item_description) print(string, end='\n') return string class ShoppingCart: # Parameter Constructor def __init__(self, customer_name='none', current_date='January 1, 2016', cart_items=[]): self.customer_name = customer_name self.current_date = current_date self.cart_items = cart_items def add_item(self, ItemToPurchase): item_name = str(input('Enter the item name:')) self.cart_items.append((ItemToPurchase(item_name))) def remove_item(self, string): string = str(input('')) i = 0 #iterates through the cart_items list and find string that matches with input for item in self.cart_items: if self.cart_items[i] == string: # deletes matching input string from list self.cart_items.remove(string) i += 1 else: print('Item not found in cart. Nothing removed.') # used to change the quantity of a specified item based on input def modify_item(self, ItemToPurchase): name = str(input('')) for item in self.cart_items: if item.item_name == name: # prompts user for new quantity quantity = int(input('NEW QUANTITY:')) item.item_quantity = quantity else: print('Item not found in cart. Nothing modified.') # used to get total number of items in cart def get_num_items_in_cart(self): num_items = 0 for item in self.cart_items: #gets the quantity of current item in loop and adds it to num_items interger num_items += item.item_quantity return num_items def get_cost_of_cart(self): cost = 0 total_cost = 0 for item in self.cart_items: cost = item.item_quantity * item.item_price total_cost += cost return total_cost def print_total(self): total = 0 for item in self.cart_items: print(item.item_name, item.item_quantity, '@', item.item_price, '=' '$' + str(item.item_quantity * item.item_price)) total += (item.item_quantity * item.item_price) return total def print_description(self): for item in self.cart_items: description = item.item_description print(description) def output_cart(self): new = ShoppingCart() print('\nOUTPUT SHOPPING CART', end='\n') print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n') print('Number of Items:', new.get_num_items_in_cart(), end='\n\n') tc = 0 for item in self.cart_items: print('{} {} @ ${} = ${}'.format(item.item_name, item.item_quantity, item.item_price, (item.item_quantity * item.item_price)), end='\n') tc += (item.item_quantity * item.item_price) print('\nTotal: ${}'.format(tc), end='\n') def print_menu(newCart): customer_Cart = newCart menu = ('\nMENU\n' 'a - Add item to cart\n' 'r - Remove item from the cart\n' 'c - Change item quantity\n' "i - Output item's descriptions\n" 'o - Output shopping cart\n' 'q - Quit\n') command = '' while (command != 'q'): print(menu) command = input('Choose an option:') while ( command != 'a' and command != 'o' and command != 'i' and command != 'q' and command != 'r' and command != 'c'): command = input('Choose an option:\n') if (command == 'a'): print("\nADD ITEM TO CART") item_name = input('Enter the item name:\n') item_description = input('Enter the item description:\n') item_price = int(input('Enter the item price:\n')) item_quantity = int(input('Enter the item quantity:\n')) itemtoPurchase = ItemToPurchase(item_name, item_price, item_quantity, item_description) customer_Cart.add_item(itemtoPurchase) elif (command == 'r'): print('REMOVE ITEM FROM CART') itemName = input('Enter the name of the item to remove :\n') customer_Cart.remove_item(itemName) elif (command == 'c'): print('\nCHANGE ITEM QUANTITY') itemName = input('Enter the name of the item :\n') quan = int(input('Enter the new quantity :\n')) itemToPurchase = ItemToPurchase(itemName, 0, quan) customer_Cart.modify_item(itemToPurchase) elif (command == 'o'): print('\nOUTPUT SHOPPING CART') customer_Cart.print_total() elif (command == 'i'): print('\nOUTPUT ITEMS\' DESCRIPTIONS') customer_Cart.print_description() """def print_menu(ShoppingCart): customer_Cart = newCart # declare the string menu menu = ('\nMENU\n' 'a - Add item to cart\n' 'r - Remove item from cart\n' 'c - Change item quantity\n' 'i - Output items\' descriptions\n' 'o - Output shopping cart\n' 'q - Quit\n') command = '' # Using while loop # to iterate until user enters q while (command != 'q'): string = '' print(menu, end='\n') # Prompt the Command command = input('Choose an option:\n') # repeat the loop until user enters a,i,r,c,q commands while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'): command = input('Choose an option:\n') # If the input command is a if (command == 'a'): # call the method to the add elements to the cart customer_Cart.add_item(string) # If the input command is o if (command == 'o'): # call the method to the display the elements in the cart customer_Cart.output_cart() # If the input command is i if (command == 'i'): # call the method to the display the elements in the cart customer_Cart.print_descriptions() # If the input command is i if (command == 'r'): customer_Cart.remove_item() if (command == 'c'): customer_Cart.modify_item()""" if __name__ == "__main__": customer_name = input("Enter customer's name:\n") current_date = input("Enter today's date:\n") print("\nCustomer name: %s" %customer_name) print("Today's date: %s" %current_date) newCart = ShoppingCart(customer_name, current_date) newCart.print_menu(newCart)
### hazf anasor tekrari list ### def hazfetekrari(classlist): new = [] for ozv in classlist: if ozv not in new: new.append(ozv) return new classlist= ["amin", "reza", "meysam", "mahnaz", "reza", "paniz", "farokh", "mobina",\ "reza", "darya", "paniz", "reza", "paniz"] print(classlist) print(len(classlist)) print(hazfetekrari(classlist)) print(len(hazfetekrari(classlist)))
nombres = input("Introduce 3 nombres: ") nombres_separados = nombres.split(" ") for nombre in nombres_separados: print(nombre)
import random import numpy as np import matplotlib.pyplot as plt import histogram from dispersion import dispersion, centralMoment, neprdispersion, varianceTheoria def even (a,b,sum,wx): h =np.sum(sum) / len(sum) wy = [] for i in range (len(wx)): wy.append((1/(b-a))+h) plt.plot (wx,wy,color = 'r') def reverse(a,b,n): N = int(n) # объем выборки y = [] for i in range(0, N): x2 = a + (b-a) * random.random() y.append(x2) print('выборка:',y) return y def MainReverse(n): print ('введите параметры а и b') a = float(input()) b = float(input()) x = reverse(a, b,n) histogram.histogram(0, x, a, b, 1, 1) print('дисперсия теоритическая :', neprdispersion(a,b)) print('момент теоритический :', (a + b)/2) print('дисперсия и момент программный :') dispersion(x) varianceTheoria(x, (a + b)/2)
class Loop: def __init__(self, x=0): self.x = x def forloop(self): i = 0 for i in range(0,10): print(self.x) self.x += 1 i = i+1 if __name__ == "__main__": f = Loop() f.forloop()
print("Программа которая показывает предыдущие и следуещие число введеного") print("Введите число: ") a = int(input()) b = a+1 c = a-1 print("The next number for the number",a,"is",b ) print("The previous number for the number",a,"is",c)
from datetime import date from enum import Enum from math import atan, degrees class Direction(Enum): NORTH = 1 EAST = 2 WEST = 3 SOUTH = 4 UP = 5 DOWN = 6 class GridSquare: def __init__(self): self.x: str = "" self.y: str = "" self.height: int = 0 self.speed: float = 0.0 self.bearing: float = 0.0 self.time: date self.neighbours = [] def get_direction(self) -> Direction: if(self.bearing < 45): return Direction.NORTH elif(self.bearing < 135): return Direction.EAST elif(self.bearing < 225): return Direction.SOUTH elif(self.bearing < 315): return Direction.WEST else: return Direction.NORTH
class BankAccount: def __init__(self, account_name, interest_rate, balance = 0): self.name = account_name self.int_rate = interest_rate self.bal = balance def deposit(self, amount): self.bal += amount return self def withdraw(self, amount): self.bal -= amount return self def display_account_info(self): print("Account Name:", self.name) print("Balance:", self.bal) print("Interest Rate:", self.int_rate) return self def yield_interest(self): self.bal = self.bal + self.bal * self.int_rate return self if __name__ == "__main__": account1 = BankAccount("Account 1", .05, 100) account2 = BankAccount("Account 2", .10, 50) account1.deposit(100).deposit(100).deposit(100).withdraw(200).yield_interest().display_account_info() account2.deposit(200).deposit(200).withdraw(50).withdraw(50).withdraw(50).withdraw(50).yield_interest().display_account_info()
import random def randInt(min= 0 , max= 100 ): if min < max: num = round(random.random() * (max-min) + min) return num else: print("specify a minimum value that is less than the maximum value that you specified (or the default of 100) \n \ or a maximum value that is greater than the minimum you specified (or the default of 0)") return False #print(randInt()) # should print a random integer between 0 to 100 #print(randInt(max=50)) # should print a random integer between 0 to 50 #print(randInt(min=50)) # should print a random integer between 50 to 100 print(randInt(min=50, max=500)) # should print a random integer between 50 and 500
# https://projecteuler.net/problem=1 # Multiples of 3 and 5 def sumOf3or5Multiples(max): sum = 0 for number in range(3, max): if number % 3 == 0 or number % 5 == 0: sum += number return sum # print sumOf3or5Multiples(10) # print sumOf3or5Multiples(100) print sumOf3or5Multiples(1000) # print sumOf3or5Multiples(10000) # print sumOf3or5Multiples(100000) # print sumOf3or5Multiples(1000000) # print sumOf3or5Multiples(10000000) # print sumOf3or5Multiples(100000000)
# https://projecteuler.net/problem=9 # Special Pythagorean triplet # parameter represents the sum of the triplets # using the formula for generating pythagorean triplets: a = m^2 - n^2, b = 2mn, c = m^2 + n^2 def find_pythagorean_triplets(sum): for n in range(sum + 1): for m in range(n, sum + 1): # if inverse loops order (m first), we can also obtain the desired sum, but product will be negative a = m ** 2 - n ** 2 b = 2 * m * n c = m ** 2 + n ** 2 current_sum = a + b + c # 2m(m+n) if current_sum == sum: return a, b, c, a * b * c elif current_sum > sum: break raise Exception("Provided argument is not the sum of any pythagorean triplet") print find_pythagorean_triplets(1000)
print("""********************************************************** * Blackjack35 Sıcaklık Çevirici * * İşlemler; * * 1-Celcius to Fahrenheit * * 2-Celcius to Kelvin * * 3-Fahrenheit to Celcius * * 4-Fahrenheit to Kelvin * * 5-kelvin to Celcius * * 6-Kelvin To Fahrenheit * * * * Programdan Çıkmak İçin "q" Ye Basınız. * **********************************************************""") while True: işlem = input("Yapmak İstediğiniz İşlemi Seçiniz: ") if (işlem == "q"): print("Her Zaman Buradayız.") break elif (işlem == "1"): celcius = float(input("Çevirmek İstediğiniz Celcius'u Giriniz: ")) fahrenheit = celcius * 1.8 + 32 print("{} Celcius {} Fahrenheit Yapar!".format(celcius,fahrenheit)) elif (işlem == "2"): celcius = float(input("Çevirmek İstediğiniz Celcius'u Giriniz: ")) kelvin = (celcius + 273.15) print("{} Celcius, {} Kelvin Yapar!".format(celcius, kelvin)) elif (işlem =="3"): fahrenheit = float(input("Çevirmek İstediğiniz Fahrenheit'i Giriniz: ")) celcius = (fahrenheit - 32) / 1.8 print("{} Fahrenheit {} Celcius Yapar! ".format(fahrenheit,celcius)) elif (işlem == "4"): fahrenheit = float(input("Çevirmek İstediğiniz Fahrenheit' i Giriniz: ")) kelvin =(fahrenheit + 459.67)* 5/9 print("{} Fahrenheit {} Kelvin yapar!".format(fahrenheit,kelvin)) elif (işlem == "5"): kelvin = float(input("Çevirmek İstediğiniz Kelvin'i Giriniz: ")) celcius = (kelvin - 273.15) print("{} Kelvin, {} Celcius yapar! ".format(kelvin,celcius)) elif (işlem == "6"): kelvin = float(input("Çevirmek İstediğiniz Kelvin'i Giriniz: ")) fahrenheit = (kelvin * 9/5) -459.67 print("{} Kelvin, {} Fahreheit Yapar ! ".format(kelvin,fahrenheit)) else : print("Yanlış Bir İşlem Seçtiniz, Tekrar Deneyiniz ! ")
# 98 Validate Binary Search Tree # I-DFS class Solution(object): def ValidateBST(self, root): """ : type root : TreeNode : rtype : bool """ pre = [None] return self.dfs(root, pre) def dfs(self, root, pre): if not root: return True if not self.dfs(root.left, pre) or pre[0] and root.val <= pre[0].val: return False pre[0]= rootreturn self.dfs(root.right, pre) # recursive class Solution1(object): def ValidateBST1(self, root): """ : type root : TreeNode : rtype : bool """ INF = float('inf') return self.judge(root, -INF, INF) def judge(self, root, minV, maxV): if not root: return True if root.val <= minV or root.val => maxV: return False return self.judge(root.left, minV, root.val) and self.judge(root.right, root.val, maxV) # III -BFS class Solution3(object): def ValidateBST3(self, root): """ : type root : TreeNode : rtype : bool """ res = [] self.inorder(root, res) return res == sorted(res) and len(res) == len(set(res)) def inorder(self, root, res): if not root: return [] l = self.inorder(root.left, res) if l: res.extend(l) res.append(root.val) r = self.inorder(root.right, res) if r : res.extend()
import os from nick import create_nick def user_exist(nickname): # should raise error if user exist # testa try: with open('usernicks.csv') as usernicksfile: for row in usernicksfile.readlines(): # split line on "," user = row.strip().split(',') if user[2] == nickname: return True except IOError as err: # if no usernicksfile, generates error return False return False def adduser(firstname,lastname,nickname): # TODO change to adduser in some computer #check if user is in usernicksfile if user_exist(nickname): message = 'user exist ' + nickname + ' on adding ' + firstname + ' ' + lastname raise StandardError(message) else: # write user and nickname to file, a is append with open('usernicks.csv', 'a') as usernicksfile: # create the line, '\n' is newline line = firstname + ',' + lastname + ',' + nickname + '\n' usernicksfile.write(line) # remove usernicks.csv if it exist try: os.remove('usernicks.csv') except: pass # do nothing # adding user from file # open user csv file with open('users.csv') as userfile: # read the lines for row in userfile.readlines(): # split line on "," user = row.strip().split(',') # assign values firstname = user[0] lastname = user[1] # call create_nick to build a username nickname = create_nick(firstname, lastname) try: adduser(firstname,lastname,nickname) except Exception as err: # try to add a number on nickname print err
'''Following Links in Python In this assignment you will write a Python program that expands on http://www.py4e.com/code3/urllinks.py. The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particular position relative to the first name in the list, follow that link and repeat the process a number of times and report the last name you find. We provide two files for this assignment. One is a sample file where we give you the name for your testing and the other is the actual data you need to process for the assignment Sample problem: Start at http://py4e-data.dr-chuck.net/known_by_Fikret.html Find the link at position 3 (the first name is 1). Follow that link. Repeat this process 4 times. The answer is the last name that you retrieve. Sequence of names: Fikret Montgomery Mhairade Butchi Anayah Last name in sequence: Anayah Actual problem: Start at: http://py4e-data.dr-chuck.net/known_by_Jesse.html Find the link at position 18 (the first name is 1). Follow that link. Repeat this process 7 times. The answer is the last name that you retrieve. Hint: The first character of the name of the last page that you will load is: S Strategy The web pages tweak the height between the links and hide the page after a few seconds to make it difficult for you to do the assignment without writing a Python program. But frankly with a little effort and patience you can overcome these attempts to make it a little harder to complete the assignment without writing a Python program. But that is not the point. The point is to write a clever Python program to solve the program. ''' from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') if len(url) < 1 : url = 'http://py4e-data.dr-chuck.net/comments_391150.html' html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, "html.parser") # Retrieve all of the anchor tags tags = soup('span') count = 0 summ = 0 for tag in tags: x = int(tag.text) count += 1 summ += x print(summ)
lista_elementos_1 = ["Douglas", "Anderson", "Libório", "Maicon", "Prefeito Géri"] lista_elementos_2 = ["Douglas", "Maicon", "Libório"] lista_diferenca = [item for item in lista_elementos_1 if item not in lista_elementos_2] print(lista_diferenca)
from flask import Flask, render_template, request, redirect from flask_sqlalchemy import SQLAlchemy from datetime import datetime """ __name__ is set to the name of the current class, function, method, descriptor, or generator instance. Python assigns the name "__main__" to the script when the script is executed. If the script is imported from another script, the script keeps it given name (e.g. hello.py). In our case we are executing the script. Therefore, __name__ will be equal to "__main__". That means the if conditional statement is satisfied and the app. """ # indicate flask app = Flask(__name__) # add the database, define the url, # will use sqlite, /// means relative path, //// means absolute app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' # initialize database db = SQLAlchemy(app) # create a model class Todo(db.Model): id = db.Column(db.Integer, primary_key = True) content = db.Column(db.String(200),nullable = False) date_created = db.Column(db.DateTime, default=datetime.utcnow) def __repr__(self): return '<Task %r>' % self.id # define the routes using app.route # we add methods, it enables this route to get as well as post @app.route('/', methods = ['POST','GET']) # define a function for index page def index(): if request.method == 'POST': # we want to display the actual content from the form # we use the id i.e. content and access the user input task_content = request.form['content'] # create an object of database and assign the content new_task = Todo(content=task_content) try: # add the content to database (each entry is an object) db.session.add(new_task) # commit the chnages db.session.commit() # reload the page return redirect('/') except: return 'There was an issue adding your task' else: # order all the tasks by date tasks = Todo.query.order_by(Todo.date_created).all() # return all the task to index.html and show them in the table return render_template('index.html', tasks=tasks) # we do not need to specify the path, # it knows where to look for it (i.e. in templates folder) # return render_template('index.html') @app.route('/delete/<int:id>') def delete(id): task_to_delete=Todo.query.get_or_404(id) try: db.session.delete(task_to_delete) db.session.commit() return redirect('/') except: return 'error in delete' @app.route('/update/<int:id>', methods=['GET','POST']) def update(id): task=Todo.query.get_or_404(id) if request.method=='POST': task.content = request.form['content'] try: db.session.commit() return redirect('/') except: return 'error in update' else: return render_template('update.html', task=task) # main function if __name__ == '__main__': app.run(debug=True)
import math def quickSort(array, p, r): if p<r: q=partition(array,p,r) quickSort(array,p,q-1) quickSort(array,q+1,r) def partition(array,p,r): x=array[r] i=p-1 for j in range(p,r): if array[j]>=x: i=i+1 temp=array[i] array[i]=array[j] array[j]=temp temp2=array[i+1] array[i+1]=array[r] array[r]=temp2 return i+1 def bucketSort(A): C=[] n=len(A) B=[[] for _ in range(n)] for i in range(0,n): B[(math.floor((A[i])*n))].append(A[i]) for i in range(0, n): quickSort(B[i],0,(len(B[i]))-1) for i in range(0, n): C+=B[i] return C
from linked_list import MyList, ListNode class MyQueue: def __init__(self): self.items = MyList() def length(self): return self.items.__len__() def isEmpty(self): if self.length() == 0: return True return False def enqueue(self, item): i = ListNode(item) self.items.add(i) def dequeue(self): if not self.isEmpty(): data = self.items.get_item() return data def __iter__( self ): return self.items.__iter__()
import pygame class DrawableButton(): color = None hovering = False pressed = False def __init__(self, color, game, rect=None): self.color = color self.rect = rect self.game = game def draw(self, screen): if (self.hovering and not self.pressed): color = [i * 0.75 for i in self.color.value] elif (self.pressed): color = [i * 0.5 for i in self.color.value] else: color = self.color.value pygame.draw.rect(screen, color, self.rect) # self.reset() def reset(self): self.hovering = False self.pressed = False def isPressed(self, state): self.pressed = state def isHovering(self, state): self.hovering = state def action(self, event): if event.type == pygame.MOUSEMOTION: mousePos = event.pos if (self.rect.collidepoint(mousePos) and not self.game.getPressedButton()): self.hovering = True else: self.hovering = False if event.type == pygame.MOUSEBUTTONDOWN: mousePos = event.pos if self.rect.collidepoint(mousePos): self.pressed = True self.game.setPressedButton(self) else: self.pressed = False if event.type == pygame.MOUSEBUTTONUP: self.pressed = False self.game.setPressedButton(None) # If mouse has left screen if not bool(pygame.mouse.get_focused()): self.hovering = False self.pressed = False
# forme générale if (une condition ici): # ... # des instructions ici # ... else: # ... # des instructions ici # ... # affichage si un test est vrai temperature = 28 if temperature>25: print('il fait chaud !') # affichages distincts selon un test temperature = 28 if temperature>25: print('il fait chaud !') else: print('il fait frais...') # enchaînement de tests temperature = 28 if temperature>25: print('il fait chaud !') elif temperature>20: print('il fait bon.') else: print('il fait frais...')
fname = input('File name: ') try: fhand = open(fname) except: print('There is an exception.') exit() count = 0 for line in fhand: if not line.startswith('From'): continue count = count + 1 words = line.split() print(words[1]) print('There is ', count, ' From lines.')
import re hand = open('mbox1.txt') for line in hand: line = line.rstrip() #start with a single lowercase letter, uppercase letter, or number [a-zA-Z0-9] #follow by zero or non blank characters \S* #follow by an uppercase or lowercase letter x = re.findall('[a-zA-Z0-9]\S+@\S+[a-zA-Z]', line) if len(x) > 0: print(x)
fname = input('Enter a file name: ') try: fhand = open(fname) except: print('Fail to open ', fname) exit() eaddr = dict() for line in fhand: if not line.startswith('From'): continue words = line.split() if words[1] not in eaddr: eaddr[words[1]] = 1 else: eaddr[words[1]] += 1 bigword = None bigcount = None for word, count in eaddr.items(): if bigcount is None or bigcount < count: bigcount = count bigword = word print(eaddr) print('Maximum messages from:', bigword, 'who has sent', bigcount, 'times.')
# program to find Fibonacci number series number = raw_input("Enter quantity of number:") p = 0 q = 1 # print p # print q for s in range(int(number)): r = p + q print r p = q q = r
'#class calculator' def add(a, b): "this function adds two numbers" return a + b def subtract(a, b): "this function subtracts two numbers" return a - b def multiply(a, b): "this function multiplies two numbers" return a * b def divide(a, b): "this function divides two numbers" return a / b print ("select operation") print ("add") print ("subtract") print ("multiply") print ("divide") operation = raw_input("Enter input (" add "/" subtract "/" multiply "/" divide ")": ) a = raw_input(int("Enter value of 'a' : ")) b = raw_input(int("Enter value of 'b' : ")) if operation == '1': print "%s + %s = %s"(a, b, add(a, b)) elif operation == '2': print "%s - %s = %s"(a, b, subtract(a, b)) elif operation == '3': print "%s * %s = %s"(a, b, multiply(a, b)) elif operation == '4': print "%s / %s = %s"(a, b, divide(a, b)) else: print("Invalid operation")
#%% # the process of classifying words into their parts of speech - part-of-speech tagging, POS-tagging # using a tagger import nltk from nltk import word_tokenize # POS tagger attaches a part of speech tag to each word text = word_tokenize('And now for something completely different') nltk.pos_tag(text) # CC - coordinating conjunction, RB - adverbs, IN - preposition, NN - noun, JJ - adj, VBP - verb # words appearing in the same context text = nltk.Text(word.lower() for word in nltk.corpus.brown.words()) text.similar('woman')
from sklearn import datasets import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split digits = datasets.load_digits() print(digits.keys()) print(digits.DESCR) print(digits.images.shape) print(digits.data.shape) plt.imshow(digits.images[1010], cmap=plt.cm.gray_r, interpolation='nearest') plt.show() X = digits.data y = digits.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=42,stratify=y) knn = KNeighborsClassifier(n_neighbors=7) knn.fit(X_train,y_train) print(knn.score(X_test, y_test))
import numpy as np from scipy.linalg import toeplitz def simu_data(n, p, rho=0.25, snr=2.0, sparsity=0.06, effect=1.0, seed=None): """Function to simulate data follow an autoregressive structure with Toeplitz covariance matrix Parameters ---------- n : int number of observations p : int number of variables sparsity : float, optional ratio of number of variables with non-zero coefficients over total coefficients rho : float, optional correlation parameter effect : float, optional signal magnitude, value of non-null coefficients seed : None or Int, optional random seed for generator Returns ------- X : ndarray, shape (n, p) Design matrix resulted from simulation y : ndarray, shape (n, ) Response vector resulted from simulation beta_true : ndarray, shape (n, ) Vector of true coefficient value non_zero : ndarray, shape (n, ) Vector of non zero coefficients index """ # Setup seed generator rng = np.random.default_rng(seed) # Number of non-null k = int(sparsity * p) # Generate the variables from a multivariate normal distribution mu = np.zeros(p) Sigma = toeplitz(rho ** np.arange(0, p)) # covariance matrix of X # X = np.dot(np.random.normal(size=(n, p)), cholesky(Sigma)) X = rng.multivariate_normal(mu, Sigma, size=(n)) # Generate the response from a linear model non_zero = rng.choice(p, k) beta_true = np.zeros(p) beta_true[non_zero] = effect eps = rng.standard_normal(size=n) prod_temp = np.dot(X, beta_true) noise_mag = np.linalg.norm(prod_temp) / (snr * np.linalg.norm(eps)) y = prod_temp + noise_mag * eps return X, y, beta_true, non_zero
def encryption(word,mpass): key = mpass[0] + mpass[-1] + mpass[3] + mpass[2] word_array = [] key_array = [] for c in word: word_array.append(ord(c)) for c in key: key_array.append(ord(c)) j = 0 for i in range(len(word_array)): if i%2 == 1: word_array[i] += key_array[j] if word_array[i] > 126: while word_array[i]<40 or word_array[i]>126: word_array[i] = word_array[i]%126 + 39 #word_array[i] = chr(word_array[i]) if i%2 == 0: word_array[i] -= key_array[j] if word_array[i] < 40: word_array[i] += (127 - 40) #word_array[i] = chr(word_array[i]) word_array[i] = chr(word_array[i]) j += 1 if j == len(key_array): j = 0 encryp = '' for c in word_array: encryp += str(c) return encryp
class swingline(object): # Class definition def __init__(self, finalAngle,pix,pct=0.8,startAngle=-90,strokeColor=200): # Object constructor self.finalAngle = finalAngle self.pix = pix self.currentAngle = float(startAngle) self.easing = 0.02 self.pctDraw = pct self.strokeColor = strokeColor self.finalAngle = self.finalAngle + self.currentAngle def step(self): dtheta = float(self.finalAngle) - self.currentAngle self.currentAngle += dtheta * self.easing def display(self): # Display method pushMatrix() translate(width/2,height/2) rotate(radians(self.currentAngle)) stroke(self.strokeColor) line(self.pctDraw*self.pix, 0, self.pix, 0) popMatrix()
#Bill late payment #For 5 months (12% extra bill on current bill) starting bill is 6565 current_bill = 6565 extra_charges = 0 for i in range(1,6): extra_charges = (12/100) * current_bill current_bill += extra_charges print("Your current bill is {} with extra charges {} for late bill payment".format(round(current_bill,2),round(extra_charges,2)))
#2 string metodu, 2 liste metodu ve 1 döngü #işlemin sonucu return #çok mantıklı bir fonksiyon olmasada ödev kurallarına uygun return eden bir fonksiyon def fonksiyon(): liste = ["ibrahim","ali","veli","ayşe","mehmet"] notlar = [100,75,50,60,0] liste_copy = liste.copy() #list method for i in range(0,len(liste)): a = liste_copy[i] a.capitalize() #string method liste_copy.append(notlar[i]) #list method liste_copy[3].replace("şe","ça") #string method toplam = 0 for i in notlar: toplam = toplam + i return toplam ortalama = fonksiyon() / 5 print(ortalama)
# Dependencies import csv import os # dir() : will return all the functions available in the csv module. #print(dir(csv)) # 1. Open the data file. ## Assign a variable for the file to load and the path. file_to_load_path = os.path.join("Resources", "election_results.csv") # print(f""" # file_to_load_path: # {file_to_load_path} # """) # 1. Initialize a total vote counter. total_votes = 0 # Candidate options array candidate_options = [] # 1. Declare the empty dictionary. candidate_votes = {} # Open the election results and read the file. with open(file_to_load_path, newline="") as election_data_pointer: # Print the file object. # print(f""" # election_data_pointer: # {election_data_pointer} # """) # To do: read and analyze the data here. # Read the file object with the reader function. file_reader = csv.reader(election_data_pointer) # Print the header row. headers = next(file_reader) # print(headers) # Print each row in the CSV file. for row in file_reader: # print(row) # 2. Add to the total vote count. total_votes += 1 # Print the candidate name from each row candidate_name = row[2] # If the candidate does not match any existing candidate... if candidate_name not in candidate_options: # Add it to the list of candidates. candidate_options.append(candidate_name) # 2. Begin tracking that candidate's vote count. candidate_votes[candidate_name] = 0 # Add a vote to that candidate's count. candidate_votes[candidate_name] += 1 # 3. Print the total votes. print(total_votes) # Print the candidate list. print(candidate_options) # Print the candidate vote dictionary. print(candidate_votes) # RESULT # 1. Total number of votes cast # 2. A complete list of candidates who received votes # 3. Total number of votes each candidate received # 4. Percentage of votes each candidate won # Winning Candidate and Winning Count Tracker winning_candidate = "" winning_count = 0 winning_percentage = 0 candidate_results = "" # Determine the percentage of votes for each candidate by looping through the counts. # 1. Iterate through the candidate list. for candidate_name in candidate_votes: # 2. Retrieve vote count of a candidate. votes = candidate_votes[candidate_name] # 3. Calculate the percentage of votes. vote_percentage = float(votes) / float(total_votes) * 100 # 4. Print the candidate name and percentage of votes. # print(f"{candidate_name}: received {round(vote_percentage,2)}% of the vote.") # print(f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n") candidate_results = (f"{candidate_results}" f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n") # Determine if the votes are greater than the winning count. if (votes > winning_count) and (vote_percentage > winning_percentage): # 2. If true then set winning_count = votes and winning_percent = # vote_percentage. winning_count = votes winning_percentage = vote_percentage # 3. Set the winning_candidate equal to the candidate's name. winning_candidate = candidate_name # 5. The winner of the election based on popular vote winning_candidate_summary = ( f"-------------------------\n" f"Winner: {winning_candidate}\n" f"Winning Vote Count: {winning_count:,}\n" f"Winning Percentage: {winning_percentage:.1f}%\n" f"-------------------------\n") # print(winning_candidate_summary) # Create a filename variable to a direct or indirect path to the file. file_to_save_path = os.path.join("analysis", "election_analysis.txt") # print(f""" # file_to_save_path: # {file_to_save_path} # """) # Using the with statement open the file as a text file. with open(file_to_save_path, "w", newline="" ) as txt_file_pointer: # Print the final vote count to the terminal. election_results = ( f"\nElection Results\n" f"-------------------------\n" f"Total Votes: {total_votes:,}\n" f"-------------------------\n") print(election_results, end="") # Save the final vote count to the text file. txt_file_pointer.write(election_results) # Print each candidate, their voter count, and percentage to the terminal. print(candidate_results) # Save the candidate results to our text file. txt_file_pointer.write(candidate_results) # Save the winning candidate's name to the text file. txt_file_pointer.write(winning_candidate_summary) # The election commission has requested some additional data to complete the audit: ## The voter turnout for each county ### print ### save ## The percentage of votes from each county out of the total count ### print ### save ## The county with the highest turnout ### print ### save
#! /usr/bin/env python # from fenics import * def poisson(): #*****************************************************************************80 # ## poisson solves the Poisson problem on the unit square. # # Discussion: # # Del^2 U = - 6 in Omega # U(dOmega) = Uexact(x,y) on dOmega # # Uexact = 1 + x^2 + 2 y^2 # Omega = unit square [0,1]x[0,1] # # Modified: # # 21 October 2018 # # Author: # # John Burkardt # # Reference: # # Hans Petter Langtangen, Anders Logg, # Solving PDEs in Python - The FEniCS Tutorial Volume ! # import matplotlib.pyplot as plt # # Create an 8x8 triangular mesh on the unit square. # mesh = UnitSquareMesh(8, 8) # # Define the function space. # V = FunctionSpace(mesh, 'P', 1) # # Define the exact solution. # Setting "degree = 2" should be OK. # FENICS prefers degree = 4 for accuracy... # u_D = Expression('1 + x[0]*x[0] + 6*x[1]*x[1]', degree=4) # # Define the boundary condition. # def boundary(x, on_boundary): return on_boundary bc = DirichletBC(V, u_D, boundary) # # Define the variational problem. # u = TrialFunction(V) v = TestFunction(V) f = Constant(-14.0) a = dot(grad(u), grad(v)) * dx L = f * v * dx # # Compute the solution. # u = Function(V) solve(a == L, u, bc) # # Plot the mesh. # plot(mesh, title='Mesh for Poisson equation') filename = 'poisson_mesh.png' plt.savefig(filename) print(' Graphics saved as "%s"' % (filename)) plt.close() # # Plot the solution. # plot(u, mode='contour', title='Solution for Poisson equation') filename = 'poisson_solution.png' plt.savefig(filename) print(' Graphics saved as "%s"' % (filename)) plt.close() # # Compute the error in the L2 norm. # error_L2 = errornorm(u_D, u, 'L2') print('error_L2 =', error_L2) # # Compute maximum error at vertices. # vertex_values_u_D = u_D.compute_vertex_values(mesh) vertex_values_u = u.compute_vertex_values(mesh) import numpy as np error_max = np.max(np.abs(vertex_values_u_D - vertex_values_u)) print('error_max =', error_max) return def poisson_test(): #*****************************************************************************80 # ## poisson_test tests poisson. # # Modified: # # 21 October 2018 # # Author: # # John Burkardt # import time print(time.ctime(time.time())) print('') print('poisson_test:') print(' FENICS/Python version') print(' Poisson equation on the unit square.') poisson() # # Terminate. # print('') print('ell_test:') print(' Normal end of execution.') print('') print(time.ctime(time.time())) return if (__name__ == '__main__'): poisson_test()
#! /usr/bin/env python # from fenics import * def poisson_nonlinear(): #*****************************************************************************80 # ## poisson_nonlinear solves the nonlinear Poisson problem on the unit square. # # Discussion: # # - div( ( 1 + u^2 ) grad(u) ) = x * sin(y) in Omega # U = 1 if x = 1 on dOmega # U = 0 otherwise on dOmega # # Omega = unit square [0,1]x[0,1] # # Modified: # # 20 October 2018 # # Author: # # John Burkardt # import matplotlib.pyplot as plt # # Set up the mesh. # mesh = UnitSquareMesh(32, 32) # # Function space. # V = FunctionSpace(mesh, "CG", 1) # # Dirichlet boundary conditions. # def right_boundary(x, on_boundary): return abs(x[0] - 1.0) < DOLFIN_EPS and on_boundary g = Constant(1.0) bc = DirichletBC(V, g, right_boundary) # # Set up the variational form. # u = Function(V) v = TestFunction(V) f = Expression("x[0]*sin(x[1])", degree=10) F = inner((1 + u**2) * grad(u), grad(v)) * dx - f * v * dx # # Compute the solution. # Because this is a nonlinear equation, we don't use the "auv = fv" form # for the solver, we ask it to solve "F==0" instead. # solve ( F == 0.0, u, bc, \ solver_parameters = { "newton_solver":{"relative_tolerance":1e-6} } ) # # Plot the solution. # plot(u, title="Nonlinear Poisson Solution") filename = 'poisson_nonlinear_solution.png' plt.savefig(filename) print('Grpahics saved as "%s"' % (filename)) plt.close() # # Plot the gradient. # plot(grad(u), title="Nonlinear Poisson Gradient") filename = 'poisson_nonlinear_gradient.png' plt.savefig(filename) print('Graphics saved as "%s"' % (filename)) plt.close() # # Terminate. # return def poisson_nonlinear_test(): #*****************************************************************************80 # ## poisson_nonlinear_test tests poisson_nonlinear. # # Modified: # # 23 October 2018 # # Author: # # John Burkardt # import time print(time.ctime(time.time())) # # Report level = only warnings or higher. # level = 30 set_log_level(level) print('') print('poisson_nonlinear_test:') print(' FENICS/Python version') print(' Solve a nonlinear Poisson problem.') poisson_nonlinear() # # Terminate. # print('') print('poisson_nonlinear_test:') print(' Normal end of execution.') print('') print(time.ctime(time.time())) return if (__name__ == '__main__'): poisson_nonlinear_test()
# https://www.codewars.com/kata/help-mrs-jefferson/train/python def shortest_arrang(n): student_range = reversed(range(n)) return student_range print shortest_arrang(10)#,[4, 3, 2, 1]) print shortest_arrang(14)#,[5, 4, 3, 2]) print shortest_arrang(16)#,[-1]) print shortest_arrang(22)#,[7, 6, 5, 4]) print shortest_arrang(65)#,[33, 32])
# https://www.codewars.com/kata/find-the-middle-element/train/python def gimme(input_array): return input_array.index(sorted(input_array)[1]) print gimme([2, 3, 1])
# https://www.codewars.com/kata/square-n-sum/train/python def square_sum(numbers): sum = 0 for i in numbers: sum += i*i return sum print square_sum([1,2]) print square_sum([0, 3, 4, 5])
# https://www.codewars.com/kata/opposite-number/train/python def opposite(number): if number < 0: return abs(number) else: return number - number - number print opposite(1) #,-1)
import sys import os def sort_quick(nums): if len(nums) == 1: return nums if nums == sorted(nums): return nums pivot = nums[len(nums)-1] leftpart,rightpart = partition(nums,pivot) return sort_quick(leftpart) + [pivot] + sort_quick(rightpart) def partition(arr,pivot): left_part = [] right_part = [] for i in arr[:-1]: if i <= pivot: left_part.append(i) else: right_part.append(i) return (left_part,right_part) if __name__ == '__main__': print(sort_quick([23,100,3,3,67,1,0,34,99,3]))
#!/usr/bin/env python """ Coder: max.zhang Date: 2015-01-29 Desc: classes of hierarchical nodes """ class BaseNode(object): """ Desc: Base class of Node Data: _id|int: id _name|str: name """ def __init__(self, node_idx, node_str): self._id = node_idx self._name = node_str def __repr__(self): return 'id:%s,name:%s' % (self._id, self._name) def __str__(self): return 'id:%s,name:%s' % (self._id, self._name) class ConNode(BaseNode): """ Desc: Node with connects and neighbours Data: _nb|dict: neighbour dict _du|float: sum of weight of all connected edges """ def __init__(self, node_idx, node_str): BaseNode.__init__(self, node_idx, node_str) self._nb = {} self._du = 0. def addNB(self, node_idx, weight): ori_weight = self._nb.get(node_idx, 0.) self._du += weight-ori_weight if self._du < 0: print 'addNB', self print node_idx, weight, ori_weight exit(1) self._nb[node_idx] = weight def delNB(self, node_idx): weight = self._nb[node_idx] self._du -= weight del self._nb[node_idx] return weight def __repr__(self): return '%s,nb:%s,du:%.3f' % ( BaseNode.__repr__(self), ','.join(['%s/%.3f' % (key, value) for key, value in self._nb.items()]), self._du) def __str__(self): return '%s,nb:%s,du:%.3f' % ( BaseNode.__str__(self), ','.join(['%s/%.3f' % (key, value) for key, value in self._nb.items()]), self._du) class DisjointNode(ConNode): """ Desc: Node of Disjoint Network Data: _com|int: community id """ def __init__(self, node_idx, node_str): ConNode.__init__(self, node_idx, node_str) self._com = -1 def setCom(self, com_idx): self._com = com_idx def clrCom(self): self._com = 0 def __repr__(self): return '%s,com_idx:%s' % ( ConNode.__repr__(self), self._com) def __str__(self): return '%s,com_idx:%s' % ( ConNode.__str__(self), self._com) class OverlapNode(ConNode): """ Desc: Node of Overlap Network Data: _com|set: community id set """ def __init__(self, node_idx, node_str): ConNode.__init__(self, node_idx, node_str) self._com = set() def addCom(self, com_idx): self._com.add(com_idx) def delCom(self, com_idx): self._com.remove(com_idx) def hasCom(self, com_idx): return com_idx in self._com def __repr__(self): return '%s,com_list:%s' % ( ConNode.__repr__(self), ','.join([str(com_idx) for com_idx in self._com])) def __str__(self): return '%s,com_list:%s' % ( ConNode.__str__(self), ','.join([str(com_idx) for com_idx in self._com])) class DisjointWeightedNode(DisjointNode): """ Desc: Weighted Node of Disjoint Network Data: _w|float: node weight """ def __init__(self, node_idx, node_str, w=1.): DisjointNode.__init__(self, node_idx, node_str) self._w = w def setW(self, w): if abs(self._w-w) < 1e-6: return self._du *= w/self._w for node_idx, weight in self._nb.items(): self._nb[node_idx] = weight*w/self._w self._w = w def __repr__(self): return '%s,w:%.3f' % ( DisjointNode.__repr__(self), self._w) def __str__(self): return '%s,w:%.3f' % ( DisjointNode.__str__(self), self._w)
#นายพงศภัค ฟุ้งทวีวงศ์ 6310301020 #นายชวัลวิทย์ วงศ์สงวน 6310301024 #นายพัชรพงษ์ สุทธิยุทธ์ 6310301026 #Github : https://github.com/pongsapak-ton/movieticketsystem import tkinter as tk from tkinter import * import tkinter.font from tkinter.ttk import * from select import * from login import * from movie_renew import * import contextvars Font_tuple = ("Comic Sans MS", 20, "bold") def exit_program(): exit() def Close(screen): screen.destroy() def movie(screen): global Font_tuple screen1 = Toplevel(screen) screen1.title('select movie') screen1.geometry('410x480+540+200') screen1.resizable(0,0) label_frame = Frame(screen1) label_frame.pack(side=TOP) radio_frame = Frame(screen1) radio_frame.pack(side = TOP,pady = 20) label = tk.Label(label_frame, text='movieTicketBookingSystem', bg='blue', fg='white', width=25, height=2) label.pack(side=TOP) label.config(font=Font_tuple) v = StringVar(radio_frame, "1") # Dictionary to create multiple buttons values = {"JUMANJI": "JUMANJI", "Ready Player One": "Ready Player One", "FREE GUY": "FREE GUY"} # Loop is used to create multiple Radiobuttons # rather than creating each button separately for (text, value) in values.items(): Radiobutton(radio_frame, text=text, variable=v, value=value,font=Font_tuple, indicator = 0, background = "light blue").pack(side=TOP, ipady=5,fill='x',pady =10 ) CnfrmBtn = Button(radio_frame, text="CONFIRM",font= Font_tuple,command = lambda :Movie_page(screen, str(v.get()))) CnfrmBtn.pack(side=BOTTOM,ipady=5,pady = 10) screen1.mainloop() def main_p(): global screen global Font_tuple screen = tk.Tk() screen.title('movie ticket') screen.geometry('400x350+90+200') screen.resizable(0,0) label = tk.Label(screen, text = 'movieTicketBookingSystem',bg = 'blue', fg = 'white',width = 25, height = 2) label.place(x = 0 , y= 0) label.config(font = Font_tuple) button_1 = tk.Button(screen, text='purchase ticket',command = lambda:movie(screen),bg= 'red',width = 15 ,height = 1,disabledforeground="#bfbfbf") button_1.place(x=70, y =130) button_1.config(font = Font_tuple) button_exit = tk.Button(screen, text='exit',command = lambda:exit_program(),bg= 'black',fg= 'white',width= 5 ,height = 2) button_exit.place(x= 300 , y = 240) button_exit.config(font = Font_tuple) print(screen.winfo_screenwidth()) print(screen.winfo_screenheight()) screen.mainloop() main_p()
#!/usr/bin/python3 import simplytaxi import premiumtaxi import reg from taxilist import taxiList print("\nWelcome to the new system of Tax Hippokampoi") print("Terminal: Buenavista #2 Shopping Mall\n\n") while True: if len(taxiList) <= 10: print("Please request more Taxis to this location\n") print("Please entry one of the following options:\n") X = input("1 - TaxiX -- New simply Taxi order -- \n2 - TaxiGold -- New premium Taxi order --\n3 - Register new vehicle\n4 - Exit\n\nOption: ") X = int(X) print("") if X == 1: simplytaxi.TaxiX(taxiList) elif X == 2: premiumtaxi.TaxiGold(taxiList) elif X == 3: reg.TaxiRegister(taxiList) elif X == 4: break else: print("Please enter valid option\n")
# -*- coding: utf-8 -*- """ Created on Wed Mar 4 09:59:27 2020 """ def fizzbuzzNumber(number): """ Prüft für eine Zahl, ob Sie durch 3 und oder 5 teilbar ist. Parameters ---------- number : int Die zu prüfende Zahl Returns ------- 'Fizz', wenn number durch 3 teilbar 'Buzz', wenn number durch 5 teilbar 'FizzBuzz', wenn number durch 3 und 5 teilbar Sonst die Zahl selber als String """ fizz = (number % 3 == 0) buzz = (number % 5 == 0) if fizz and buzz: return "FizzBuzz" elif fizz: return "Fizz" elif buzz: return "Buzz" else: return str(number) def run(): ''' Für alle Zahlen von 1-100 wird die jeweilige Ausgabe unter Nutzung der Funktion fizzbuzzNumber(...) erzeugt. Returns ------- Einen String mit der Auflistung aller Zahlen und mit 10 Zahlen pro Zeile. Trennung erfolgt mit Komma und Leerzeichen: "1, 2, Fizz, 4" Nach der letzten Zeile erfolgt ein Zeilenumbruch. ''' result = '' for x in range(1, 101): result += fizzbuzzNumber(x) if x % 10 == 0: result += '\n' else: result += ', ' return result if __name__ == '__main__': print( run() )
#!/usr/bin/env python3 import BlackJack_Main as main import print_functions as pf def Game(): #_StartValues endgame=False Deck=[2,3,4,5,6,7,8,9,10,'J','Q','K','A']*4 dealer_hand=[] player_hand=[] print(f'You have {Credits["bank"]}$') #_place bet while True: bet_input=input('place bet: ') if not bet_input.isdigit(): print('please enter a number') continue if int(bet_input)>int(Credits["bank"]): print(f'you cant spend more than {Credits["bank"]}$') continue Credits['bet']=int(bet_input) break #_Hand out first 2 cards dealer_hand=main.first_play(dealer_hand,Deck) player_hand=main.first_play(player_hand,Deck) player_points=main.count_cards(player_hand) print('\n Dealer Hand:') pf.DisplayDealerHidden(dealer_hand) print(' Your Hand:') print(pf.DisplayCards(player_hand)) #BlackJack! if player_points==21: if player_points==main.count_cards(dealer_hand): print('\n Dealer Hand:') print(pf.DisplayCards(dealer_hand)) print(' Your Hand:') print(pf.DisplayCards(player_hand)) print(f'The House drew a Blackjack as well, bet moves to next round') dealer_hand=main.first_play(dealer_hand,Deck) player_hand=main.first_play(player_hand,Deck) player_points=main.count_cards(player_hand) print('\n Dealer Hand:') pf.DisplayDealerHidden(dealer_hand) print(' Your Hand:') print(pf.DisplayCards(player_hand)) endgame=True else: print(f'Blackjack! You won {Credits["bet"]} $. You own : : {Credits["bank"]}') endgame=True #_Game while endgame==False: #_Players Choice Choice=input('\n [1]Hit [2]stand [3] Fold or [4] Split? \n\n ') if Choice not in ('1','2','3','4'): print ('\n please enter a valid choice to continue') continue #_[1] Hit if Choice=='1': player_hand.append(Deck.pop()) print(pf.DisplayCards(player_hand)) player_points=main.count_cards(player_hand) if player_points>=21: main.result('',player_points,Credits) endgame=True while endgame==False: c_hit=input('[1]Hit or [2]Stand ? ') if c_hit not in ('1','2'): print ('\n please enter a valid choice to continue') continue if c_hit=='1': player_hand.append(Deck.pop()) print(pf.DisplayCards(player_hand)) player_points=main.count_cards(player_hand) print (player_points) if player_points>=21: main.result('',player_points,Credits) break continue if c_hit=='2': dealer_hand=main.dealer_play(dealer_hand,Deck) print(pf.DisplayCards(dealer_hand)) print(pf.DisplayCards(player_hand)) player_points=main.count_cards(player_hand) dealer_points=main.count_cards(dealer_hand) main.result(dealer_points,player_points,Credits) break break #_[2] Stand if Choice=='2': dealer_hand=main.dealer_play(dealer_hand,Deck) print(pf.DisplayCards(dealer_hand)) print(pf.DisplayCards(player_hand)) player_points=main.count_cards(player_hand) dealer_points=main.count_cards(dealer_hand) main.result(dealer_points,player_points,Credits) break #_[3]Fold if Choice=='3': print(f'Fold, you got {int(Credits["bet"])/2}$ back') print (Credits['bank']) Credits['bank']=int(Credits['bank'])+ (int(Credits["bet"])/2) print(f'You own : {Credits["bank"]}') break #_[4]Split if Choice=='4': #_check if split is possible if player_hand[0]!=player_hand[1]: print('you need a pair to split.') continue if int(Credits['bet'])*2>int(Credits['bank']): print('not enough funds to double the bet.') continue else: #Split Decks and Add one card DeckA=[] DeckB=[] Da_list=[] Db_list=[] printline='' Credits['bet']=int(Credits['bet'])*2 print(f'bet doubled to {Credits["bet"]}') DeckA.append(player_hand[0]) DeckB.append(player_hand[1]) DeckA.append(Deck.pop()) DeckB.append(Deck.pop()) #build Print String for split Da_list=pf.DisplayCards(DeckA).split('\n') Db_list=pf.DisplayCards(DeckB).split('\n') for line in range(0,7): if line>0 and line<6: storageline=Da_list[line] + '| ' + Db_list[line] printline+=storageline + '\n' else: storageline=Da_list[line] + ' ' + Db_list[line] printline+=storageline + '\n' #dealer round dealer_hand=main.dealer_play(dealer_hand,Deck) dealer_points=main.count_cards(dealer_hand) #_print cards print('\n Dealer Hand:') print(pf.DisplayCards(dealer_hand)) print('\n Your Hand:') print (printline) DeckAValue=main.count_cards(DeckA) DeckBValue=main.count_cards(DeckB) if DeckAValue>DeckBValue and DeckAValue<22: main.result(dealer_points,DeckAValue,Credits) break if DeckBValue>DeckAValue and DeckBValue<22: main.result(dealer_points,DeckBValue,Credits) break if DeckAValue==DeckBValue: main.result(dealer_points,DeckAValue,Credits) break #_GAME Credits={'bank':100, 'bet':0} print('Welcome to the table!') while True: Game() #question restart while True: Choice=input('\n [1]continue game [2]Leave table \n\n ') if Choice not in ('1','2'): print ('\n please enter a valid choice to continue') continue else: break if Choice=='1': if Credits['bank']<=0: print("You're broke!,Goodbye") break else: continue else: break
class Room(): """ The Room class represents one room and is initialized by passing a room name. Stores all created rooms in a list 'Room.rooms'. """ rooms = [] def __init__(self, room_name): """ Creates a Room object which connect other classes in the game. Args: room_name (string): The name of the room. Other values: description (string): The description of the room. full_describe (boolean): The value indicates whether the room was explored. linked_rooms (dict): The dictionary containing all adjacent rooms, the key indicates the direction of the door. character (Character/Guest/Police): The character standing in the room. item (Item): The item which is in the room. note (string): The note added to the room. command (int): The value assigned to the room. """ self._name = room_name self._description = "" self._full_describe = False self.linked_rooms = {} self._character = None self._item = None self._note = '' self._command = 0 Room.rooms.append(self) @property def name(self): """Gets or sets the name of the room.""" return self._name @name.setter def name(self, room_name): self._name = room_name @property def description(self): """Gets or sets the description of the room.""" return self._description @description.setter def description(self, room_description): self._description = room_description @property def full_describe(self): """Gets or sets the value indicating a room exploration.""" return self._full_describe @full_describe.setter def full_describe(self, describe): self._full_describe = describe def link_room(self, room_to_link, direction): """ Add door which links a rooms together. Args: room_to_link (Room): The Room object. direction (string): The direction in which to link the adjacent room. """ self.linked_rooms[direction] = room_to_link #print( self.name + " linked rooms :" + repr(self.linked_rooms) ) @property def character(self): """Gets or sets the character (Guest/Policeman) in the room.""" return self._character @character.setter def character(self, new_character): self._character = new_character @property def item(self): """Gets or sets the item in the room.""" return self._item @item.setter def item(self, new_item): self._item = new_item @property def note(self): """Gets or sets the note to the room.""" return self._note @note.setter def note(self, note): self._note = note @property def command(self): """Gets or sets the command to the room.""" return self._command @command.setter def command(self, command): self._command = command def get_content(self): """ Finds out if there is an item and/or a character in the room. Returns 2 boolean values: item present, character present """ item = False if self.item: item = True if self.character: self.character.describe() return item, True return item, False def move(self, direction): """ Move to another room based on the given direction. Returns adjacent room (if is in that direction) or current room. Args: direction (string): The direction in which to move. """ if direction in self.linked_rooms: return self.linked_rooms[direction] else: print("\tYou can't go that way.") return self def describe(self): """ Prints description of the room. """ print(self.name) print("--------------------") print(self.description) if len(self.linked_rooms) > 0: self.get_details() if self.full_describe: self.get_more_details() def get_details(self): """ Prints adjacent rooms. """ print("Doors:") for direction in self.linked_rooms: room = self.linked_rooms[direction] print("\t[" + direction + "]: " + room.name) def get_more_details(self): """ Prints items and characters in the room. """ item = False if self.item: self.item.describe() item = True if self.character: self.character.describe() return item, True if not item: print("I don't see anything special.") return item, False
hello_str = 'hello world' # 1. 判断是否以指定字符串开始 print(hello_str.startswith('Hello')) # 2. 判断是否以指定字符串结束 print(hello_str.endswith('world')) # 3. 查找指定字符串 # index 同样可以查找指定的字符串在大字符串中的索引 # index 如果指定的字符串不存在,会报错 # find 如果指定的字符串不存在,会返回-1 print(hello_str.find('llo')) print(hello_str.find('abc')) # 返回 -1 # 4. 替换字符串 # replace 方法执行完成之后,会返回一个新的字符串 # 注意:不会修改原有字符串的内容 print(hello_str.replace('world', 'python')) print(hello_str)
i = 0 while i < 10: # continue 某一条件满足时,不执行后续重复的代码,跳转到循环开始的条件判断 # i == 3 if i == 3: # 注意:在循环中,如果使用 continue 关键字 # 在使用关键字之前,需要确认循环的计数是否修改 # 否则可能会导致死循环 i += 1 continue print(i) i += 1
def binary_search1(li, item): """递归版本:二分查找""" n = len(li) if n > 0: mid = n // 2 if li[mid] == item: return True elif item < li[mid]: return binary_search1(li[:mid], item) else: return binary_search1(li[mid + 1:], item) else: return False def binary_search2(li, item): """非递归版本:二分查找""" n = len(li) low = 0 high = n - 1 while low <= high: mid = (high + low) // 2 if li[mid] == item: return True elif li[mid] > item: high = mid - 1 elif li[mid] < item: low = mid + 1 return False if __name__ == '__main__': li = [1, 2, 3, 4, 5, 7, 8, 9] print(binary_search1(li, 6)) print(binary_search1(li, 3)) print(binary_search2(li, 6)) print(binary_search2(li, 3)) """ False True False True """
# 多值参数又叫可变长参数 def demo(num, *nums, **person): print(num) print(nums) print(person) # demo(1) # demo(1, 2, 3, 4) demo(1, 2, 3, 4, 5, name='小明', age=18)
# print triples of lines import sys import json class Triple: def __init__(self): self.triple = [] def push(self, line): if len(self.triple) == 3: self.pop() self.triple.append(line) def pop(self): if len(self.triple) > 0: json.dump(self.triple, sys.stdout) self.triple = self.triple[1:] if __name__ == "__main__": for line in sys.stdin: paragraphs = json.loads(line) t = Triple() for para in paragraphs: for line in para: t.push(line) t.pop()
import numpy as np import math import matplotlib as mpl import matplotlib.pyplot as plt t = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] y = [6.80, 3.00, 1.50, 0.75, 0.48, 0.25, 0.20, 0.15] x1 = t y1 = y # (a) # Assume some initial values for x1 & x2 and then apply gradient descent xA = [0, 0] def computeJ(x1, x2, t, y): e = np.exp(np.multiply(x2, t)) v = np.multiply(np.multiply(2, np.subtract(np.multiply(x1, e),y)), e) v1 = np.multiply(v, np.multiply(x1,t)) J = [np.sum(v), np.sum(v1)] return J n_iter = 0 eta = 0.02 delta = [10, 10] while (abs(np.linalg.norm(delta)) > 0.0000001 and n_iter<=10000): delta = computeJ(xA[0], xA[1], t, y) xA -= np.multiply(eta, delta) n_iter += 1 print "(x1,x2) = (", xA[0], ",", xA[1], ")" error1 = 0 for i in range(len(t)): error1 += math.pow((y[i] - (xA[0] * math.exp(xA[1]*t[i]))),2) print "Error in Gradient Descent: ", error1 # (b) B = np.transpose(np.matrix(np.log(y))) A = np.transpose(np.ones((2,len(y)))) A[:,1] = t Q, R = np.linalg.qr(A) xB = np.linalg.solve(R, np.matmul(np.transpose(Q),B)) xB[0,0] = np.exp(xB[0,0]) print "(x1,x2) = (", xB[0,0], ",", xB[1,0], ")" error2 = 0 for i in range(len(t)): error2 += math.pow((y[i] - (xB[0] * math.exp(xB[1]*t[i]))),2) print "Error in Linear Least Squares: ", error2 # Graph mpl.rcParams['lines.color'] = 'k' mpl.rcParams['axes.prop_cycle'] = mpl.cycler('color', ['k']) x = np.linspace(-1, 6, 400) y = np.linspace(-1, 10, 400) x, y = np.meshgrid(x, y) def axes(): plt.axhline(0, alpha=.1) plt.axvline(0, alpha=.1) axes() l1 = plt.contour(x, y, (y - xA[0] * (math.e ** (xA[1]*x))), [0], colors='red') l1.collections[0].set_label('Non-linear Least Squares') l2 = plt.contour(x, y, (y - xB[0,0] * (math.e ** (xB[1,0]*x))), [0], colors='green') l2.collections[0].set_label('Linear Least Squares') plt.plot(x1,y1,'bo') plt.xlabel('x') plt.ylabel('y') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.legend() plt.show()
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: result = TreeNode() if root1 and root2: result.val = root1.val + root2.val result.left = Solution.mergeTrees(result, root1=root1.left, root2=root2.left) result.right = Solution.mergeTrees(result, root1=root1.right, root2=root2.right) elif root1: result.val = root1.val if root1.left: result.left = Solution.mergeTrees(result, root1 = root1.left, root2 = None) if root1.right: result.right = Solution.mergeTrees(result, root1 = root1.right, root2 = None) elif root2: result.val = root2.val if root2.left: result.left = Solution.mergeTrees(result, root1 = None, root2 = root2.left) if root2.right: result.right = Solution.mergeTrees(result, root1 = None, root2 = root2.right) else: result = None return result
class Solution: def thirdMax(self, nums: List[int]) -> int: nums.sort(reverse = True) unique = [] while len(nums) > 0: var = nums.pop(0) if var not in unique: unique.append(var) if len(unique) == 3: return unique[2] return unique[0] #O(n)
# Peter wants to generate some prime numbers for his cryptosystem. # Help him! Your task is to generate all prime numbers between # two given numbers! #Input #The input begins with the number t of test cases in a single line (t<=10). # In each of the next t lines there are two numbers m and n # (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space. #Output #For every test case print all prime numbers p such that m <= p <= n, # one number per line, test cases separated by an empty line. import math def sieveoferathostenes(num,num1): prime = [True for i in range(num + 1)] p = 2 while(p <= math.sqrt(num)): if (prime[p] == True): for i in range(p * 2,num + 1 ,p): prime[i] = False p += 1 prime[0] = False prime[1] = False listy = [] for p in range(num1,num + 1): if prime[p] == True: listy.append(p) return listy t = int(input()) output = '' for a in range(t ) : if a > 0: output += '\n' lower,bigger = input().split(' ') for j in sieveoferathostenes(int(bigger),int(lower)): output += str(j) + ' ' print(output[:-1])
#Hemisphere Network is the largest television network in Tumbolia, # a small country located east of South America (or south of East America). # The most popular sport in Tumbolia, unsurprisingly, is soccer; # many games are broadcast every week in Tumbolia. #Hemisphere Network receives many requests to replay dubious plays # usually, these happen when a player is deemed to be offside by the referee. # An attacking player is offside if he is nearer to his opponents’ goal line than the second last opponent. # A player is not offside if # he is level with the second last opponent or # he is level with the last two opponents. #Through the use of computer graphics technology, # Hemisphere Network can take an image of the field # and determine the distances of the players to the defending team’s goal line, # but they still need a program that, given these distances, decides whether a player is offside. a ,b = '30', '30' while True: a,b = input().split(' ') if int(a) == 0 and int(b)== 0: break attack= input().split(' ') lisa = [int(x) for x in attack] defend = input().split(' ') lisd = [int(x) for x in defend] lisd.sort() if min(lisa) < lisd[1]: print('Y') else: print('N')
#7) Определить количество разрядов числа #Написать функцию, которая определяет количество разрядов введенного целого #числа """def digits(n): i = 0 while n > 0: n = n//10 i += 1 return i num = abs(int(input('Введите число: '))) print('Количество разрядов:', digits(num))""" def func(): try: vvod = int(input("введите число:")) vvod2 = str(vvod) print(len(vvod2)) except Exception: print("введите только числа: ") func() func()
# 5.11 break문없이 재작성 sum = 0 number = 0 while sum <= 100: number += 1 sum += number print("마지막 숫자는", number,"입니다.") print("합계는", sum,"입니다.") # 5.12 continue문 없이 재작성 sum = 0 number = 0 while number < 20: number += 1 if number == 10 or number == 11: sum = sum else: sum += number print("합계는", sum, "입니다.")
def max(num1, num2): result = num1 if (num1 > num2) else num2 return result def main(): i = 5 j = 2 k = max(i, j) print(i,"와/과", j, "중에서 큰 수는", k, "입니다.") main()
score = eval(input("Input your score: ")) pay = eval(input("Input your pay: ")) if score > 90: afterPay = pay * (1 + 0.03) else: afterPay = pay * (1 + 0.01) print("afterPay: ",afterPay)
""" To classify the input skin into one of the 6 skin tones """ import pandas as pd from sklearn.neighbors import KNeighborsClassifier def skin_tone_knn(mean_values): # df = pd.read_csv("public\pre-processing\skin_tone_dataset_RGB.csv") df = pd.read_csv("public\skin_tone_dataset.csv") X = df.iloc[:, [1, 2, 3]].values y = df.iloc[:, 0].values classifier = KNeighborsClassifier(n_neighbors=6, metric='minkowski', p=2) classifier.fit(X, y) X_test = [mean_values] y_pred = classifier.predict(X_test) return y_pred[0]
# -*- coding: utf-8 -*- """ Created on Tue Sep 11 18:52:15 2018 @author: admin Problem Statement: In this assignment students will build the random forest model after normalizing the variable to house pricing from boston data set. """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn import datasets boston = datasets.load_boston() features = pd.DataFrame(boston.data, columns=boston.feature_names) targets = pd.DataFrame(boston.target) from sklearn.preprocessing import Normalizer norm = Normalizer() X = norm.fit_transform(features) y = targets from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state=0) #fitting the random forest classification to the training sets from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor(n_estimators=10, oob_score=True, random_state=0) rf.fit(X_train, y_train) y_pred = rf.predict(X_test) #Step 6. Plotting the graph for plt.scatter(y_test, y_pred) plt.xlabel("Actual Price") plt.ylabel("Predicted prices") plt.title("Prices vs Predicted prices")
import re def is_pangram(given: str) -> bool: temp = re.sub(r'[^a-zA-Z]', '', given).lower() return len(set(temp)) == 26
import functools from typing import List def is_prime(knowns: List[int], num: int) -> bool: return 0 == len([k for k in knowns if k <= num and num%k == 0]) def memoize(func): cache = func.cache = {} @functools.wraps(func) def memoized_func(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = func(*args, **kwargs) return cache[key] return memoized_func @memoize def find_next_few_primes(primes: List[int]) -> List[int]: limit = primes[-1] ** 2 new = [i for i in range(primes[-1], limit, 2) if is_prime(primes, i)] return primes + new @memoize def nth_prime(n: int) -> int: if n < 1: raise ValueError('Non negative numbers only please') primes = [2, 3] while len(primes) <= n: primes = find_next_few_primes(primes) return primes[n-1]
import re from itertools import groupby def decode(given: str) -> str: numbers = (int(n) if n else 1 for n in re.split('\D', given)) letters = ''.join(n for n in re.split('\d', given) if n) return ''.join(number*letter for number,letter in zip(numbers,letters)) def encode(given: str) -> str: code = '' for letter, group in groupby(given): count = len(list(group)) code += (str(count) if count > 1 else '') + letter return code
def flatten(nested_list): ## type hinting here can be interesting def helper(): for item in nested_list: if isinstance(item, (list, tuple)): for subitem in flatten(item): yield subitem elif item is not None: yield item return list(helper())
import numpy as np #reversing an array normally using reverse method arr = [1,2,3,4,5] arr.reverse() print(arr) #reversing an array using reversed method arr1=[1,2,3,4,5,6,7,8,9,10] print(list(reversed(arr1))) #reversing using flip method in numpy arr2=np.array(['p','r','a','b','h','a','s','a','l','e','t','i']) print(np.flip(arr2))
def binary_search(my_list,target): left=0 right=len(my_list)-1 while left<=right: middle=(left+right)//2 if target==my_list[middle]: return middle elif target>=my_list[middle]: left=middle+1 else: right=middle-1 return -1 x=binary_search([1,2,3,4,5,6,7,8,9],1) print(x)
# -*- coding: utf-8 -*- ''' Задание 6.1b Сделать копию скрипта задания 6.1a. Дополнить скрипт: Если адрес был введен неправильно, запросить адрес снова. Ограничение: Все задания надо выполнять используя только пройденные темы. ''' #Solution address_correct = False while not address_correct: IP_address = input("Enter IP address in format 10.0.1.1: ") if IP_address.count('.') == 3: IP_address = [x for x in IP_address.split('.')] for part in IP_address: if part.isdigit(): part = int(part) if part in range(0,256): address_correct = True else: address_correct = False print('Incorrect IPv4 address') break else: address_correct = False print('Incorrect IPv4 address') break else: print('Incorrect IPv4 address') if ( IP_address[0] in range(1, 128) or IP_address[0] in range(127, 192) or IP_address[0] in range (191, 224) ): print('unicast') elif IP_address[0] in range(223, 240): print('multicast') elif ( IP_address[0]==255 and IP_address[1]==255 and IP_address[2]==255 and IP_address[3]==255 ): print('local broadcast') elif ( IP_address[0]==0 and IP_address[1]==0 and IP_address[2]==0 and IP_address[3]==0 ): print('unassigned') else: print('unused')
map = {"miles": 1, "meters": 1609.34, "yards": 1760 } def convert(fromUnit, toUnit, value): if fromUnit == "miles" and toUnit == "yards": result = value * 1760 return result elif fromUnit == "miles" and toUnit == "meters": result = value * 1609.344 return result elif fromUnit == "yards" and toUnit == "miles": result = value / 1760 return result elif fromUnit == "yards" and toUnit == "meters": result = value * 0.9144 return result elif fromUnit == "meters" and toUnit == "miles": result = value / 1609.344 return result elif fromUnit == "meters" and toUnit == "yards": result = value / 0.9144 return result elif fromUnit == toUnit: return value else: raise ConversionNotPossible("Units not convertable") class ConversionNotPossible(ValueError): pass
''' n개의 자연수 입력 각 자연수를 뒤집은 후 그 뒤집은 수가 소수이면 그 뒤집은 수를 출력 뒤집는 함수 reverse(x) 소수인지 확인하는 함수 isPrime(x) ''' import sys # sys.stdin = open("input.txt", "rt") def reverse(x): result = 0 while x > 0: n = x%10 x = x//10 result = result*10 + n return result def isPrime(x): if x == 1: return False for i in range(2, (x//2)+1): if x%i == 0: return False else: return True n = int(input()) nums = list(map(int, input().split())) for num in nums: num = reverse(num) if isPrime(num): print(num, end=' ')
def sum_weight(beep_weight,bop_weight): total_weight=beep_weight+bop_weight return total_weight def calc_avg_weight(beep_weight,bop_weight): avg_weight=(beep_weight+bop_weight)/2 return avg_weight def run(): beep_weight=int(input("What is the weight of Beep?")) bop_weight=int(input("What is the weight of Bop?")) decision=input("What would you like to calcluate (sum or average)?") if(decision=="sum"): print("The sum of Beep and Bop's weight is "+ str(sum_weight(beep_weight,bop_weight))) elif(decision=="average"): print("The avg of Beep and Bop's weight is " + str(calc_avg_weight(beep_weight,bop_weight))) else: print("invalid decision") run()
answer=input("What happens when the last petal falls?\n") print("My dear Bella when the last petal falls "+ answer)