text
stringlengths
37
1.41M
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root:return res = [] def helper(root, depth): if not root:return if len(res) == depth: res.append([]) res[depth].append(root.val) if root.left: helper(root.left, depth + 1) if root.right: helper(root.right, depth + 1) helper(root, 0) res.reverse() return res
x = 1 while x==1: print("Triangle Program!") a = int(input("Enter value of a : ")) b = int(input("Enter value of a : ")) c = int(input("Enter value of a : ")) if(a<=0 or b<=0 or c<=0): print("Invalid dimensions!") elif(a>=b+c or b>=a+c or c>=a+b): print("Triangle cannot be formed!") elif(a==b & b==c and c!=a): print("Impossible!") elif(a==b & b!=c & c==a): print("Impossible!") elif(a!=b & b==c & c==a): print("Impossible!") elif(a==b & b==c & c==a): print("Equilateral triangle!") elif(a!=b & b!=c & c!=a): print("Scalene triangle!") elif(a!=b & b!=c & c==a): print("Isosceles triangle!") elif(a!=b & b==c & c!=a): print("Isosceles triangle!") elif(a==b & b!=c & c!=a): print("Isosceles triangle!") x = int(input("Enter 1 to continue and 0 to exit"))
# -*- coding: utf-8 -*- """ Created on Sat Dec 1 21:15:35 2018 @author: kaysm """ import itertools as it Input=open("Ordering Strings of Varying Length Lexicographically.txt", "r") Input=Input.read().strip().split("\n") Symbols="".join(Input[0].split(" ")) N=int(Input[1]) f = open('Ordering Strings of Varying Length Lexicographically Output.txt','w') List=[] for i in range(1,N+1): for pattern in it.product(Symbols,repeat=i): List.append("".join(pattern)) List=(sorted(List, key=lambda word: [Symbols.index(c) for c in word])) f.write("\n".join(List))
size=int(input()) for row in range(size): for space in range(size-(row+1)): print(" ",end=" ") for n1 in range(row+1): print("*",end=" ") print()
size=int(input()) for row in range(size): for space in range(row): print(" ",end="") for star in range(size-row): print("*",end=" ") print(6)
class CPF(object): INVALID_CPFS = ['00000000000', '11111111111', '22222222222', '33333333333', '44444444444', '55555555555', '66666666666', '77777777777', '88888888888', '99999999999'] def __init__(self, cpf): self.cpf = cpf def validate_size(self): cpf = self.cleaning() if bool(cpf and (len(cpf) > 11 or len(cpf) < 11)): return False return True def validate(self): cpf = self.cleaning() if self.validate_size() and cpf not in self.INVALID_CPFS: digit_1 = 0 digit_2 = 0 i = 0 while i < 10: digit_1 = (digit_1 + (int(cpf[i]) * (11-i-1))) % 11 if i < 9 else digit_1 digit_2 = (digit_2 + (int(cpf[i]) * (11-i))) % 11 i += 1 return ((int(cpf[9]) == (11 - digit_1 if digit_1 > 1 else 0)) and (int(cpf[10]) == (11 - digit_2 if digit_2 > 1 else 0))) return False def cleaning(self): return self.cpf.replace('.', '').replace('-', '') if self.cpf else '' def format(self): return '%s.%s.%s-%s' % (self.cpf[0:3], self.cpf[3:6], self.cpf[6:9], self.cpf[9:11]) if self.cpf else '' class ZipCode(object): def __init__(self, zip_code): """ Class to interact with zip_code brazilian numbers """ self.zip_code = zip_code def format(self): return '%s-%s' % (self.zip_code[0:5], self.zip_code[5:8]) if self.zip_code else '' def cleaning(self): return self.zip_code.replace('-', '') if self.zip_code else '' class Phone(object): def __init__(self, phone): self.phone = phone def cleaning(self): if self.phone: phone = self.phone.replace('(', '') phone = phone.replace(')', '') phone = phone.replace('-', '') phone = phone.replace(' ', '') phone = phone.replace('.', '') phone = phone.replace('+', '') return phone return '' def format(self): if self.phone: if len(self.phone) == 8: return '%s.%s' % (self.phone[0:4], self.phone[4:8]) if len(self.phone) == 9: return '%s %s.%s' % (self.phone[0:1], self.phone[1:5], self.phone[5:9]) if len(self.phone) == 10: return '%s %s.%s' % (self.phone[0:2], self.phone[2:6], self.phone[6:10]) if len(self.phone) == 11: return '%s %s%s.%s' % (self.phone[0:2], self.phone[2:3], self.phone[3:7], self.phone[7:11]) if len(self.phone) == 13: return '+%s (%s) %s %s.%s' % ( self.phone[0:2], self.phone[2:4], self.phone[4:5], self.phone[5:9], self.phone[9:13] ) return '' class CNPJ(object): def __init__(self, cnpj): """ Class to interact with cnpj brazilian numbers """ self.cnpj = cnpj def calculating_digit(self, result): result = result % 11 if result < 2: digit = 0 else: digit = 11 - result return str(digit) def calculating_first_digit(self): one_validation_list = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] result = 0 pos = 0 for number in self.cnpj: try: one_validation_list[pos] except IndexError: break result += int(number) * int(one_validation_list[pos]) pos += 1 return self.calculating_digit(result) def calculating_second_digit(self): two_validation_list = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] result = 0 pos = 0 for number in self.cnpj: try: two_validation_list[pos] except IndexError: break result += int(number) * int(two_validation_list[pos]) pos += 1 return self.calculating_digit(result) def validate(self): """ Method to validate brazilian cnpjs """ self.cnpj = self.cleaning() if len(self.cnpj) != 14: return False checkers = self.cnpj[-2:] digit_one = self.calculating_first_digit() digit_two = self.calculating_second_digit() return bool(checkers == digit_one + digit_two) def cleaning(self): if self.cnpj: return self.cnpj.replace('-', '').replace('.', '').replace('/', '') return '' def format(self): """ Method to format cnpj numbers. """ if self.cnpj: return '%s.%s.%s/%s-%s' % (self.cnpj[0:2], self.cnpj[2:5], self.cnpj[5:8], self.cnpj[8:12], self.cnpj[12:14]) return ''
def anonymous(x): return x**2 + 1 def integrate(fun, start, end): step = 0.1 intercept = start area = 0 while intercept < end: intercept += step high = fun(intercept) area = area + step*high ''' your work here ''' return area print(integrate(anonymous, 0, 10))
#try to plot bernoulli dsitribution import math import matplotlib.pyplot as plt def binom(n, p): list_x = [] list_y = [] for i in range(n+1): print(i) list_x.append(i) PX = ( math.factorial(n)/(math.factorial(i)*math.factorial(n-i)) ) * (p**i) * ((1-p)**(n-i)) list_y.append(PX) return list_x, list_y x, y = binom(100,0.01) plt.plot(x,y, 'ro') plt.show()
largest = 0 smallest= 0 while True: num = input("Enter a number:") if num=="done": break try: n=int(num) except: print("Invalid input") continue if n>largest: largest=n else: smallest=n print("Maximum is",largest) print("Minimum is",smallest)
names = [] for i in range(10): name = input("enter the name") if name not in names: names.append(name) else: print("please enter unique name") print(names)
a=[1,2,3,4,5,6,7] b=0 for number in a: b+=number print(b) # length=0 # for number in a: # length+=1 # print(length) # range(start, stop, step) tao ra cac so bang cach + step tu start den truoc stop # print(list(range(6))) # print(list(range(-3,8,1))) # print(list(range(3, -4.-1))) # for i in range(6): # print(i) # animals=['dog', 'cat', 'cow', 'fish'] # for i in range(len(animals)): # print(animals[i]) # for number in range(2,7): # print(list(range(1, number))) # a=[10,20,30,40,50,60] # length= len(a) # for i in range(-1,-length-1,-1): # print(a[i])
''' Created on Apr 1, 2013 @author: redw0lf ''' import pygame from pygame.locals import MOUSEBUTTONDOWN, MOUSEMOTION from breakout.data.GameElement import GameElement class Ball(GameElement): """ This class describes the game ball, which moves around the screen with a given slope and a given speed """ def __init__(self): # GameElement.__init__(self) GameElement.__init__(self) self.image, self.rect = self.load_image('nicubunu_Monkey_head.png', -1) self.image = pygame.transform.scale(self.image, (25, 25)) self.rect = self.image.get_rect() self.slope = 3 screen = pygame.display.get_surface() self.area = screen.get_rect() self.speed = -3 self.rect.center = self.area.center self.rect.y = self.area.height - 2 * self.rect.h self.resetState = True def update(self): """ this is the update method for the ball, it checks if the ball is within the boundaries of the gamefield if this is not the case it is reflected. """ # if the ball does not move i.e. in the beginning and after # a reset the update step is skipped if self.resetState == True: return #lets the ball reflect from the walls if self.rect.top < self.area.top or \ self.rect.bottom > self.area.bottom: self.slope = -self.slope if self.rect.left < self.area.left or \ self.rect.right > self.area.right: self.speed = -self.speed newpos = self.rect.move((self.speed, self.slope)) self.rect = newpos def checkHit(self, targets): """ Checks for multiple Blocks, if the ball collides with any of these blocks """ for target in targets.sprites(): hitbox = target.rect if hitbox.colliderect(self.rect): # check if hit from side, this is when the center of the ball # is within the top and bottom of the block #hitbox = target.rect.inflate(0, 0) if self.rect.centery < hitbox.top and \ self.rect.centery > hitbox.bottom: self.speed = -self.speed else: self.slope = -self.slope return target return None def handleEvent(self, event): """ Event handler for the ball if the ball is in the reset state it moves according to the mouse if the mousebutton is clicked the reset state is leaved """ if event.type == MOUSEMOTION: if self.resetState == True: self.rect.center = (event.pos[0], self.rect.centery) elif event.type == MOUSEBUTTONDOWN: self.resetState = False def reverse(self): self.slope = -self.slope def reflect(self): self.speed = -self.speed def resetSelf(self, barPosition): """ sets the ball on top of the bar and let the ball enter the reset state """ self.rect.centerx = barPosition.centerx self.rect.midbottom = barPosition.midtop self.resetState = True
from tkinter import* from math import* def cal(): a=leng_e.get() b=wid_e.get() h=he_e.get() length=int(a) width=int(b) height=int(h) ans=2*height*(width+height) answer=Label(main,text="The abswer is: "+str(ans)) answer.grid(row=4,column=0) def cl(): main.destroy() def rect_round_open(): global main,leng_e,wid_e,he_e main=Tk() main.geometry("1000x500") leng_L=Label(main,text="Length= ") leng_L.grid(row=0,column=0) leng_e=Entry(main,width=20) leng_e.grid(row=0,column=1) wid_L=Label(main,text="Width= ") wid_L.grid(row=1,column=0) wid_e=Entry(main,width=20) wid_e.grid(row=1,column=1) he_L=Label(main,text="Height= ") he_L.grid(row=2,column=0) he_e=Entry(main,width=20) he_e.grid(row=2,column=1) st=Button(main,text="Start",bg="red",command=cal) st.grid(row=3,column=0) q=Button(main,text="Back",bg="red",command=cl) q.grid(row=8,column=0)
from tkinter import* def triangle_w(): global triangle_main triangle_main=Tk() triangle_main.title("Triangle") pytago=Button(triangle_main,text="Square",command=pytago_w,fg="green") pytago.pack() Normal_area=Button(triangle_main,text="Normal area",fg="green",command=triangle_normal) Normal_area.pack() Normal_per=Button(triangle_main,text="Normal Perimeter",fg="green",command=triangle_normal_per) Normal_per.pack() close=Button(triangle_main,text="Close",command=close_triangle_m) close.pack() def close_triangle_m(): triangle_main.destroy() def pytago_w(): global pytago_main global a1,b1,c1 pytago_main=Tk() pytago_main.title("Square") pytago_main.geometry("600x400") note=Label(pytago_main,text="Choose your edge to calculate by write a choosen edge number 0") note.grid(row=0,column=0) a=Label(pytago_main,text="AB=") a.grid(row=1,column=0) a1=Entry(pytago_main,width=5) a1.grid(row=1,column=1) b=Label(pytago_main,text="AC=") b.grid(row=2,column=0) b1=Entry(pytago_main,width=5) b1.grid(row=2,column=1) c=Label(pytago_main,text="BC=") c.grid(row=3,column=0) c1=Entry(pytago_main,width=5) c1.grid(row=3,column=1) start=Button(pytago_main,text="Start",command=start_pytago) start.grid(row=4,column=0) close=Button(pytago_main,text="Close",command=close_win) close.grid(row=5,column=0) def close_win(): pytago_main.destroy() def start_pytago(): a2=a1.get() b2=b1.get() c2=c1.get() a3=int(a2) b3=int(b2) c3=int(c2) if a3==0: ans=sqrt((c3**2)-(b3**2)) ans1=str(ans) ans2=Label(pytago_main,text="AB="+ans1) ans2.grid(row=5,column=0) elif b3==0: ans=sqrt((c3**2)-(a3**2)) ans1=str(ans) ans2=Label(pytago_main,text="AC="+ans1) ans2.grid(row=5,column=0) elif c3==0: ans=sqrt((a3**2)+(b3**2)) ans1=str(ans) ans2=Label(pytago_main,text="BC="+ans1) ans2.grid(row=5,column=0) def triangle_normal(): global pytago_main global Edge1,Height1 pytago_main=Tk() pytago_main.title("Normal") pytago_main.geometry("700x400") lab=Label(pytago_main,text="Normal (area)") lab.grid(row=0,column=0) Edge=Label(pytago_main,text="Edge=") Edge.grid(row=1,column=0) Edge1=Entry(pytago_main,width=20) Edge1.grid(row=1,column=1) Height=Label(pytago_main,text="Height=") Height.grid(row=2,column=0) Height1=Entry(pytago_main,width=20) Height1.grid(row=2,column=1) But=Button(pytago_main,text="Start area",command=start_normal_area) But.grid(row=3,column=0) Close=Button(pytago_main,text="CLose",command=close_normal_area) Close.grid(row=4,column=0) def start_normal_area(): edge2=Edge1.get() height2=Height1.get() height3=int(height2) edge3=int(edge2) ans=(height3*edge3)/2 ans1=Label(pytago_main,text="The answer is: "+str(ans)) ans1.grid(row=4,column=0) def close_normal_area(): pytago_main.destroy() def triangle_normal_per(): global pytago_main global a,b,c pytago_main=Tk() pytago_main.title("Perimeter") pytago_main.geometry("700x400") lab=Label(pytago_main,text="Normal (perimeter)") lab.grid(row=0,column=0) a1=Label(pytago_main,text="a=") a1.grid(row=1,column=0) a=Entry(pytago_main,width=30) a.grid(row=1,column=1) b1=Label(pytago_main,text="b=") b1.grid(row=2,column=0) b=Entry(pytago_main,width=30) b.grid(row=2,column=1) c1=Label(pytago_main,text="c=") c1.grid(row=3,column=0) c=Entry(pytago_main,width=30) c.grid(row=3,column=1) But=Button(pytago_main,text="Start perimeter",command=start_normal_per) But.grid(row=4,column=0) Close=Button(pytago_main,text="CLose",command=close_normal_area) Close.grid(row=5,column=0) def start_normal_per(): a2=a.get() b2=b.get() c2=c.get() a3=int(a2) b3=int(b2) c3=int(c2) ans=a3+b3+c3 ans1=Label(pytago_main,text="The answer is: "+str(ans)) ans1.grid(row=6,column=0)
total = 0 i = 8 while i > 0: total = total + i i=i-1 print(total)
class NombreCortoError(Exception): def __init__(self): self.mensaje="No cuela, tu nombre no puede tener solo dos letras..." super().__init__(self.mensaje) def solucionar(self): print("Solucionando...") class EdadInsuficienteError(Exception): def __init__(self): self.mensaje="Tienes que ser mayor de 18..." super().__init__(self.mensaje) def solucionar(self): print("Solucionando...") class MalGustoError(Exception): def __init__(self): self.mensaje="En serio Naranja? no te da verguenza?" super().__init__(self.mensaje) def solucionar(self): print("Solucionando...") def testcolor(color): if color=="Naranja": raise MalGustoError() return color def testedad(edad): if edad < 18: raise EdadInsuficienteError() return edad def testnombre(nombre): if len(nombre)<3: raise NombreCortoError() return nombre nombre=input("Introduzca su nombre:") edad=int(input("Introduzca su edad:")) color=input("Introduce tu color favorito:") print(testnombre(nombre)) print(testedad(edad)) print(testcolor(color))
import datetime as fechas anho_actual=int(fechas.date.today().year) Nombre_completo=input("Introduce tu nombre completo:") Anho_nacimiento=int(input("Introduce tu año de nacimiento:")) Direccion_email=input("Introduce un correo electrónico:") Telefono=input("Introduce un telefono:") nombre_correcto=len(Nombre_completo)>=10 edad=anho_actual-Anho_nacimiento anho_correcto=edad>=18 email_correcto= "@" in Direccion_email telefono_correcto= Telefono.isnumeric() if nombre_correcto: if anho_correcto: if email_correcto: if telefono_correcto: estado = "Correcto" else: estado = "Telefono no es numérico" else: estado = "el correo no contiene @" else: estado="No eres mayor de edad" else: estado="El nombre no supera 10 caracteres" print(estado)
INTENTOS=3 SWITCHOFF="0" ip="-1" listaip=[] blacklist=[] while ip!=SWITCHOFF: ip=input("Introcude una dirección IP:") #if (listaip.count(ip)<2) or (ip not in blacklist): if ip not in blacklist: listaip.append(ip) if listaip.count(ip)==INTENTOS: blacklist.append(ip) else: print("Tu ip se ha encontrado en una lista negra... ") print(listaip)
''' Two words are blanagrams if they are anagrams but exactly one letter has been substituted for another. Given two words, check if they are blanagrams of each other. Example For word1 = "tangram" and word2 = "anagram", the output should be checkBlanagrams(word1, word2) = true; After changing the first letter 't' to 'a' in the word1, the words become anagrams. For word1 = "tangram" and word2 = "pangram", the output should be checkBlanagrams(word1, word2) = true. Since a word is an anagram of itself (a so-called trivial anagram), we are not obliged to rearrange letters. Only the substitution of a single letter is required for a word to be a blanagram, and here 't' is changed to 'p'. For word1 = "aba" and word2 = "bab", the output should be checkBlanagrams(word1, word2) = true. You can take the first letter 'a' of word1 and change it to 'b', obtaining the word "bba", which is an anagram of word2 = "bab". It is also possible to change the first letter 'b' of word2 to 'a' and obtain "aab", which is an anagram of word1 = "aba". For word1 = "silent" and word2 = "listen", the output should be checkBlanagrams(word1, word2) = false. These two words are anagrams of each other, but no letter substitution was made (the trivial substitution of a letter with itself shouldn't be considered), so they are not blanagrams. Test 1 Input: word1: "tangram" word2: "anagram" Expected Output: true Test 2 Input: word1: "tangram" word2: "pangram" Expected Output: true Test 3 Input: word1: "aba" word2: "bab" Expected Output: true ''' def checkBlanagrams(word1, word2): s_word1 = sorted(word1) s_word2 = sorted(word2) print(s_word1, s_word2) count = 0 for i in range(len(word1)): if s_word1[i] in s_word2: s_word2.pop(s_word2.index(s_word1[i])) if len(s_word2) == 1: return True return False
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): if not matrix: return None res = [] while matrix: res += matrix.pop(0) # 取出矩阵的第一行 if not matrix or not matrix[0]: break matrix = self.TurnMatrix(matrix) return res def TurnMatrix(self, matrix): """ 对矩阵进行逆时针旋转 :param matrix: 旧矩阵 :return: 返回旋转后新的矩阵 """ c_size = len(matrix[0]) r_size = len(matrix) newMatrix = [] for c in range(c_size): newRow = [] for r in range(r_size): newRow.append(matrix[r][c]) newMatrix.append(newRow) newMatrix.reverse() return newMatrix if __name__ == '__main__': m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] s = Solution() res = s.printMatrix(m) print(res)
# -*- coding:utf-8 -*- def swap(_ls, _a, _b): tmp = _ls[_a] _ls[_a] = _ls[_b] _ls[_b] = tmp return _ls class Solution: def __init__(self): self.res = [] def Permutation(self, ss): if ss != None and len(ss) > 0: self.PermutationHelp(list(ss), 0) self.res.sort() return self.res def PermutationHelp(self, sl, idx): if idx == len(sl) - 1: val = ''.join(sl) if val not in self.res: self.res.append(val) else: for j in range(idx, len(sl)): sl = swap(sl, idx, j) self.PermutationHelp(sl, idx + 1) sl = swap(sl, idx, j)
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here if not pHead1: return pHead2 if not pHead2: return pHead1 if pHead1.val <= pHead2.val: headNode=pHead1 pHead1=pHead1.next else: headNode=pHead2 pHead2=pHead2.next ptrNode=headNode while pHead1 and pHead2: if pHead1.val <= pHead2.val: ptrNode.next=pHead1 pHead1=pHead1.next if pHead1.next else None else: ptrNode.next=pHead2 pHead2=pHead2.next if pHead2.next else None ptrNode=ptrNode.next ptrNode.next=pHead1 if pHead1 else pHead2 return headNode
# -*- coding:utf-8 -*- class Solution: def reOrderArray(self, array): if len(array) == 0: return array # 偶数指针和奇数指针 ptr_o = ptr_j = 0 while ptr_o < len(array) and ptr_j < len(array): if (array[ptr_o] % 2 == 1): # 如果是奇数则指针后移 ptr_o += 1 else: ptr_j = ptr_o while ptr_j < len(array) and array[ptr_j] % 2 == 0: ptr_j += 1 if ptr_j == len(array): break else: temp = array[ptr_j] while ptr_j >= ptr_o: array[ptr_j] = array[ptr_j - 1] ptr_j -= 1 array[ptr_o] = temp ptr_o += 1 return array if __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6, 7] s = Solution() print(s.reOrderArray(arr))
#!/usr/bin/env python3 import sys import random #argument checks if len(sys.argv) <=1: print("Monty Hall Problem Simulator") print("Usage: monty num_tests") sys.exit(1) if len(sys.argv) >=3: print("Too many arguments.") print("Usage: monty num_tests") sys.exit(1) #test if argument is int num=sys.argv[1] try: num=int(num) except ValueError: print("Number of tests is not an integer.") print("Usage: monty num_tests") sys.exit(3) #count variables stay_count=0 switch_count=0 for x in range(0,num): #create array with 3 doors and shuffle the order #we will assume doors[0] contains the car and #doors[1] and [2] contain goats doors=[1,2,3] random.shuffle(doors) #create user guess of door 1-3 inclusive door_guess=random.randint(1,3) #Monty will now reveal a door that is not the user's guess #nor the car. We can assume doors[1] or doors[2] will be revealed. #From implementation view, either the user's guess was initally right # and should stay or the user should switch their guess. #if the user guesses the door held in doors[0], stay #otherwise switch doors if door_guess == doors[0]: stay_count+=1 else: switch_count+=1 #print("switch",switch_count) #print("stay",stay_count) print("Switch would win %.2f percent of experiments"%(switch_count/num)) print("Stay would win %.2f percent of experiments"%(stay_count/num)) sys.exit(0)
"""An exercise in remainders and boolean logic.""" __author__ = "730529273" choice: int = int(input("Enter ana int: ")) leftover_one: int = choice % 2 leftover_two: int = choice % 7 leftover_three: int = choice % 14 if leftover_three == 0: print("TAR HEELS") else: if leftover_one == 0: print("TAR") else: if leftover_two == 0: print("HEELS") else: print("CAROLINA")
"""List utility functions.""" __author__ = "730529273" def all(numbers: list[int], b: int) -> bool: """Iff b is found in the numbers, return true.""" # Move through each int within the list. i: int = 0 if len(numbers) == 0: return False while i < len(numbers): item: int = numbers[i] if item != b: return False i += 1 return True def is_equal(list_1: list[int], list_2: list[int]) -> bool: """Given two lists of int values, return True if every element at every index is equal in both lists.""" if list_1 == list_2: return True return False def max(a: list[int]) -> int: """This is a function which returns the maximun of a list.""" if len(a) == 0: raise ValueError("max() arg is an empty List") else: counter: int = 0 maximun: int = a[0] while counter < len(a) - 1: if maximun <= a[counter + 1]: maximun = a[counter + 1] counter += 1 return maximun print(all([1, 2, 3], 1)) print(all([1, 1, 1], 2)) print(all([1, 2, 3], 2)) print(is_equal([1, 2, 3], [1, 2, 3])) print(is_equal([1, 1, 0], [1, 0, 1])) print(is_equal([], [1, 2, 3])) print(max([1, 2, 3]))
# integer x = 100 print type(x) if x >= 100: print "That's a big number!" else: print "That's a small number" # string y = 'hello world' print type(y) if y >= 50: print 'Long sentence' else: print 'Short setence' z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] print type(z) if len(z) >= 10: print 'Big List!' else: print 'Small List!'
class Store(object): def __init__(self, product, location, owner): self.product = product self.location = location self.owner = owner def add_product(self, product): self.product.append(product) def remove_product(self, product): self.product.remove(product) def inventory(self): print self.product a = Store(product=['apples', 'strawberries', 'pineappe'], location='Mexico', owner='Noel') a.add_product('grapes') a.inventory() a.remove_product('grapes') a.inventory() a.remove_product('apples')
black = ['* * * *'] red = [' * * * *'] # print black # print red for new in range(1, 9): if new % 2 == 1: print black else: print ' ', black star1 = '* * * *' star2 = ' * * * *' for new in range(0, 8): if new % 2 == 1: print star1 else: print star2
grad = float(input("점수 : ")) toelc = int(input("토익 : ")) if toelc >= 700 and grad >= 4.0: print('면접대상자') elif toelc >= 700 and grad >= 3.5: print('서류전형대상자') elif toelc >= 700 and grad >= 3.0: print('필기시험대상자') else: print('지원불가')
h = int(input('근무시간')) p = int(input('시간당 임금')) if h > 40: over = h - 40 total = p * 40 + over * p * 1.5 else: total = h * p print(f'total{total}')
""" В некоторой школе занятия начинаются в 9:00. Продолжительность урока — 45 минут, после 1-го, 3-го, 5-го и т.д. уроков перемена 5 минут, а после 2-го, 4-го, 6-го и т.д. — 15 минут. Дан номер урока (число от 1 до 10). Определите, когда заканчивается указанный урок. Выведите два целых числа: время окончания урока в часах и минутах. """ # nice input # print("Enter the number of lesson") lesson_number = int(input()) hours = 9 minutes = lesson_number * 45 + int(lesson_number / 2) * 5 + int((lesson_number - 1) / 2) * 15 hours += int(minutes / 60) minutes = minutes % 60 # nice output # print("Lesson ends at {:0>2}:{:0>2}".format(hours, minutes)) print(hours) print(minutes)
import Card import random import Player suits = ["Clubs", "Diamonds", "Hearts", "Spades"] class Game: def __init__(self, startingBalance): self.startingBalance = startingBalance self.deck = list() self.players = list() self.button = 0; self.board = list() Game.addCards(self) Game.shuffleCards(self) def deal(self): # burn one at the start self.deck.pop() # deal two to each player start = self.button for x in range(2): for i in range(len(self.players)): if start >= len(self.players): start -= len(self.players) self.players[start].hand.append(self.deck.pop()) start += 1 self.button += 1 if self.button >= len(self.players): self.button = 0 # burn one before the flop self.deck.pop() for x in range(3): self.board.append(self.deck.pop()) # burn one before the turn self.deck.pop() self.board.append(self.deck.pop()) # burn one before the river self.board.append(self.deck.pop()) def addPlayer(self, name): if len(self.players) < 22: self.players.append(Player.Player(name, self.startingBalance)) else: print("Max number of players reached : 22") def shufflePlayers(self): Game.shuffle(self.players) i = 0; for p in self.players: p.seatOrder = i i += 1 def addCards(self): for suit in suits: for x in range(13): self.deck.append(Card.Card(x, suit)) def shuffleCards(self): Game.shuffle(self,self.deck) def shuffle(self,list): i = 0 for c in list: rand = random.randint(0, len(list) - 1) temp = c list[i] = list[rand] list[rand] = temp i += 1
''' 产生一个0~500的一个随机数,给5000金币 -- 输入的数字大于随机数输出大了-500 -- 输入的数字小于随机数输出小了-500 -- 输入的数字正确输出“恭喜您猜对了”+3000金币 系统在输入15锁定。系统没有金币系统锁定 ''' #产生一个随机数 import random num = random.randint(0,500) kj = 5000 #开始金币 # i = 0 print(num) while i < 15: #判断次数 number = input("请输入一个数字") #键盘输入 number = int(number) #将字符创改为整数 if number > num: #判断 kj= (kj - 400) print("大了,您还有金币为:",kj) elif number < num: kj= (kj - 300) print("小了,您还有金币为:",kj) else: kj= (kj + 3000) print("恭喜您猜对了,随机数字是:",num,"您当前金币为:",kj) print(kj) break if kj <= 0: print("您没有金币了") break #跳出循环 i= i + 1 # print("您已经输入了15次请重新开始",i)
import unittest import random class TestMethods(unittest.TestCase): def test_No_Players(self): TeamOne = [] ChoicesOne = [] TeamTwo = [] ChoicesTwo = [] Team_One_Index = 0 Team_Two_Index = 0 game_over = True if game_over == True: computer_One_choice = 4 computer_Two_choice = 4 else: computer_One_choice = random.randint(1, 3) computer_Two_choice = random.randint(1, 3) if Team_One_Index != 0: for y in range(len(TeamOne)): TeamOne.reverse() name_of_player = TeamOne.pop() print(name_of_player + '. What do you want to play?') the_Choice = int(input('Reminder: 1 = Rock, 2 = Paper, 3 = Scissors \nYour choice: ')) if the_Choice != 1 or the_Choice != 2 or the_Choice != 3: ChoicesOne.append(random.randint(1, 3)) else: ChoicesOne.append(the_Choice) Final_Team_One_Choice = ChoicesOne[random.randint(0, (Team_One_Index - 1))] else: Final_Team_One_Choice = computer_One_choice if Team_Two_Index != 0: for w in range(len(TeamTwo)): TeamTwo.reverse() name_of_player = TeamTwo.pop() print(name_of_player + '. What do you want to play?') the_Choice = int(input('Reminder: 1 = Rock, 2 = Paper, 3 = Scissors \nYour choice: ')) if the_Choice != 1 or the_Choice != 2 or the_Choice != 3: ChoicesTwo.append(random.randint(1, 3)) else: ChoicesTwo.append(the_Choice) Final_Team_Two_Choice = ChoicesTwo[random.randint(0, (Team_Two_Index - 1))] else: Final_Team_Two_Choice = computer_Two_choice if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') assert Final_Team_One_Choice == 4 and Final_Team_Two_Choice == 4 def test_Ending_One(self): Final_Team_One_Choice = 1 Final_Team_Two_Choice = 1 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 3 def test_Ending_One_Part_Two(self): Final_Team_One_Choice = 2 Final_Team_Two_Choice = 2 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 3 def test_Ending_One_Part_Three(self): Final_Team_One_Choice = 3 Final_Team_Two_Choice = 3 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 3 def test_Ending_One_Part_Four(self): Final_Team_One_Choice = 4 Final_Team_Two_Choice = 4 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 3 def test_Ending_Two(self): Final_Team_One_Choice = 1 Final_Team_Two_Choice = 2 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 2 def test_Ending_Two_Part_Two(self): Final_Team_One_Choice = 2 Final_Team_Two_Choice = 3 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 2 def test_Ending_Two_Part_Three(self): Final_Team_One_Choice = 3 Final_Team_Two_Choice = 1 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 2 def test_Ending_Three(self): Final_Team_One_Choice = 1 Final_Team_Two_Choice = 4 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 2 def test_Ending_Three_Part_Two(self): Final_Team_One_Choice = 2 Final_Team_Two_Choice = 4 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 2 def test_Ending_Three_Part_Three(self): Final_Team_One_Choice = 3 Final_Team_Two_Choice = 4 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 2 def test_Ending_Four(self): Final_Team_One_Choice = 1 Final_Team_Two_Choice = 3 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 1 def test_Ending_Four_Part_Two(self): Final_Team_One_Choice = 2 Final_Team_Two_Choice = 1 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 1 def test_Ending_Four_Part_Three(self): Final_Team_One_Choice = 3 Final_Team_Two_Choice = 2 if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') winner = 3 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') winner = 2 if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') winner = 2 if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and \ Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') winner = 1 if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') winner = 1 assert winner == 1
import random Rock = '1' Paper = '2' Scissors = '3' Gun = '4' TeamOne = [] ChoicesOne = [] TeamTwo = [] ChoicesTwo = [] Team_One_Index = 0 Team_Two_Index = 0 game_over = False def do_stuff(): print('Welcome to Rock, Paper, Scissors! The game of all kids to decide on something. \n(Psst if it\'s a draw the start the program again! ;D)\nSo how to play. Well, it\'s simple. Pick 1 for Rock, 2 for Paper and 3 for Scissors. \nSo Rock beats Scissors. Scissors cuts Paper and Paper covers Rock. Got it Lets play') number_of_players=int(input('Please input the number of players: ')) if number_of_players <= 0: game_over = True else: for x in range(number_of_players): name_of_player = raw_input('Please enter your name: ') team_player_wants=int(input('What team would you like to join? \n1 or 2? \n Hint: If you do not put either 1 or 2, something bad happens. ')) if team_player_wants == 1: TeamOne.append(name_of_player) global Team_One_Index Team_One_Index += 1 if team_player_wants == 2: TeamTwo.append(name_of_player) global Team_Two_Index Team_Two_Index += 1 pass if team_player_wants != 1 and team_player_wants != 2: game_over = True pass def play_game(): if game_over == True: computer_One_choice = 4 computer_Two_choice = 4 else: computer_One_choice = random.randint(1,3) computer_Two_choice = random.randint(1,3) if Team_One_Index != 0: for y in range(len(TeamOne)): TeamOne.reverse() name_of_player = TeamOne.pop() print(name_of_player + '. What do you want to play?') the_Choice = int(input('Reminder: 1 = Rock, 2 = Paper, 3 = Scissors \nYour choice: ')) if the_Choice != 1 or the_Choice != 2 or the_Choice != 3: ChoicesOne.append(random.randint(1,3)) else: ChoicesOne.append(the_Choice) Final_Team_One_Choice = ChoicesOne[random.randint(0,(Team_One_Index-1))] else: Final_Team_One_Choice = computer_One_choice if Team_Two_Index != 0: for w in range(len(TeamTwo)): TeamTwo.reverse() name_of_player = TeamTwo.pop() print(name_of_player + '. What do you want to play?') the_Choice = int(input('Reminder: 1 = Rock, 2 = Paper, 3 = Scissors \nYour choice: ')) if the_Choice != 1 or the_Choice != 2 or the_Choice != 3: ChoicesTwo.append(random.randint(1,3)) else: ChoicesTwo.append(the_Choice) Final_Team_Two_Choice = ChoicesTwo[random.randint(0,(Team_Two_Index-1))] else: Final_Team_Two_Choice = computer_Two_choice if Final_Team_One_Choice == Final_Team_Two_Choice: print('Congrats. Both teams lose and win because it is a tie.') if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 2 or Final_Team_One_Choice == 2 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 1: print('Congrats Team Two!') if Final_Team_One_Choice != 4 and Final_Team_Two_Choice == 4: print('Congrats Team Two! You shot Team One with a Gun. Gun always wins!') if Final_Team_One_Choice == 1 and Final_Team_Two_Choice == 3 or Final_Team_One_Choice == 2 and Final_Team_Two_Choice == 1 or Final_Team_One_Choice == 3 and Final_Team_Two_Choice == 2: print('Congrats Team One!') if Final_Team_One_Choice == 4 and Final_Team_Two_Choice != 4: print('Congrats Team One! You shot Team Two with a Gun. Gun always wins!') do_stuff() play_game()
import cv2 import numpy as np puppy_img = cv2.imread("Computer-Vision-with-Python//DATA//dog_backpack.jpg", cv2.COLOR_BGR2RGB) copyright_img = cv2.imread("Computer-Vision-with-Python//DATA//watermark_no_copy.png", cv2.COLOR_BGR2RGB) print("Puppy image size = ",puppy_img.shape) print("Copyright image size = ",copyright_img.shape) def same_size_img_blend(img1, img2): ''' this functions blends two images which are of the same size and returns blended img ''' reshaped_img1 = cv2.resize(img1, (934, 1280)) reshaped_img2 = cv2.resize(img2, (934, 1280)) return cv2.addWeighted(reshaped_img1, 0.9, reshaped_img2, 0.1, 0) def diff_size_img_overlay(img1, img2): ''' this func replaces a certain portion of larger img with entire of smaller img img1 is bigger, img2 is smaller ''' reshaped_img2 = cv2.resize(img2, (934, 340)) y_start, x_start = 0, 0 y_end, x_end = reshaped_img2.shape[0], reshaped_img2.shape[1] print(y_end, x_end) merged_img = img1.copy() merged_img[y_start:y_end, x_start:x_end] = reshaped_img2 merged_img = cv2.resize(merged_img, (0,0), merged_img, 0.5, 0.5) return merged_img def diff_size_img_blend(img1, img2): ''' this function adds a watermark at desired location ''' reshaped_img1 = cv2.resize(img1, (0, 0), img1, 0.5, 0.5) reshaped_img2 = cv2.resize(img2, (300, 300)) roi = reshaped_img1[ reshaped_img1.shape[0]-300:reshaped_img1.shape[0] , reshaped_img1.shape[1]-300:reshaped_img1.shape[1]] mask = cv2.cvtColor(reshaped_img2, cv2.COLOR_RGB2GRAY) inv_mask = cv2.bitwise_not(mask) #white_bg = np.full(reshaped_img2.shape, 255, np.uint8) #final_mask = cv2.bitwise_or(white_bg, white_bg, mask=inv_mask) fg = cv2.bitwise_or(reshaped_img2, reshaped_img2, mask=inv_mask) final_roi = cv2.bitwise_or(roi, fg) reshaped_img1[reshaped_img1.shape[0]-300:reshaped_img1.shape[0] , reshaped_img1.shape[1]-300:reshaped_img1.shape[1]] = final_roi return reshaped_img1 blended_img = diff_size_img_blend(puppy_img, copyright_img) while True: #cv2.imshow("My Doggo", reshaped_puppy_img) #cv2.imshow("My Img", reshaped_copyright_img) cv2.imshow("Blended Img", blended_img) if cv2.waitKey(1) & 0xFF == 27: break cv2.destroyAllWindows() ''' create ROI create mask convert img to grey invert grey img -> this is mask but has only 1 channel '''
import random from articles import articles # Add a key-value pair to each article. for article in articles['response']['results']: article['view'] = 0 # print(article) def read_article(): # Randomly selects an article and increases the articles "views" by one each time it's selected. num_of_articles = len(articles['response']['results']) # 10 random_num = random.randint(1,num_of_articles-1) # print(random_num) # print(articles['response']['results'][random_num]) articles['response']['results'][random_num]['view'] += 1 # print(articles['response']['results'][random_num]['view']) def display_views(): # Iterates through the articles and displays their titles and view counts. for article in articles['response']['results']: print(article['webTitle']) print(f"This article has been read {article['view']} times.\n") read_article() read_article() read_article() read_article() read_article() display_views()
#!/usr/local/bin/python # -*- coding: utf-8 -*- capitales_dict = { "Aguascalientes" : "Aguascalientes", "Baja California" : "Mexicali", "Baja California Sur" : "La Paz", "Campeche" : "Campeche", "Chihuahua" : "Chihuahua", "Chiapas" : "Tuxtla Gutiérrez", "Coahuila" : "Saltillo", "Colima" : "Colima", "Durango" : "Victoria", "Guanajuato" : "Guanajuato", "Guerrero" : "Chilpancingo", "Hidalgo" : "Pachuca", "Jalisco" : "Guadalajara", "México" : "Toluca", "Michoacán" : "Morelia", "Morelos" : "Cuernavaca", "Nayarit" : "Tepic", "Nuevo León" : "Monterrey", "Oaxaca" : "Oaxaca", "Puebla" : "Puebla", "Querétaro" : "Querétaro", "Quintana Roo" : "Chetumal", "San Luis Potosí" : "San Luis Potosí", "Sinaloa" : "Culiacán", "Sonora" : "Hermosillo", "Tabasco" : "Villahermosa", "Tamaulipas" : "Ciudad Victoria", "Tlaxcala" : "Tlaxcala", "Veracruz" : "Xalapa", "Yucatán" : "Mérida", "Zacatecas" : "Zacatecas" } import random estados = list(capitales_dict.keys()) #for i in [1,2,3,4,5]: while True: estado = random.choice(estados) capital = capitales_dict[estado] respuesta = input("Cual es la capital de " + estado + "? ") if respuesta == "salir": break elif respuesta == capital: print("Respuesta correcta! " + "\N{Sports Medal}") else: print("Respuesta incorrecta. La capital de " + estado + " es " + capital + "\N{grinning face}" + ".") print("Adios")
a = b = 2 # A esto se le llama "asignación encadenada". Asigna el valor 2 a las variables "a" y "b". print("a = " + str(a)) # Explicaremos la expresion str(a) despues en el curso. por ahora es utilizado para convertir la variable a en una cadena. print("b = " + str(b)) greetings = "saludos" print("saludos = " + str(greetings)) greetings = another value print("saludos = " + str(greetings))
import os import time import socket import threading import tkinter as tk import tkinter.messagebox import tkinter.scrolledtext as sct client = socket.socket() # Client's socket object for, well, being a client ui = tk.Tk() # variable for holding and performing GUI operations rowCount = 0 # variable to hold the current row - used in inital setup name = "" # variable to hold the username the client has entered, used in the inital setup initialFrame = tk.Frame(ui) # variable to hold the inital setup GUI components in a frame chatFrame = tk.Frame(ui, bg = "white") # variable to hold the chat GUI components in a frame chatText = sct.ScrolledText(chatFrame, wrap = tk.WORD, bd = 2) # variable for printing text to the GUI window (chatFrame) with vertical scrollbars ansEntry = tk.Entry(initialFrame, width = 30) # variable for the text box that the client enters their name in during the inital setup sendTextBox = tk.Text(chatFrame, height = 5, wrap = tk.WORD, bd = 2) # variable to hold the client's text box for sending messages to the server def join_server(h = "localhost", p = 8888): "Connect client to server" global rowCount tk.Label(initialFrame, text = "Connecting to server...").grid(row = rowCount) rowCount+=1 try: host = h post = p client.connect((host, post)); tk.Label(initialFrame, text = "Connected!").grid(row = rowCount) rowCount+=1 except socket.error as err: tk.Label(initialFrame, text = "Failed to connect to server.\n\nExiting...").grid(row = rowCount) rowCount+=1 time.sleep(2) quit() else: send_username() def send_username(): "Complete username registration and then enter chat room" global rowCount, name try: while True: getName = client.recv(1024) # read server message for entering username getName = getName.decode() tk.Label(initialFrame, text = getName).grid(row = rowCount) ansEntry.grid(row = rowCount, column = 1) ansEntry.bind("<Return>", getusername_label) while (name == ""): # will be updated when user clicks send button time.sleep(1) client.send(str.encode(name)) # send server the username entered valid = client.recv(1024) # check if server approves of username valid = valid.decode() taken = "Username " + name + " is already taken." notTaken = name + " has entered the chat room." if valid == taken: tk.messagebox.showerror("Error", taken + "\nTry a different username.") name = "" continue elif valid == notTaken: initialFrame.destroy() make_chatGUI() printUI(notTaken) receive_message() break except socket.error as err: tk.Label(initialFrame, text = "Lost connection with server.\n\nExiting...").grid(row = rowCount + 1) time.sleep(2) quit() def receive_message(): "Listen for messages from the server and display them." try: while True: text = client.recv(1024) text = text.decode() printUI(text) except socket.error as err: printUI("Lost connection with server.\nExiting...") time.sleep(2) quit() def send_message(event = None, textBox = sendTextBox): "Send messages to the server" try: text = get_sendTextBox(event, textBox) text = str.encode(text) if text != "": client.send(text) return "break" # prevents <Return> from inserting a new line so cursor in text box returns the first line rather than second after hitting send except socket.error as err: printUI("Lost connection with server.\nExiting...") time.sleep(2) quit() def printUI(text): "Print text onto the GUI widget, chatText (equivalent to print() for the chatText widget)" chatText.configure(state=tk.NORMAL) chatText.insert(tk.INSERT, text + "\n") chatText.see(tk.END) # focus on the last message printed (autoscroll) chatText.configure(state=tk.DISABLED) def quit(): "Close the client's connection and exit the program" client.close() ui.destroy() os._exit(0) def getusername_label(event): "Return the username the client entered during the inital setup process" global name name = ansEntry.get() ansEntry.delete(0, tk.END) return name def get_sendTextBox(event, textBox = sendTextBox): "Return the text the client entered in the sendTextBox widget (what the client wants to send to server)" text = textBox.get("1.0", "end-1c") # end-1c: end means read to end of text, but this adds newline. -1c mean remove 1 character textBox.delete("1.0", "end-1c") return text def make_chatGUI(): "Alter and make new GUI component after the client has entered the chat room" # update main GUI window ui.title(name + " - Client.py") ui.minsize(width = 450, height = 200) ui.configure(bg = "white") ui.grid_rowconfigure(0, weight = 1) # will allow GUI components in window to expand ui.grid_columnconfigure(0, weight = 1) # will allow GUI components in window to expand chatFrame.grid_rowconfigure(0, weight = 1) # will allow GUI components in frame to expand chatFrame.grid_columnconfigure(0, weight = 1) # will allow GUI components in frame to expand chatFrame.grid(sticky = tk.N + tk.S + tk.E + tk.W) # will allow GUI components in frame to expand in all directions # make GUI component for the chat log chatText.grid(sticky = tk.N + tk.S + tk.E + tk.W) # make the chat text log read only # make GUI component for the client to send messages sendTextBox.grid(row = 1, column = 0, sticky = tk.W) sendTextBox.bind("<Return>", send_message) sendTextBox.grid(sticky = tk.N + tk.S + tk.E + tk.W) # expand in all directions if resized # make a GUI button for the client to send messages in text box sendButton = tk.Button(chatFrame, text = "Send", width = 5, height = 1, command = send_message, bg = "#2d89ef", fg = "white") sendButton.grid(row = 2, column = 0, sticky = tk.N + tk.S + tk.E + tk.W) # expand button in center button def start_GUI(): "Start the program with it's GUI elements" ui.title("Client.py") ui.protocol("WM_DELETE_WINDOW", quit) initialFrame.grid() rt = threading.Thread(target = join_server) # make a new thread for handling the client communicating with the server rt.start() ui.mainloop() start_GUI() """ Active Threads: - Main/GUI thread will handle sending messages to server - A new thread (rt) is made for joining and receiving message from server """
''' This is the NN project applied to MNIST. The initial goal is to practice NN concepts with the MNIST lib of images. First test will be composed of simple backpropagation machines. The algorithm for this simple, backpropagation, perceptron based NN is as follows: * Retrieve input files (MNIST in this case); * process the images into an input array; * Add a cell to the input array, totaling 1, in order to represent the bias; * Establish the number of initial hidden layers; // In this case we are starting with 1; * Based on the number of Hidden layers, set up the weight array; * Weight array should be something of the input, and the respective number of hidden layers; // This is for iteration through the array. * Randomize all Ws. // Now establishing an algo for 1 Hidden Layer specific case: * Set up 10 neurons; // each representing a number; * set up a W(sizeOfInputIMGs+1,1); // the +1 is for the bias; * Input Transposed times W + Bias; * Whichever Neuron has the highest signal wins; // Training the network; // Produce the back propagation; * Start running trainng Data samples; * Compare the result of the winning neuron with the actual result; * Calculate error; * Propagate the error back through the network in order to adjust; // Check respective error methods * Adjust Weights; * Run next sample; * Do this until overall testing error reaches a very low number (acceptable error); ''' # Must remember to normalize the values; # for example the input: X=X/np.amax(X,axis=0); # sigmoid function is: y=1/(1+np.e(-z)); # sigmoid prime: np.exp(-z)/((1+np.exp(-z))**2); import numpy as np; #import numba; from Neuron import Neuron; from threading import Thread; #import multiprocessing; #from scipy import optimize; class NeuralNetwork(object): # This is the constructor; def __init__(self,numberOfHiddenLayers=1,numberOfNeuronsPerLayer=10): print("NeuralNetwork Constructor called;"); self.neuronN=[]; self.numberOfNeuronsPerLayer=numberOfNeuronsPerLayer; for _ in range(self.numberOfNeuronsPerLayer): self.neuronN.append(Neuron()); print(" number of neuron: %d"%len(self.neuronN)); def feedForward(self,X): # Must feed information forward; self.Xn=X; t=[]; for r in range(self.numberOfNeuronsPerLayer): t.append(Thread(target=self.processFeed, name=r,args=(r,))); #t.append(multiprocessing.Process(target=self.processFeed, name=r,args=(r,))); t[r].start(); for item in t: item.join(); return self.neuronN; def processFeed(self,k): self.neuronN[k].sumInputs(self.Xn); self.neuronN[k].sigmoid(); #print("processed thread %d"%k); return 0; def feedBack (self,error): # will feed the error; return 0;
#!/usr/bin/python3 # 《Python语言程序设计》程序清单7-检查点练习 # Programed List 7-Checkpoint Programme # 第七章 检查点练习程序 7.1~7.18 # 7.1 # 7.2 # 7.3 # 7.4 # 7.5 # 7.6 # 7.7 # 7.8 # 7.9 # class A: # def __init__(self, i): # def __init__(self, i = 0): # self.i = i # def main(): # a = A() # print(a.i) # main() # Call the main function # 7.10 # class A: # # Construct an object of the class # def A(self): # radius = 3 # class A: # # Construct an object of the class # def __init__(self): # radius = 3 # def setRadius(radius): # self.radius = radius # 7.11 # class Count: # def __init__(self, count = 0): # self.count = count # # def main(): # c = Count() # times = 0 # for i in range(100): # increment(c, times) # print("count is", c.count) # print("times is", times) # # def increment(c, times): # c.count += 1 # times += 1 # # main() # Call the main function # 7.12 # class Count: # def __init__(self, count = 0): # self.count = count # # def main(): # c = Count() # n = 1 # m(c, n) # # print("count is", c.count) # print("n is", n) # # def m(c, n): # c = Count(5) # n = 3 # # main() # Call the main function # 7.13 # class A: # def __init__(self, i): # self.__i = i # def main(): # a = A(5) # print(a.__i) # main() # Call the main function # 修改后: # class A: # def __init__(self, i): # self.__i = i # def getI(self): # return self.__i # def main(): # a = A(5) # print(a.getI()) # main() # Call the main function # 7.14 # def main(): # a = A() # a.print() # class A: # def __init__(self, newS = "Welcome"): # self.__s = newS # def print(self): # print(self.__s) # main() # Call the main function # 7.15 # class A: # def __init__(self, on): # self.__on = not on # def main(): # a = A(False) # print(a.on) # main() # Call the main function # 修改后: # class A: # def __init__(self, on): # self.__on = not on # def getOn(self): # return self.__on # def main(): # a = A(False) # print(a.getOn()) # main() # Call the main function # 7.16 # 7.17 # 7.18
#!/usr/bin/python3 # 《Python语言程序设计》程序清单1-5 # Programed List 1-5 # Draw OlympicSymbol import turtle # Import turtle module turtle.color("blue") turtle.penup() turtle.goto(-110, -25) turtle.pendown() turtle.circle(45) turtle.color("black") turtle.penup() turtle.goto(0, -25) turtle.pendown() turtle.circle(45) turtle.color("red") turtle.penup() turtle.goto(110, -25) turtle.pendown() turtle.circle(45) turtle.color("yellow") turtle.penup() turtle.goto(-55, -75) turtle.pendown() turtle.circle(45) turtle.color("green") turtle.penup() turtle.goto(55, -75) turtle.pendown() turtle.circle(45) turtle.done()
#!/usr/bin/python3 # 《Python语言程序设计》程序清单2-9 # Programed List 2-9 # Compute distance between the two points # Enter the first point with two float values x1, y1 = eval(input("Enter x1 and y1 for Point 1: ")) # Enter the second point with two float values x2, y2 = eval(input("Enter x2 and y2 for Point 2: ")) # Compute the distance distance = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5 print("The distance between the two points is ", distance)
#!/usr/bin/python3 # 《Python语言程序设计》程序清单6-1 # Programed List 6-1 # 返回两个数中较大的数 # Return the max of two numbers def max(num1, num2): if num1 > num2: result = num1 else: result = num2 return result def main(): i = 5 j = 2 k = max(i, j) # Call the max function print(i, "与", j, "中最大的是", k) main() # Call the main function
# This is NOT the correct answer for this assessment. # You MUST modify this code and make it satisfy the specification. # Do NOT modify anything inside the quotation marks "". score1 = 95 score2 = 90 score3 = 70 score4 = 50 grade1 = "A+" grade4 = "A" grade3 = "B" grade7 = "C" grade5 = "Fail" course1 = "DTEC101" mn = 0 mx = 100 mid = 50 name1 = input("Please enter your first name: ") name2 = input("{}, please enter your last name: ".format(name1)) bigproblem = True while bigproblem == True: number = input("{}, please enter your mark for assessment 1: ".format(name1)) if (number == mx): print("Sorry {}, {} was too low. Please re-enter the mark.".format(name1, number)) print("Sorry {}, {} was too high. Please re-enter the mark.".format(name1, number)) bigproblem = False if number == score1: grade = grade1 elif number == score3: grade = grade7 else: if number == score3: grade = grade3 if number == score4: grade = grade4 else: grade = grade5 if number == mx: print("Congratulations {} {}, you have passed {} with a grade of {}.".format(course1, name2, grade, name1)) print("Unfortunately {} {}, you have not passed {}. You received the grade {}.".format(course1, name2, grade, name1))
number_1 = int(raw_input("please enter number: ")) number_2 = int(raw_input("please enter another number: ")) print number_1 * number_2 print number_2 - number_1 print number_1 + number_2 print number_1 / number_2 print number_1 % number_2
# -*- coding: utf-8 -*- from bitarray import bitarray class Protein: """ Representing a protein instance in the simulated cell. Contains the state of the protein in it, a pointer to the protein-type and the neccesary methods for protein interaction. """ def __init__(self, name, protein_pointer): """ Initialize a protein instance with its name, the information to the protein type and a state without any other proteins bound. """ self.name = name self.index = protein_pointer.index self.interactions = protein_pointer.interactions self.map_interactor_domains = protein_pointer.map_interactor_domains self.domains = protein_pointer.domains self.state = bitarray(len(self.index)) self.state.setall(False) self.number_of_free_domains = len(self.domains) def get_possible_interactors(self): """ Return a list of the possible interactors of this protein. """ return list(self.map_interactor_domains.keys()) def get_domains_to_interactor(self, interactor): """ Return the domains at which the given $interactor can interact with this protein. """ return self.map_interactor_domains[interactor] def is_interacting(self, protein, domain): """ Test if this protein instance is already interacting with $protein at $domain. """ if not (protein, domain) in self.index: return False i = self.index[(protein, domain)] return self.state[i] def is_association_possible(self, protein, domain): """ Test if this protein can associate with $protein at $domain. """ if not (protein, domain) in self.index: return False s = self.state i = self.index[(protein, domain)] # each clause contains two bitarrays: p=positive and n=negative for p, n in self.interactions[i]: # all bits from positive clauses must be set and no bit from a negative is allowed if ((p&s) == p) and ((n&(~s)) == n): return True return False def associate(self, protein, domain): """ Perfom an association beteween this protein and $protein at $domain. In the updated state the bit of index(protein,domain) is set to 1. """ i = self.index[(protein, domain)] assert not self.state[i], "For a association the proteins should not be interacting before." self.state[i] = True self.number_of_free_domains -= 1 return def dissociate(self, protein, domain): """ Perfom an dissociation beteween of the interaction this protein and $protein at $domain. In the updated state the bit of index(protein,domain) is set to 0. """ i = self.index[(protein, domain)] assert self.state[i], "For a dissociation the proteins must be interacting first." self.state[i] = False self.number_of_free_domains += 1 return
# EJERCICIO 1 print("hola Mundo") # EJERCICIO 2 saludo = "hola Mundo" print(saludo) # EJERCICIO 3 nombre = input("Cual es tu nombre?") print("hola" , nombre) # EJERCICIO 4 resultado = ((3+2)/(2*5))**2 print(resultado) # EJERCICIO 5 print("Calculadora de pago de un dia de trabajo") horas = int(input("Proporcione el numero de horas trabajadas por dia: ")) pago = int(input("Proporcione el precio de la hora de trabajo: ")) print("El pago por dia es: " ,horas * pago , "pesos") # EJERCICIO 6 print("Sumador de numeros de 1 a n numero que usted elija") n = int(input("Ingrese un numero ")) sum = 0 if n>0: sum = (n*(n+1))/2 print(sum) else: print("El numero tiene que ser positivo") # EJERCICIO 7 print("Sistema para calcular IMC") peso = float(input("ingrese su peso en kg: ")) altura = float(input("ingrese su altura en metros: ")) imc = peso / altura**2 imc = round(imc,2) print("Tu índice de masa corporal es" , imc) # EJERCICIO 8 print("Sistema para calcular el resto y cociente de una division de dos numeros enteros") n = int(input("ingrese un numero entero ")) m = int(input("ingrese otro numero entero ")) c = n//m r = n%m print("El cociente de n/m es c: " , c , "y el resto es r:" , r) # EJERCICIO 9 print("Sistema para calcular inversiones ") cantidad = float(input("Cantidad a invertir ")) interesa = float(input("Interes anual ")) años = float(input("Cantidad de años de la inversion ")) print ("La capital obtenido es: " ,round(cantidad*((interesa/100)+1)*años , 2) , "pesos") # EJERCICIO 10 nombre = input("Ingrese su nombre: ") n = int(input("Ingrese un numero n de veces que quiera que se repita su nombre: ")) print(nombre * n)
# Escribir un programa que almacene las materias de un curso (por ejemplo Matemáticas, # Física, Química, Historia y Lengua) en una lista, pregunte al usuario la nota que ha sacado en # cada materia, y después las muestre por pantalla con el mensaje En <materia> has sacado # <nota> donde <materia> es cada una de las asignaturas de la lista y <nota> cada una de las # correspondientes notas introducidas por el usuario. materias = ['Matemáticas', 'Física', 'Química', 'Historia' , 'Lengua'] notas = [] for mat in materias: nota = int(input(f'Cual es la nota que saco en la siguiente materia {mat}: ')) notas.append(nota) for i in range(len(materias)): print(f'En {materias[i]} has sacado {notas[i]}')
# Escribir un programa que almacene las materias de un curso (por ejemplo Matemáticas, # Física, Química, Historia y Lengua) en una lista, pregunte al usuario la nota que ha sacado en # cada materia y elimine de la lista las materias aprobadas. Al final el programa debe mostrar # por pantalla las materias que el usuario tiene que recursar. materias = ['Matemáticas', 'Física', 'Química', 'Historia' , 'Lengua'] notas = [] mate = [] notasf = [] for mat in materias: nota = int(input(f'Cual es la nota que saco en la siguiente materia {mat}: ')) notas.append(nota) for i in range(len(materias)): if notas[i] < 4: mate.append(materias[i]) notasf.append(notas[i]) for i in range(len(mate)): print(f'En {mate[i]} has sacado {notasf[i]}')
# Escribir una función que calcule el área de un círculo y otra que calcule el volumen de un # cilindro usando la primera función. def area(radio , h=1 ): areaCirculo = 3.14*(radio**2)*h return areaCirculo print(area(5 , 5))
frase = input("Ingrese una frase: ") vocal = input("ingrese una vocal: ") print(frase.replace(vocal , vocal.upper()))
# Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el # número de años, y muestre por pantalla el capital obtenido en la inversión cada año que dura # la inversión. cantidad = int(input('Ingrese la suma a invertir: ')) interes = int(input('Cual es el interes anual: ')) anos = int(input('Ingrese los anos que dura la inversion: ')) capital = cantidad for i in range(anos): capital = capital + (capital * (interes/100)) print(f'El ano {i+1} el capital obtenido sera {round(capital , 2)} ')
# Escribir un programa que pida al usuario un número entero y muestre por pantalla si es par # o impar. num = int(input("Ingrese un numero: " )) if num%2 == 0: print("Es par") else: print("No es par")
month = 12 day = 24 if (month == 12): if (day == 24): print('今天是平安夜') elif (day == 25): print('今天是圣诞节') else : print('今天既不是圣诞节,也不是平安夜')
def tax_calc(amount, state): tax = 0 total = '' if state == 'WI': tax = 5.5 / 100 total += f'The subtotal is ${amount}. \n' total += f'The tax is ${tax}. \n' total += f'The total is: ${amount+tax}' return total def main(): try: amount = float(input('What is the order amount? ')) except Exception as e: return 'Amount must be a number.' state = input("What is the state? ") return tax_calc(amount, state) if __name__ == '__main__': print(main())
import numpy as np import pandas as pd from itertools import combinations INFINITY = 10e9 def take_input(): # print("Enter the number of variables in the objective function") n = int(input()) # print("Enter the number of constraints") m = int(input()) # print("Enter the coefficients of the Objective Function") c = [float(i) for i in input().split(" ")] # print("Enter the value of the constant in the objective function") d = float(input()) # print("Enter the matrix A which is the coefficient of the constraints row by row") a = [] for i in range(m): a.append([float(j) for j in input().split(" ")]) # print("Enter the constants/RHS bi for the constraint equations") b = [float(i) for i in input().split(" ")] # print("Enter the equation or in-equation type fo the variable") s = input().split(" ") return n, m, a, c, d, b, s def val_objective_function(c, x, d): return np.dot(c, x) + d def print_standard_form(n, m, a, c, d, b, s): obj_func = "" var = [] a_f = [] for i, c_prime in enumerate(c): obj_func += str(c_prime) + "x" + str(i + 1) obj_func += " + " var.append("x" + str(i + 1)) size = len(c) obj_func += str(d) print("The objective function to maximize is: \n" + obj_func) print("\nThe standard form of the constraints using slack/surplus variables is:") k = n + 1 for j, row in enumerate(a): constraint = "" for i, a_prime in enumerate(row): constraint += str(a_prime) + "x" + str(i + 1) + " + " * (i != len(row) - 1) if s[j] == "=" or s[j] == "<=": constraint += " + x" + str(k) k += 1 else: constraint += " - x" + str(k) + " + x" + str(k + 1) k += 2 constraint += " = " + str(b[j]) print(constraint) lee = n + 1 for j, row in enumerate(a): a_final = [] for alpha, a_prime in enumerate(row): a_final.append(a_prime) for alpha in range(n, lee - 1): a_final.append(0) if s[j] == "=" or s[j] == "<=": a_final.append(1) lee += 1 else: a_final.append(-1) a_final.append(1) lee += 2 while len(a_final) < k - 1: a_final.append(0) a_f.append(a_final) while len(c) < k - 1: c.append(0) return np.array(a_f), c def print_table(a_prime, c_prime, d_prime, b_prime, c, list_of_basic_variables, list_of_non_basic_variables, x): l_ = [] for basic in list_of_basic_variables: l_.append(basic + '=' + str(x[int(basic[1]) - 1])) print("Non Basic Variables = ", l_) l_ = [] for non_basic in list_of_non_basic_variables: l_.append(non_basic + '=' + str(x[int(non_basic[1]) - 1])) print("Basic Variables = ", l_) print(a_prime) print(b_prime) print(-c_prime) print("So the optimal value of objective function is:", round(val_objective_function(c, x, d_prime), 5)) def equation_solver(a, b): return np.matmul(np.linalg.inv(a),b) def linear_solver(a, b, c): li = [i for i in range(a.shape[1])] for item in combinations(li, a.shape[0]): print(item) arr = np.array([a[:, items] for items in item]).transpose() # print(arr) try: ans = equation_solver(arr, b) li_ = [] for i, items in enumerate(item): li_.append("x" + str(items+1) + " = " + str(ans[i])) print("The answer is: ", li_) x = np.zeros((a.shape[1],)) for i, items in enumerate(item): x[items] = ans[i] d = 0 print(x) print(c) print("The objective function is", val_objective_function(c, x, d)) if np.min(ans)>=0: print("The Solution is Feasible") else: print("The Solution is Not Feasible") except np.linalg.LinAlgError: li_ = [] for i, items in enumerate(item): li_.append("x" + str(items)) print("The answer after considering ", li_, " is unbounded solution") if __name__ == '__main__': # t = int(input("Enter the number of test cases:")) t = 1 M = 10000 for i in range(t): print("*" * 60) print("This is the solution to the testcase number ", i + 1) n, m, a, c, d, b, s = take_input() # Question 1 a_f, c = print_standard_form(n, m, a, c, d, b, s) print(a_f, c) # simplex method linear_solver(a_f, b, c)
""" This module contains the necessary classes for formulating a problem for the general problem solver (GPS) implemented in gps.py. In particular, a problem is composed of: 1. A goal: a set of Condition objects 2. A starting state: a set of Condition objects 3. Allowable operations: a set of Operation objects """ class Condition(object): """Represent a condition: some information about the world.""" def __init__(self, name): """ :param str name: The unique name of the condition. """ self.name = name def __eq__(self, other_condition): return self.name == other_condition.name def __repr__(self): return self.name.upper() def __str__(self): return repr(self) class Problem(object): """A problem which can be solved by the GPS.""" def __init__(self, goals, state, ops, name='unnamed'): """ :type goals: ordered collection of :class:Condition :param goals: The set of Conditions we need to achieve in order to say that we have solved this problem. :type state: collection of :class:Condition :param state: The set of conditions that currently stand. :type ops: collection of :class:Operation :param ops: The set of allowable operations we can apply in order to achieve our goal conditions. """ self.goals = goals self.state = set(state) self.ops = set(ops) self.name = name def __repr__(self): header = '{} PROBLEM'.format(self.name.upper()) rep = [header, '-' * len(header)] rep.append('\nGoal:') rep += [' {}'.format(cond) for cond in self.goals] rep.append('\nState:') rep += [' {}'.format(cond) for cond in self.state] rep.append('\nAllowable Operations:') rep += [' {}'.format(op) for op in self.ops] return '\n'.join(rep) def __str__(self): return repr(self) class Operation(object): """Some means to an end (goal).""" def __init__(self, action, preconditions=(), add_list=(), del_list=()): """ :param str action: The action performed by this operation. :type preconditions: collection of :class:Condition :param preconditions: Set of conditions which must be true in order to apply this operation. :type add_list: collection of :class:Condition :param add_list: Set of the conditions that will be added to the current state when this operation is applied. :type del_list: collection of :class:Condition :param del_list: Set of the conditions that will be deleted from the current state when this operation is applied. """ self.action = action self.preconditions = set(preconditions) self.add_list = set(add_list) self.del_list = set(del_list) def __repr__(self): return self.action.upper() def __str__(self): return repr(self) def achieves(self, goal): """Determine if the operation will achieve a particular goal. :type goal: :class:`.Condition` :param goal: The goal to check. """ return goal in self.add_list def simulate(self, state): """Simulate an execution of the operation. In other words, apply the operation to the state of the executor but don't actually perform the action that 'executes' this operation. :type state: set of :class:Condition :param state: The state to apply the operation to. """ self._apply(state) def execute(self, state): """Perform some action that 'executes' this operation. The default action simply prints 'Executing <action_name>'. This can be overriden to execute some callback or perform some set of operations. The execution of an operation will alter the state of the executor. :type state: set of :class:Condition :param state: The state to apply the operation to. """ print 'Executing {}'.format(self.action) self._apply(state) def _apply(self, state): """Apply the operation by adding all conditions in its add-list and removing all in its delete-list. """ state.difference_update(self.del_list) state.update(self.add_list)
def sum_of_digits(n): print(sum(int(i) for i in str(2 ** n))) sum_of_digits(1000)
def fact(n): fact = 1 for i in range(1, n + 1): fact = fact * i return fact def bc(a, b): return (fact(a+b)//(fact(a)*fact(b))) def path(a,b): paths = bc(a, b) return paths print(path(20,20))
import random import itertools class Dice(object): def __init__(self, dnumber=6): self.dnumber = dnumber def roll(self, n=1): for _ in range(n): yield random.randint(1, self.dnumber+1) def possibilities(self, n=1): return list(itertools.combinations_with_replacement(range(1, self.dnumber+1), n)) def possible_rolls(amount_of_dice=1, min_value= 1, max_value=6): return list(itertools.combinations_with_replacement(range(min_value, max_value+1), amount_of_dice)) def outcomes(possible_rolls): from collections import defaultdict tally = defaultdict(int) for roll in possible_rolls: tally[sum(roll)] += 1 return tally roll_n = lambda n, d_max=6: outcomes(possible_rolls(n, max_value=d_max)) def distribution(outcomes): spacing = ' ' * max([len(str(k)) for k in outcomes.keys()]) height = max(outcomes.values()) // 2 print('') for y in reversed(range(height + 1)): chart_row = '' for value, frequency in sorted(outcomes.items()): difference = frequency - 2 * y if difference > 1: chart_row += ':' elif difference > 0: chart_row += '.' else: chart_row += ' ' chart_row += spacing print(chart_row) print(' '.join([(str(k) + (' ' if len(str(k)) != len(spacing) else '')) for k in outcomes.keys()])) if __name__ == '__main__': distribution(roll_n(2, 20)) distribution(roll_n(3)) d = Dice(20) print(list(d.roll()))
# -*- coding: utf-8 -*- """ Created on Sun Jun 19 12:24:09 2016 @author: Administrator """ import numpy as np # import packages import math import mpl_toolkits.mplot3d import matplotlib.pyplot as plt # class BASEBALL will compute the trajetory of the baseball with air resistance # where # vx0,vy0,vz0: initial velocity of the baseball # dt: time step size # omgx,omgy,omgz: the angular velocity class BASEBALL(object): def __init__(self, _vx0, _vy0, _vz0, _dt= 0.1, _omgx=0,_omgy=0,_omgz=0): self.vx, self.vy, self.vz= _vx0, _vy0, _vz0 self.v = math.sqrt(_vx0**2+ _vy0**2+ _vz0**2) self.B2= 0.0039+ 0.0058/(1.+math.exp((self.v-35)/5)) self.S0= 4.1E-4 self.g= 9.8 self.dt= _dt self.x, self.y, self.z= [0], [1.8], [0] self.omgx, self.omgy, self.omgz= _omgx, _omgy, _omgz def calculate(self): while True: self.x.append(self.vx*self.dt+self.x[-1]) # append coordinates to x,y,z self.y.append(self.vy*self.dt+self.y[-1]) self.z.append(self.vz*self.dt+self.z[-1]) self.vx, self.vy, self.vz = \ (-self.B2*self.v*self.vx+ self.S0*self.vy*self.omgz)*self.dt+ self.vx, \ (-self.g- self.B2*self.v*self.vy+ self.S0*self.vz*self.omgx)*self.dt+ self.vy,\ (self.S0*self.vx*self.omgy)*self.dt+ self.vz # change the velocity self.v= math.sqrt(self.vx**2+self.vy**2+self.vz**2) self.B2= 0.0039+ 0.0058/(1.+math.exp((self.v-35)/5)) if self.y[-1]< 0: break def graphics(self,_gra, _omgy): # plot the trajetory _gra.plot(self.z, self.x, self.y, label=r'$\omega _y$ = %.2f rad/s'%_omgy) _gra.scatter([self.z[0],self.z[-1]],[self.x[0],self.x[-1]],[self.y[0],self.y[-1]],s=30) _gra.text(self.z[-1], self.x[-1]-80, self.y[-1], r'$\omega _y$ = %.2f rad/s'%_omgy,fontsize=10) fig= plt.figure(figsize=(6,6)) ax = plt.subplot(1,1,1,projection='3d') for omgy in [-400.,200.,0.,200.,400.]: # change the angular velocity the determine the dependence of trajetory on omega comp= BASEBALL(110*0.4470*math.cos(np.pi/4), 110*0.4470*math.sin(np.pi/4), 0., 0.1,0, omgy, 0) comp.calculate() comp.graphics(ax, omgy) ax.set_xlabel('z (m)', fontsize=18) ax.set_ylabel('x (m)', fontsize=18) ax.set_zlabel('y (m)', fontsize=18) ax.set_title('ball with horizontal spin', fontsize=18) ax.set_xlim(-100,100) ax.set_ylim(0,180) ax.set_zlim(0,100) ax.text(0,0,80,'with air drag', fontsize= 18) plt.show(fig)
class Bus: #List,NumOfPassengers def __init__(self,num): self.List=['Free' for i in range(num)] self.NumOfPassengers=0 def getOn(self,name): for i in range(len(self.List)): if self.List[i]=='Free': self.List[i]=name self.NumOfPassengers+=1 break else: print("The passenger: "+name+" "+" don't get on to the bus") def getOff(self,name): for i in range(len(self.List)): if self.List[i]==name: self.List[i]='Free' self.NumOfPassengers-=1 break else: print("The passenger: "+name+" "+"don't available on the bus") def __str__(self): return f'The List of seats: {self.List}'
list=[i for i in range(1,11)] list1=list[7:] print(list1) print(list[::-1]) print(list[::2]) list2=list[::2] print(list2) num1=int(input("Enter a new number: ")) num2=int(input("Enter a new number: ")) num3=int(input("Enter a new number: ")) list[4:6]=[num1,num2] list.append(num3) print(list) list3=[list[i]*2 for i in range(10)] print(list3) list4=[list[0],list[-2]] print(list4)
num = int(input("Enter choose of num: ")) i = 1 serial = i max = num while (i < 7): if num > max: max = num serial = i num = int(input("Enter choose of num: ")) i += 1 if max > num: print("The serial max number: " + str(serial)) else: max = num serial = i print("The serial max number: " + str(serial))
count=0 list=[] grade=int(input("Enter yout new grade: ")) while grade!=0: list.append(grade) grade=int(input("Enter the next grade: ")) for i in list: if i<60: count+=1 print("The number of fail grades:"+str(count)+"\nThe number of success grades: "+str(len(list)-count))
num1 = int(input("Enter num: ")) num2 = int(input("Enter num2: ")) if num1 >= num2: for num2 in range(num2 + 1, num1): if num2 % 2 == 0: print(num2) else: continue # לא חובה else: for num1 in range(num1 + 1, num2): if num1 % 2 == 0: print(num1) else: continue # לא חובה
num = int(input("Input a positive number: ")) num2 = int(input("Input a positive number: ")) divi = 1 mudu = 0 while num2 > num: num2 = int(input("Input a little number: ")) nnum = num2 while num2 + nnum <= num: divi += 1 num2 += nnum mudu = num - (nnum * divi) print("The divided is: " + str(divi) + " " + "The mudulo is: " + str(mudu))
class Circle: #Radius,Pi def __init__(self,Radius): self.Radius=Radius self.Pi=3.14 def area(self): return (self.Pi*self.Radius)**2 def circumference(self): return 2*self.Pi*self.Radius if __name__=='__main__': Radius=int(input("Enter a new radius: ")) Circle1=Circle(Radius) print("The area of circle: "+str(Circle1.area())+" "+"The circumference of circle: "+str(Circle1.circumference()))
def passfunction(grade): if grade>=70 and grade<=100: return True else: return False if __name__=='__main__': for i in range(5): grade=int(input("Enter a new grade: ")) if passfunction(grade)==True: print("You passed the test") else: print("Sorry,you dont passed ")
def FloatToInt(num1): num2=int(num1) sum = 1 - (num1 - num2) if(num1-num2>=0.5): num1+=sum num1=int(num1) else: num1=int(num1) return num1 if __name__=='__main__': num1=float(input("Enter the first number: ")) num2=float(input("Enter the second number: ")) print(FloatToInt(num1)+FloatToInt(num2))
from OriHasinClasses2.T2Class import * if __name__=='__main__': seats=int(input("Enter number of seats: ")) Bus1=Bus(seats) num=int(input("Enter a number you want to do on the bus . 1 - get on passenger on the bus , 2 - get off passenger from the bus , 0 - stop program: ")) while num!=0: name=input("Enter a passenger name: ") if num==1: Bus1.getOn(name) if num==2: Bus1.getOff(name) num = int(input("Enter a number you want to do on the bus . 1 - get on passenger on the bus , 2 - get off passenger from the bus , 0 - stop program: ")) print(Bus1.__str__())
def minfunction(num1,num2): if num1>=num2: return num2 else: return num1 def maxfunction(num1,num2): if num2>=num1: return num2 else: return num1 from OriHasinFunctions.Targil6 import * if __name__=='__main__': num1=int(input("Enter a new number: ")) num2=int(input("Enter again new number: ")) num3=minfunction(num1,num2) num4=maxfunction(num1,num2) printnumbers(num3,num4)
import ast def rawStringSize(string): return len(string) def calcStringSize(string): return len(ast.literal_eval(string)) def calcEncodeSize(string): return rawStringSize(string) + string.count('\\') + string.count('\"') + 2 representationSize = 0 actualSize = 0 recodeSize = 0 with open('Day08/InputStrings.txt') as file: while True: line = file.readline().rstrip() if not line: break representationSize = representationSize + rawStringSize(line) actualSize = actualSize + calcStringSize(line) recodeSize = recodeSize + calcEncodeSize(line) print(representationSize, "-", actualSize, "=", representationSize - actualSize) print(recodeSize, "-", representationSize, "=", recodeSize - representationSize)
#!/usr/bin/python3 """ locked boxes """ def canUnlockAll(boxes): """ INPUT a list of boxes with it's keys OUTPUT true if every box can be open false otherwise """ keys = [x for x in range(1, len(boxes))] for i in range(len(boxes)): for key in boxes[i]: if key in keys and key != i: keys.remove(key) return len(keys) == 0
import sys #导入sys库 script, encoding, error, languages = sys.argv #赋值三个变量参数给sys.argv模块 #定义主函数main,对参数进行处理。 参数依次为:文件、编码类型、错误处理 def main(language_file, encoding, errors): print(">>>> in main ",repr(language_file), encoding, errors) line = language_file.readline() #赋值变量line为逐行读取文件 print(">>>line:", line) if line: #此处if语句的条件是,当line可读取到内容为真,继续执行,读取不到则停止 print_line(line, encoding, errors) #调用下方的函数处理文件、编码和错误参数 print(">>>> main again") return main(language_file, encoding, errors) #调用main函数处理参数,此处算是自我循环,只有当if为假就停止 print("<<<< main exit") #定义函数print_line def print_line(line, encoding, errors): print("line:", repr(line), encoding, errors) next_lang = line.strip() #.strip的作用是去除开头和结尾的空行或换行符 raw_bytes = next_lang.encode(encoding, errors = errors) #对字符串编码为字节串 cooked_string = raw_bytes.decode(encoding, errors = errors) #对字节串解码为字符串 print(raw_bytes, "<===>", cooked_string) #打印上面的两个变量,可看到一致 print("print_line done") #赋值变量languages为使用utf-8编码,打开某个文件 #languages = open("languages.txt", encoding = "utf-8") #也可以直接在参数上赋值要打开的文件,以后就可以用脚本处理其他文本文件 languages = open(languages, encoding = "utf-8") #调用main函数处理文件,函数自带循环,从终端可看到处理结果,添加调试代码也可 main(languages, encoding, error)
#赋值ten_things变量为字符串 ten_things = "apples oranges crows telphone light sugar" #这个列表中没有10个元素,可使用代码修改下并实现。 print("wait there are not 10 things in that list . let's fix that.") #定义stuff变量,赋值为ten_things的split分割方法,使用空格分割为列表 stuff = ten_things.split(' ') print(stuff) #根据输出结果,可以看出stuff是一个列表。 print(type(stuff)) #使用type函数看出,stuff是一个list. #定义more_stuff变量,赋值为一个列表。 more_stuff = ["day", "night", "song", "frisbee", "corn", "banana", "girl", "boy"] #执行while循环,条件为len(stuff) != 10,即用len函数查看stuff长度为多少,如果不等于10的时候为真,执行代码块 while len(stuff) < 10: next_one = more_stuff.pop() #定义变量next_one,赋值为more_stuff.pop(),即对more_stuff执行pop函数,默认为抓取more_stuff的最后一个元素,抓取后原list值减少一个 print("adding:", next_one) #打印取到的元素值。 stuff.append(next_one) #执行stuff.append(next_one) ,将元素添加到stuff列表中 print(f"there are {len(stuff)} items now.") #打印len(stuff),知道执行一次循环后的stuff长度。 print("there we go: ", stuff) #打印stuff的值,此时应该是10个元素了 print("let's do some things with stuff.") print(stuff[1]) #输出stuff的第二个元素,因为默认从0开始 print(stuff[-1]) # whoa! fancy 输出最后一个元素 print(stuff.pop()) #取出stuff的最后一个元素并打印 print(' '.join(stuff)) #what? cool! 对stuff中每个元素添加空格分割 print('#'.join(stuff[3:5])) #super stellar! 对索引3至4取值打印,并添加'#'分割
# 定义一个变量,赋值为4个可接收格式化参数的空值,如果变量只给三个{}参数,而下面的参数引入了4个值,就只打印从左往右的前三个。 formatter = "{} {} {} {} " # 执行format方法的时候从左往右。 print(formatter.format(1, 2, 3, 4)) print(formatter.format("one", "two", "three", "four")) # 参数为布尔值,format后变为字符串 print(formatter.format(True, False, False, True)) # 直接打印布尔值,也不会报错,但是修改比如False为false就会报错,报错信息为变量没有定义。 也就是说如果按布尔值变量打印无问题,按正常变量打印的话,需要赋值。 按字符串的话,需要加双引号。 print(True, False, False, True) # 此处格式化变量formatter,该变量的赋值已设置双引号,所以按字符串“{}”格式化了。 print(formatter.format(formatter, formatter, formatter, formatter)) print(formatter.format( "try you", "own text here", "maybe a pome", "or a song about fear" ))
print('the game name is "eat what"?') eat = input("please tell me ,what do eat? Such as noodles, rice, dumplings... > ") if eat == "noodles": print("Okay, but you need to choose again, chow mein or noodle soup.?") print("enter '1', choose chow mein.") print("enter '2', choose noodle soup.") noodles_choose = input("please enter 1 or 2. > ") if noodles_choose == "1": print("All right, let's go right. To a noodle shop. ") elif noodles_choose == '2': print("OK, Let's go to Lanzhou to pull noodles.") else: print("Without this food.") elif eat == "rice": print("Let's have braised chicken rice.") wait_people = int(input("how many people are waiting? > ")) if wait_people > 10: print("Don't want to wait. Choose again.") else: print("Wait a minute.It's right here.") elif eat == "dumplings": print("我们去小恒水饺店吧.") else: print("let's Order meal.")
# 定义变量days是一个字符串。 months变量赋值字符串,但是使用\n进行了换行操作。 days = "mon tue wed the fri sat sun " months = "\njan\nfeb\nmar\napr\nmay\njun\njul\naug" print("here are the days: ", days) print("here are the months: ", months) # 三个连续的引号可以输入一整段的字符串,且随意换行。可以在每行前增加\t标识制表符tab,使得每行缩进8个空格?也有可能4个。。。 print(""" \tthere's something going on the here. \twith the three double-quotes. \twe'll be able to type as much as we like. \teven 4 lines if we wang, or 5, or 6. """)
#Write a function called num_factors. num_factors should #have one parameter, an integer. num_factors should count #how many factors the number has and return that count as #an integer # #A number is a factor of another number if it divides #evenly into that number. For example, 3 is a factor of 6, #but 4 is not. As such, all factors will be less than the #number itself. # #Do not count 1 or the number itself in your factor count. #For example, 6 should have 2 factors: 2 and 3. Do not #count 1 and 6. You may assume the number will be less than #1000. #Add your code here! def num_factors(n): total = 0 for x in range(2,n): if n % x == 0: total +=1 return total #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: 0, 2, 0, 6, 6, each on their own line. print(num_factors(5)) print(num_factors(6)) print(num_factors(97)) print(num_factors(105)) print(num_factors(999)) ORRRR #We first write the function name and have one #parameter, as written in the instructions def num_factors(num): #We declare a variable that will count the number #of factors the input num will have. count = 0 #We use a for loop because we know the number #of iterations we have to go through for this problem #We start from 2 because 1 does not count as a factor #and end in the number because the number itself #is not a factor either # #The rule for factors is that when you divide the factor #to the number, the remainder is 0. In code, you use #the modulus operator to represent that. As shown, when #the num and i is divided, it must equal 0 to be a factor. #Since the count increment is only passed through when #we verify that the current i value is a factor, we can return #the count at the end which tells us the number of factors it has for i in range(2, num): if num % i == 0: count += 1 return count
def dict_construct(keys, values) -> dict: return dict(zip(keys, values)) if __name__ == "__main__": cort_keys = (1, 2, 3, 4, 5) cort_values = ("orange", "apple", "banana", "grapefruit", "watermelon") coin = ('Bitcoin', 'Ether', 'Ripple', 'Litecoin') code = ('BTC', 'ETH', 'XRP', 'LTC') fruits = dict_construct(cort_keys, cort_values) crypto = dict_construct(coin, code) print(fruits) print(crypto)
def temp_calc(degree: float, temp_type: str): if temp_type == 'C': celsius = degree kelvin = celsius + 273.15 fahrenheit = celsius * 1.8 + 32 elif temp_type == 'K': kelvin = degree celsius = kelvin - 273.15 fahrenheit = kelvin * 1.8 - 459.67 elif temp_type == 'F': fahrenheit = degree celsius = (fahrenheit - 32) / 1.8 kelvin = (fahrenheit + 459.67) / 1.8 else: print("404 \nБыть может в следующих обновлениях придумают такой тип температуры. \nПопробуйте С, F или К") exit() return celsius, kelvin, fahrenheit if __name__ == "__main__": user_degree = float(input("Сколько градусов? ")) user_degree_type = input("С - Цельсий, K - Кельвин, F - Фаренгейт \nПо какой шкале? ").upper() print("C = {0}° \nK = {1}° \nF = {2}°".format(temp_calc(user_degree, user_degree_type)[0], temp_calc(user_degree, user_degree_type)[1], temp_calc(user_degree, user_degree_type)[2]))
letter_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] num_list = [1, 2, 3, 4, 5, 6, 7, 8] print(""" Введите шахматный ход для вашего коня. Важно! Вводите ход в формате настоящих шахмат! Напрмер: A2 - D7 И не забудь верхний регистр и англ раскладку, ну будь ты человеком, а? """) start = input("Начальная точка фигуры: ") finish = input("Конечная точка фигуры: ") start = list(start) finish = list(finish) x1 = 0 x2 = 0 y1 = int(start[1]) y2 = int(finish[1]) for i in letter_list: a = int(letter_list.index(i)) if start[0] == letter_list[a]: x1 = num_list[a] if finish[0] == letter_list[a]: x2 = num_list[a] dx = abs(x1 - x2) dy = abs(y1 - y2) if dx == 1 and dy == 2 or dx == 2 and dy == 1: print('Да, конь может так ходить!') else: print('Нет, конь не может так ходить!')
def symb_amount(x): return len(x) def words_amount(x): x = x.split() return len(x) some_string = input("Input your sentence: ") print("Your sentence contains {0} words and {1} symbols" .format(words_amount(some_string), symb_amount(some_string)))
#Calculator Project def add(a,b): return a+b def subtract(a,b): return a-b def multiply(a,b): return a*b def divide(a,b): return a/b operations = { "+":add, "-":subtract, "*":multiply, "/":divide } def calculator(): num1 =float(input("What's your first number?: ")) for symbol in operations: print(symbol) calculation_done = True while calculation_done: sign = input("Pick an operation:") num2 =float(input("What's your next number?: ")) calculation_function = operations[sign] answer = calculation_function(num1, num2) print(f"{num1} {sign} {num2} = {answer}") if input("Are you want to continue? Type 'yes' or 'no'.\n") == "y": num1 = answer else: calculation_done = False calculator() calculator()
price = 490 while True: #In Prozent discount_input = input("Wie hoch ist der Rabatt?: (in Prozent) ") discount = price / 100 * float(discount_input) price = price - discount text = "Dein finaler Preis lautet: " print(text + str(price))
companies = ["VW","Audi","Tesla"] while True: companies.sort() print(companies) new_company = input("Gib eine Automarke ein:") companies.append(new_company)
name = input('Wie ist dein Name?') if name == "Philipp": print('Hallo Administrator') elif name == "Julia": print('Hallo Max') else: print('Du bist kein Administrator')
class Person: def __init__(self, name, height, weight): self.height = height self.weight = weight self.name = name self.bmi = weight / (height * height) def printBMI(self): print(self.name + '\'s BMI ist: ' + str(self.bmi)) def getHeightIn(self,metric): if (metric == "CM"): return self.height * 100 elif (metric == "FEET"): return self.height * 3.281 return self.height person_a = { "height": 1.7, "weight": 50.00, "name": "Musterfrau" } person_b = Person("Musterfrau",1.7,50) print(person_a) person_b_height_cm = person_b.getHeightIn("CM") if(person_b_height_cm > 160): print("Du bist super!")
import random guess = 0 secret = random.randint(1, 5) while True: guess = int(input('Rate meine Zahl!')) if (guess == secret): print('Super!') break elif (guess > secret): print('Deine geratene Zahl ist größer als meine geheime Zahl!') elif (guess < secret): print('Deine geratene Zahl ist kleiner als meine geheime Zahl!') print('Versuche es nochmal')
class Diff(object): def __init__(self, f, h=1E-5): self.f = f self.h = float(h) class Forward1(Diff): def __call__(self, x): f, h = self.f, self.h return (f(x+h) - f(x))/h class Backward1(Diff): def __call__(self, x): f, h = self.f, self.h return (f(x) - f(x-h))/h class Central2(Diff): def __call__(self, x): f, h = self.f, self.h return (f(x+h) - f(x-h))/(2*h) class Central4(Diff): def __call__(self, x): f, h = self.f, self.h return (4./3)*(f(x+h) - f(x-h)) /(2*h) - \ (1./3)*(f(x+2*h) - f(x-2*h))/(4*h) class Central6(Diff): def __call__(self, x): f, h = self.f, self.h return (3./2) *(f(x+h) - f(x-h)) /(2*h) - \ (3./5) *(f(x+2*h) - f(x-2*h))/(4*h) + \ (1./10)*(f(x+3*h) - f(x-3*h))/(6*h) class Forward3(Diff): def __call__(self, x): f, h = self.f, self.h return (-(1./6)*f(x+2*h) + f(x+h) - 0.5*f(x) - \ (1./3)*f(x-h))/h
number = float(raw_input("Give me a number: ")) if number % 4 == 0: print("Your number is a multiple of 4.") elif number % 2 == 0: print("Your number is even.") else: print("Your number is odd. Get it? :P")
# Import statement import math # ORGANIZE CODE BEFORE PROCEEDING FURTHER # implement images in text # print if a monster attacks def printMonsterImage(): print("███████████████████████████") print("███████▀▀▀░░░░░░░▀▀▀███████") print("████▀░░░░░░░░░░░░░░░░░▀████") print("███│░░░░░░░░░░░░░░░░░░░│███") print("██▌│░░░░░░░░░░░░░░░░░░░│▐██") print("██░└┐░░░░░░░░░░░░░░░░░┌┘░██") print("██░░└┐░░░░░░░░░░░░░░░┌┘░░██") print("██░░┌┘▄▄▄▄▄░░░░░▄▄▄▄▄└┐░░██") print("██▌░│██████▌░░░▐██████│░▐██") print("███░│▐███▀▀░░▄░░▀▀███▌│░███") print("██▀─┘░░░░░░░▐█▌░░░░░░░└─▀██") print("██▄░░░▄▄▄▓░░▀█▀░░▓▄▄▄░░░▄██") print("████▄─┘██▌░░░░░░░▐██└─▄████") print("█████░░▐█─┬┬┬┬┬┬┬─█▌░░█████") print("████▌░░░▀┬┼┼┼┼┼┼┼┬▀░░░▐████") print("█████▄░░░└┴┴┴┴┴┴┴┘░░░▄█████") print("███████▄░░░░░░░░░░░▄███████") print("██████████▄▄▄▄▄▄▄██████████") print("███████████████████████████") def printFaceImage(): print("---") print("\ \ ") print(" \ \ ") print(" \ \ ") print(" \ \ ") print(" \ \ ") print(" \ \ ") print(" [] ") # Telling user how to play def showInstructions(): # Print out an intro and main menu print("Welcome to : ") print("========") print("Commands: ") print("go '[direction]' to chose a path") print("get '[item]' to pick up an item") print("attack '[enemy]' with '[item]' to attack an enemy") # Player health. Maybe change to "Healthy", "Near death", etc... playerHealth = 50 print("-----------------------") print("Please enter your name") playerName = input() print("-----------------------") # Player's current status def showStatus(playerHealth): print("-----------------------") print(playerHealth) print("You are in the " + rooms[currentRoom]["name"]) if "item" in rooms[currentRoom]: print("You see " + str(rooms[currentRoom]["item"])) # Print current inventory # str is toString print("Inventory: " + str(inventory)) # If an enemy is in the room... if "enemy" in rooms[currentRoom]: print("You are confronted by a " + rooms[currentRoom]["enemy"] + "!") print("What will you do?") print("-----------------------") printMonsterImage() return playerHealth # An initially empty inventory array inventory = ["rocks"] # Currently equiped currentEquip = [] # Using dictionaries to make a room room = { "name" : "Hall" } # Getting the name of the room roomName = room["name"] # Mapping rooms to a room number rooms = { 1 : { "name" : "Hall" } , 2 : { "name" : "Bedroom" }} print(roomName) # Adding doors/More rooms/Linking together rooms # Add additional items to a room by adding to its dictionary rooms = { 1 : { "name" : "Hall", # Being mapped to Hall "east" : 2 , # East being mapped to 2 "south" : 3 , # Does not currently support two word items "item" : ["axe" , "bat" , "apple" , "family portrait" ] , "enemy" : "Skeleton" } , 2 : { "name" : "Bedroom" , "west" : 1 , "south" : 4 , "item" : ["dressing table" , "bed" , "mirror"] } , 3 : { "name" : "Kitchen" , "north" : 1 , "item" : "butcher knife", "enemy" : "Skeleton" } , 4 : { "name" : "Bathroom" , "north" : 2 , "item" : "mirror", "enemy" : "Skeleton" } } # Where the player statrs starts currentRoom = 1 showInstructions() # An infitnite loop while True: # Use error handling showStatus(playerHealth) try: action = input().lower().split() # Movement if action[0] == "go": if action[1] in rooms[currentRoom]: currentRoom = rooms[currentRoom][action[1]] else: print("You cannot go that way.") showStatus() # Other player actions if action[0] == "get": print("ok") # If item is in the room and if the item is what the player enters if "item" in rooms[currentRoom] and action[1] in rooms[currentRoom]["item"]: print("ok 2") #if action[1] in rooms[currentRoom]: print("ok 3") inventory += [action[1]] # Deleting entire key, not allowing user to get other items...a problem # if action[1] in rooms[currentRoom]["item"]: del rooms[currentRoom]["item"] # Need to remove value from key after user takes it # Block to use item if action[0] == "use": if action[1] in inventory: print(playerName + " used " + str(action[1])) # Block to equip item if action[0] == "equip": if action[1] in inventory: print(playerName + " equiped " + str(action[1])) # Block to handle combat if action[0] == "attack": if action[1] in rooms[currentRoom]["enemy"]: print("") # If incorrect input, print error message to console break except TypeError: print("I cannot do that...")
from Stack import * from StackIter import * if __name__ == '__main__': s1 = Stack() for i in range(5): s1.push(i) """ s2-s5 same as s1 """ s2 = s1 s3 = s1 s4 = s1 s5 = s1 """ test the stack operations """ s3.pop() s5.pop() s4.push(2) s5.push(9) """ Demonstrate overloaded operator """ print("1 == 2", (s1 == s2)) print("1 == 3", (s1 == s3)) print("1 == 4", (s1 == s4)) print("1 == 5", (s1 == s5))
import socket import time #define address & buffer size HOST = "www.google.com" PORT = 8001 BUFFER_SIZE = 1024 #get host information def get_remote_ip(host): print(f'Getting IP for {host}') try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: print ('Hostname could not be resolved. Exiting') sys.exit() print (f'Ip address of {host} is {remote_ip}') return remote_ip def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as proxy_start: #QUESTION 3 proxy_start.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #bind socket to address proxy_start.bind(("", PORT)) #set to listening mode proxy_start.listen(2) #continuously listen for connections while True: conn, addr = proxy_start.accept() print("Connected by", addr) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as proxy_end: print("Connecting to Google") remote_ip = get_remote_ip(HOST) port = 80 proxy_end.connect((remote_ip, port)) #recieve data and send to google full_data = conn.recv(BUFFER_SIZE) print("sending received data to google") proxy_end.sendall(full_data) proxy_end.shutdown(socket.SHUT_WR) data = proxy_end.recv(BUFFER_SIZE) print(f"Sending received data {data}back to client") conn.send(data) conn.close() if __name__ == "__main__": main()
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn import preprocessing from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split class wealthPredict: # Read CSV file into DataFrame df #XPredict=np.array([111375,147324,150844,171303,166807,222071,248594,276870,272201,288159,307153,340263,324594]).reshape(-1, 13) def __init__(self, XPredict): self.XPredict = XPredict def predict(self): df = pd.read_csv('Wealth.csv', index_col=0) df = df[['age', 'location', 'workclass', 'education', 'marital_status', 'occupation', 'sex', 'hours_per_week', 'native_country','MonthyIncome_2020','Networth_2007','Networth_2008','Networth_2009','Networth_2010','Networth_2011','Networth_2012','Networth_2013','Networth_2014','Networth_2015','Networth_2016','Networth_2017','Networth_2018','Networth_2019','Networth_2020']].copy() #df.info() y_list=df.iloc[:,19:24] #Networth_2020.values X_list=df.iloc[:,10:18] #df.age.values#[:, :1] y_array=np.array(y_list).reshape(-1,5)#1 X_array=np.array(X_list).reshape(-1,8)#13 print(X_array) print("predict wealth,y ", y_array.shape) print("predict wealth,x ", X_array.shape) # split into train and test datasets x_train, x_test, y_train, y_test = train_test_split(X_array, y_array) #print(x_train.shape) # fit final model model = LinearRegression() model.fit(x_train, y_train) print("intercept",model.intercept_) print("coef", model.coef_) print("model.score(x_train, y_train)",model.score(x_train, y_train)) print("model.score(x_test, y_test)",model.score(x_test, y_test)) ynew = model.predict(self.XPredict) # show the inputs and predicted outputs for i in range(len(self.XPredict)): print("X=%s, Predicted=%s" % (self.XPredict[i], ynew[i])) return(ynew[i])
def main(): print fact_loop(4) # added note def fact_loop(d): fact = 1 for i in range(1,d+1): fact = fact * i return fact if __name__ == "__main__": main() # added another note