text
stringlengths
37
1.41M
heads = int(input("Enter Heads: ")) legs = int(input("Enter Legs: ")) chicken = 0; rabbit = 0; for a in range(0,(heads)) : b = heads - a x = (a*2)+(b*4) if x == legs: chicken = a; rabbit = b; print("Chickens: "+str(chicken)+" , Rabbits: "+str(rabbit))
import random def number_wang(): answer = random.randint(1,10) guesses = 0 while True: guess = int(input("What is your number, scrub?: ")) guesses += 1 if guess == answer: print ("Yup, that's it alright.") break else: if guess < answer: print ("Ha, no that's too low.") elif guess > answer: print ("Ha, no that's too high.") if abs((guess - answer)) < 3: print ("Getting close.") if guesses == 5: print ("game over man, game over") break print (guesses) number_wang()
# this file contain features function that we'll be used to put features in the right # format for the machine learning algorithms to work from basic_ml import * import sys sys.path.append('..') from basic import * #TODO: simplify the 3 lines of code that append to the feat name list # valid values for some attributes VALID_SEX_VALUES = ['m', 'f'] VALID_LOCAL_VALUES = ['df', 'outros', 'indisponível'] VALID_QUOTA_VALUES = ['sim', 'não'] VALID_SCHOOL_TYPE_VALUES = ['não informada', 'particular', 'pública'] VALID_COURSE_VALUES = COURSES_OFF_NAME VALID_WAY_IN_VALUES = ['Vestibular', 'Convênio-Int', 'Transferência Obrigatória', 'Acordo Cultural-PEC-G', 'Convênio - Andifes', 'Matrícula Cortesia', 'Sisu-Sistema de Seleção Unificada', 'Transferência Facultativa', 'Portador Diplom Curso Superior', 'PEC-Peppfol-Graduação', 'Vestibular para mesmo Curso', 'Programa de Avaliação Seriada', 'Enem'] def add_feature_sex(stu, stu_features, feat_name_lst): """ append feature sex to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. list with the name of the features considered so far returns: nothing """ name_feature = 'sex' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) # assert value is as expected assert(stu.sex in VALID_SEX_VALUES) if stu.sex == 'm': stu_features.append(0) elif stu.sex == 'f': stu_features.append(1) else: exit('error on add feature sex function') def add_feature_age(stu, stu_features, feat_name_lst): """ append feature age to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. list with the name of the features considered so far returns: nothing """ name_feature = 'age' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) # assert value is as expected assert(stu.age > 0 and stu.age < 100) stu_features.append(stu.age) def add_feature_condition(stu, stu_features, semester, feat_name_lst): """ append feature condition to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. the semester we are interested. 4. list with the name of the features considered so far returns: nothing """ name_feature = 'condition' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) assert(type(stu.in_condition[semester - 1]) == int) if stu.in_condition[semester - 1] == 0: stu_features.append(0) else: stu_features.append(1) def add_feature_course(stu, stu_features, feat_name_lst): """ append feature course to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. list with the name of the features considered so far returns: nothing """ # use dummy list name_feature = 'course' put_dummy_variables(stu.course, VALID_COURSE_VALUES, stu_features, name_feature,\ feat_name_lst) def add_feature_credit_rate_acc(stu, stu_features, semester, feat_name_lst): """ append feature credit_rate_acc to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. the semester we are interested. 4. list with the name of the features considered so far returns: nothing """ name_feature = 'credit_rate_acc' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) # if student has already graduate, put last value in the list assert(stu.credit_rate_acc[semester - 1] >= 0) stu_features.append(stu.credit_rate_acc[semester - 1]) def add_feature_hard_rate(stu, stu_features, semester, feat_name_lst): """ append feature hard_rate to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. the semester we are interested. 4. list with the name of the features considered so far returns: nothing """ name_feature = 'hard_rate' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) # if student has already graduate, put last value in the list assert(stu.hard_rate[semester - 1] >= 0 and stu.hard_rate[semester - 1] <= 1.0) stu_features.append(stu.hard_rate[semester - 1]) def add_feature_drop_rate(stu, stu_features, semester, feat_name_lst): """ append feature drop_rate to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. the semester we are interested. 4. list with the name of the features considered so far returns: nothing """ name_feature = 'drop_rate' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) assert(stu.drop_rate[semester - 1] >= -1 and stu.drop_rate[semester - 1] <= 2) stu_features.append(stu.drop_rate[semester - 1]) def add_feature_impr_rate(stu, stu_features, semester, feat_name_lst): """ append feature improvement_rate to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. the semester we are interested. 4. list with the name of the features considered so far returns: nothing """ name_feature = 'impr_rate' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) # if student has already graduate, put last value in the list stu_features.append(stu.improvement_rate[semester - 1]) def add_feature_ira(stu, stu_features, semester, feat_name_lst): """ append feature ira to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. the semester we are interested. 4. list with the name of the features considered so far returns: nothing """ name_feature = 'ira' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) # if student has already graduate, put last value in the list assert(stu.ira[semester - 1] >= 0.0 and stu.ira[semester - 1] <= 5.0) stu_features.append(stu.ira[semester - 1]) def add_feature_local(stu, stu_features, feat_name_lst): """ NOTE: this function should not be used anymore append feature local to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. list with the name of the features considered so far returns: nothing """ exit('add feature local is not to be used') # use dummy list #name_feature = 'local' #put_dummy_variables(stu.local, VALID_LOCAL_VALUES, stu_features, name_feature, # feat_name_lst) def add_feature_quota(stu, stu_features, feat_name_lst): """ append feature quota to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. list with the name of the features considered so far returns: nothing """ # use dummy list name_feature = 'quota' put_dummy_variables(stu.quota, VALID_QUOTA_VALUES, stu_features, name_feature, feat_name_lst) def add_feature_quota_enh(stu, stu_features, feat_name_lst): """ append feature quota enhanced to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. list with the name of the features considered so far returns: nothing * function should enhance performance of model by considering a different set of * categories than the original """ ENH_QUOTA_VALUES = ['negro', 'universal', 'outros'] assert (stu.quota in VALID_QUOTA_VALUES) if stu.quota == 'negro': enh_quota = stu.quota elif stu.quota == 'universal': enh_quota = stu.quota else: enh_quota = 'outros' # use dummy list name_feature = 'enh_quota' put_dummy_variables(enh_quota, ENH_QUOTA_VALUES, stu_features, name_feature, feat_name_lst) def add_feature_pass_rate(stu, stu_features, semester, feat_name_lst): """ append feature pass_rate to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. the semester we are interested. 4. list with the name of the features considered so far returns: nothing """ name_feature = 'pass_rate' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) # if student has already graduate, put last value in the list assert(stu.pass_rate[semester - 1] >= -1 and stu.pass_rate[semester - 1] <= 2) stu_features.append(stu.pass_rate[semester - 1]) def add_feature_position(stu, stu_features, semester, feat_name_lst): """ append feature position to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. the semester we are interested. 4. list with the name of the features considered so far returns: nothing """ name_feature = 'position' if not (name_feature in feat_name_lst): feat_name_lst.append(name_feature) # if student has already graduate, put last value in the list assert(stu.position[semester - 1] >= -1) stu_features.append(stu.position[semester - 1]) def add_feature_school_type(stu, stu_features, feat_name_lst): """ NOT TO USE -> please don't use this atribute, because there are a lot of missing values. append feature school_type to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. list with the name of the features considered so far returns: nothing """ exit('too much missing values here') # use dummy list name_feature = 'school_type' put_dummy_variables(stu.school_type, VALID_SCHOOL_TYPE_VALUES, stu_features, name_feature, feat_name_lst) def add_feature_way_in(stu, stu_features, feat_name_lst): """ append feature way in enhance to the student feature list append atribute to the name list, if not already in there receives: 1. a student 2. a list containing all the student features 3. list with the name of the features considered so far returns: nothing """ ENH_WAY_IN_VALUES = ['PAS', 'Vestibular', 'Outros'] assert (stu.way_in in VALID_WAY_IN_VALUES) if stu.way_in == 'PAS': enh_way_in = stu.way_in elif stu.way_in == 'Vestibular': enh_way_in = stu.way_in else: enh_way_in = 'Outros' # use dummy list name_feature = 'way_in' put_dummy_variables(enh_way_in, ENH_WAY_IN_VALUES, stu_features, name_feature, feat_name_lst) def add_outcome(stu, target_lst): """ append student outcome (whether student was able to graduate or not) to a target list containing this students results receives: 1. a student 2. the target list returns: nothing """ # assert value is as expected assert(stu.graduated() or stu.migrated() or stu.evaded()) if stu.graduated(): target_lst.append(GRADUATED) elif stu.migrated(): target_lst.append(MIGRATED) else: target_lst.append(EVADED) def put_dummy_variables(atr_value, lst_values, stu_features, feat_name, \ feat_name_lst): """ put a given atribute as dummy variable make sure the feature name list remain correct receives: 1. atribute value 2. list of possible values for the attribute 3. list of students variable that we must append attributes 4. atribute name 5. list of features name returns: nothing """ if not (feat_name in feat_name_lst): # repeat as long as there we'll be dummy variables for i in range(len(lst_values)): feat_name_lst.append(feat_name) # make sure dummy variable is correct try: assert(atr_value in lst_values) except: print(atr_value) exit() # build list of dummy variables dummy_lst = [] for i in range(len(lst_values)): dummy_lst.append(0) # change dummy variable for the list the student is in ind = lst_values.index(atr_value) dummy_lst[ind] = 1 # append to student features list for elem in dummy_lst: stu_features.append(elem)
#!/usr/bin/python3.4 # python file to make test related to the files given to me from insertion import * # constants # maximum number of values a column possess MAX_DIFF_VALUES = 100000 def study_row(row, index, diff_values): """ analyses if the column with given index in the row passed presents a value different from diff_values. If it does, append to diff_values receives: 1. a row of a csv file 2. an index, 3. a list of different values found so far """ global lines_read, valid_lines # return case of empty row if len(row) == 0: return lines_read += 1 # get row content - the row is a list with possibly more than one entry content = row[0] for i in range(1, len(row)): content += row[i] # split content in list info = content.split(';') # skip if not from graduation if info[DEGREE_IND].lower() != "graduacao": return valid_lines += 1 if not (info[index] in diff_values): diff_values.append(info[index]) # shows how many different values a column has for a given year and semester def test_column_values(index): """ print all diferent values found for a particular database column receives: 1. index of the column returns: nothing """ global lines_read, valid_lines # file for writing the different values encontered log = open('../logs/dif_values_index_' + str(index) + '.txt', 'w') log.write("different values encountered for the csv file\n") file_name = CSV_PATH + FILE_NAME + EXTENSION # get connection conn = get_conn() # different values found so far diff_values = [] # read line by line, parsing the results and putting on database with open(file_name, newline = '', encoding = ENCODING) as fp: reader = csv.reader(fp) # iterate through the rows, inserting in the table for row in reader: study_row(row, index, diff_values) if len(diff_values) > MAX_DIFF_VALUES: print("too much diff_values") # show diff values diff_values.sort() log.write(str(diff_values)) # close connection close_conn(conn) # close file pointer fp.close() print("lines: %s valid_lines: %s" % (lines_read, valid_lines)) # test values for some columns in the database def test_database(): """ test the values for columns in database returns: nothing receives: nothing """ # list of index we are considering - for this study, were not considering #CODE_IND and BDAY_IND ind_list = [] #ind_list.append(SEX_IND) #ind_list.append(DEGREE_IND) #ind_list.append(COURSE_IND) #ind_list.append(LOCAL_IND) #ind_list.append(QUOTA_IND) #ind_list.append(SCHOOL_IND) #ind_list.append(RACE_IND) #ind_list.append(YEAR_IN_IND) #ind_list.append(SEM_IN_IND) #ind_list.append(YEAR_END_IND) #ind_list.append(YEAR_END_IND) #ind_list.append(SUB_CODE_IND) #ind_list.append(SUB_NAME_IND) #ind_list.append(WAY_IN_IND) #ind_list.append(WAY_OUT_IND) for ind in ind_list: test_column_values(ind) if __name__ == "__main__": #test_database() insert_database() #clean_database()
'''18. Faça um Programa para um caixa eletrônico. O programa deverá perguntar ao usuário a valor do saque e depois informar quantas notas de cada valor serão fornecidas. As notas disponíveis serão as de 1, 5, 10, 50 e 100 reais. O valor mínimo é de 10 reais e o máximo de 600 reais. O programa não deve se preocupar com a quantidade de notas existentes na máquina. Exemplo 1: Para sacar a quantia de 256 reais, o programa fornece duas notas de 100, uma nota de 50, uma nota de 5 e uma nota de 1; Exemplo 2: Para sacar a quantia de 399 reais, o programa fornece três notas de 100, uma nota de 50, quatro notas de 10, uma nota de 5 e quatro notas de 1.''' saque = int(input("Digite o valor do saque: ")) if saque < 10 or saque > 600: print("Valor invalido") cem = int((saque/100)) cinquenta = int((saque%100)/50) dez = int(((saque%100)%50)/10) cinco = int((((saque%100)%50)%10)/5) um = int(((((saque%100)%50)%10)%5)/1) print(f"{cem} notas de R$100") print(f"{cinquenta} notas de R$50") print(f"{dez} notas de R$10") print(f"{cinco} notas de R$5") print(f"{um} notas de R$1")
'''21. Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: "Telefonou para a vítima?" "Esteve no local do crime?" "Mora perto da vítima?" "Devia para a vítima?" "Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participação da pessoa no crime. Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente".''' print("Digite 1 para 'sim' e 0 para 'não'.") qt1 = int(input("Telefonou para a vitima? ")) qt2 = int(input("Esteve no local do crime? ")) qt3 = int(input("Mora perto da vítima? ")) qt4 = int(input("Devia para a vítima? ")) qt5 = int(input("Já trabalhou com a vítima? ")) if (qt1+qt2+qt3+qt4+qt5) == 2: print("Suspeito") elif 3 <= (qt1+qt2+qt3+qt4+qt5) <= 4: print("Cúmplice") elif (qt1+qt2+qt3+qt4+qt5) == 5: print("Assassino") else: print("Inocente")
# Ex.31 Python Progressivo # O Sr. Manoel Joaquim expandiu seus negócios para além dos negócios de 1,99 e agora possui # uma loja de conveniências. Faça um programa que implemente uma caixa registradora rudimentar. O programa deverá # receber um número desconhecido de valores referentes aos preços das mercadorias. Um valor zero deve ser informado # pelo operador para indicar o final da compra. O programa deve então mostrar o total da compra e perguntar o valor # em dinheiro que o cliente forneceu, para então calcular e mostrar o valor do troco. Após esta operação, o programa # deverá voltar ao ponto inicial, para registrar a próxima compra. A saída deve ser conforme o exemplo abaixo: Lojas # Tabajara Produto 1: R$ 2.20 Produto 2: R$ 5.80 Produto 3: R$ 0 Total: R$ 8.00 Dinheiro: R$ 20.00 Troco: R$ 12.00 ... print("Lojas Tabajara") count = 1 total = 0 while count > 0: count += 1 print("Produto ", count, ": ", end=" ") preço = float(input()) total += preço if preço == 0: print("Total: R$%.2f"% total) dinheiro = float(input("Dinheiro recebido R$: ")) print("Troco = R$%.2f"% (dinheiro - total))
# Exercicio 1 de Funções # Escreva um script que pergunta ao usuário se ele deseja converter uma temperatura de grau # Celsius para Farenheit ou vice-versa. Para cada opção, crie uma função. Crie uma terceira, que é um menu para o # usuário escolher a opção desejada, onde esse menu chama a função de conversão correta. def fahrenheit(): x = float(input("Digite o numero que será convertido de Graus Celcius para Fahrenheit: ")) return (x * 1.8) + 32 def celcius(): x = float(input("Digite o numero que será convertido de Fahrenheit para Graus Celcius: ")) return (x - 32) / 1.8 def menu(): while True: escolha = int(input("Qual conversão deseja fazer? (1) Celcius em Fahrenheit (2) Fahrenheit em Celcius: ")) if escolha == 1: a = fahrenheit() print("O resultado é: ", a) elif escolha == 2: b = celcius() print("O resultado é: ", b) else: print("Opção incorreta, digite novamente: ") menu()
# Decorator concept practice class Testing_decorator: def __init__(self) -> None: pass def decorator(self,fun): def dec(): print('Before function to be decorated') fun() print('After the function decorated') return dec def dec_fun(): print('Function decorated') def test_dec(test): def wrap(): print('Before ') test() print('wawaawaawawaaaaaaaaaaaa/...!') return wrap @test_dec def test_direct(): print('Testing direct method of decorating of the function') if __name__ == '__main__': t = Testing_decorator() # Using class and method as decorator s = t.decorator(dec_fun) s() test_direct()
from _collections import deque stack = deque() # print(dir(stack)) stack.append('500') stack.append('600') # print("Stack : ", stack) class Stack: def __init__(self): self.container = deque() def push(self, value): self.container.append(value) def pop(self): return self.container.pop() def peek(self): return self.container[-1] def is_empty(self): return len(self.container) == 0 def size(self): return len(self.container) objStack = Stack() objStack.push(200) objStack.push('Bc') print(objStack.size()) print(objStack.is_empty()) objStack.pop() print(objStack.peek())
#TASK SEVEN: CLASSES AND ONJECTS ''' 1. Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2*C*D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. ''' import math def sqrtof(C = 50, H = 30): val = [] D = [x for x in input("Enter number seperated by commas: ").split(',')] for i in D: Q = math.sqrt(2*C*int(i)/H) val.append(round(Q, 2)) print(val) sqrtof() ''' 2. Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have an area function which can print the area of the shape where Shape’s area is 0 by default. ''' class Shape(): def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self, length): Shape.__init__(self) self.length = length def area(self): return self.length*self.length S = Square(5) print(S.area()) ''' 3. Create a class to find the three elements that sum to zero from a set of n real numbers. Input array: [-25,-10,-7,-3,2,4,8,10] Output: [[-10,2,8],[-7,-3,10]] ''' class Solution(object): def threesum(self, nums): res = [] nums.sort() length = len(nums) for i in range(length-2): if i > 0 and nums[i] == nums[i-1]: continue l = i+1 r = length-1 while l < r: total = nums[i] + nums[l] + nums[r] if not total: res.append([nums[i], nums[l], nums[r]]) while nums[l] == nums[l + 1]: l += 1 while nums[r] == nums[r - 1]: r -= 1 l += 1 r -= 1 elif total < 0: l = l + 1 else: r = r - 1 return res nums = [-25,-10,-7,-3,2,4,8,10] s = Solution().threesum(nums) print(s) ''' 4. What is the output of the following code? Explain your answer as well. ''' class Test: def __init__(self): self.x = 0 class Derived_Test(Test): def __init__(self): self.y = 1 def main(): b = Derived_Test() print(b.x,b.y) main() ''' Answer: It will give us an Error because class Derived_Test inherits class Test variable x is not inherited we have to mention the Test.__init__(self) in the Derived_Test class. ''' # Output: # 0 1 # Reason: when main() function is called, object b of Derived_Test # class is created which also inherits the properties of Test class. class A: def __init__(self, x= 1): self.x = x class der(A): def __init__(self,y = 2): super().__init__() self.y = y def main(): obj = der() print(obj.x, obj.y) main() ''' Answer : 1 2 In this code invoking method is properly implemented i.e. super().__init__() ''' class A: def __init__(self,x): self.x = x def count(self,x): self.x = self.x+1 class B(A): def __init__(self, y=0): A.__init__(self, 3) self.y = y def count(self): self.y += 1 def main(): obj = B() obj.count() print(obj.x, obj.y) main() ''' Answer: 3 1 invoking method is properly implemented as we are class B inherits properties of class A ''' class A: def __init__(self): self.multiply(15) print(self.i) def multiply(self, i): self.i = 4 * i; class B(A): def __init__(self): super().__init__() def multiply(self, i): self.i = 2 * i; obj = B() ''' Answer: 30 The Class B overrides parent class A ''' ''' 5. Create a Time class and initialize it with hours and minutes. Make a method addTime which should take two time object and add them. E.g.- (2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min) Make a method displayTime which should print the time. Make a method DisplayMinute which should display the total minutes in the Time. E.g.- (1 hr 2 min) should display 62 minute. ''' class Time(object): def __init__(self, hours, minutes): self.hours = hours self.minutes = minutes def addTime(t1, t2): x = Time(0, 0) x.hours = t1.hours + t2.hours x.minutes = t1.minutes + t2.minutes while x.minutes >= 60: x.hours += 1 x.minutes -= 60 return x def displayTime(self): print(f"Time is, {self.hours} hours and {self.minutes} minutes.") def displayMinutes(self): print((self.hours*60) + self.minutes, "minutes") a = Time(2, 50) b = Time(1, 20) c = Time.addTime(a, b) d = Time(1, 2) c.displayTime() d.displayMinutes() ''' 6. Write a Person class with an instance variable, , and a constructor that takes an integer, , as a parameter. The constructor must assign to after confirming the argument passed as is not negative; if a negative argument is passed as , the constructor should set to and print Age is not valid, setting age to 0.. In addition, you must write the following instance methods: 1. yearPasses() should increase the instance variable by . 2. amIOld() should perform the following conditional actions: ○ If , print You are young.. ○ If and , print You are a teenager.. ○ Otherwise, print You are old.. Sample Input: 4 -1 10 16 18 Sample Output: Age is not valid, setting age to 0. You are young. You are young. You are young. You are a teenager. You are a teenager. You are old. You are old. You are old. ''' class Person: def __init__(self, Age): if Age < 0: self.age = 0 print("Age is not valid, setting age to 0") else: self.age = Age def yearPasses(self): self.age += 1 def amIOLD(self): if self.age<13: print("You are Young. ") elif 13 <= self.age < 18: print("You are a Teenager. ") else: print("You are old. ") x = int(input("Enter a count")) for i in range(0, x): a = int(input("Please Enter your age: ")) p = Person(a) p.amIOLD() for j in range(0, 3): p.yearPasses() p.amIOLD()
"""Q.1- Print anything you want on screen.""" print('Hello World') #String always writeen in double or single quotes print(1) #The numeric value can be printed with or without double or single quotes """Q.2- Join two strings using '+'.E.g.-"Acad"+"View”""" a = "Acad" #"Acad" is being assigned to variable a which is of string type made at runtime or dynamically b = "View" #"View is being assigned to b which is of string type made at runtime or dynamically c = a+b #"+" operator helps to concatenate two strings but it is possible only when both side have same datatype variables print(c) """Q.3- Take the input of 3 variables x, y and z . Print their values on screen. """ a = input("Enter the 1 input") #This take input of both as numbers and alphabets but inform of string b = input("Enter the 2 input") c = int(input("Enter the third input")) #The int type cast will take input only numericals as they are of base 10 not the strings print("1 input ",a) print("2 input ",b) print("3 input ",c) """Q.4- Print “Let’s get started” on screen.""" print('“Let’s get started”') #A string print line can't contain same quote in one line so we have to make use of different quotes """Q.5- Print the following values using placeholders. s=”Acadview” course=”Python” fees=5000""" s = "Acadview" course = "Python" fees = 5000 print ("%s %s %s"%(s,course,fees)) #A placeholder make it easy to insert the value in a line just by using specific placeholder """Q.6- Let’s do some interesting exercise: name=”Tony Stark” salary=1000000 print(‘%s’’%d’)%(____ ,____)""" name="Tony Stark" salary=1000000 print('%s"%d'%(name,salary)) ##As in given question the print statement was not containing 2 brackets so as to close statement in print function so after puting the brackets it prints th statement """Q.6- Find the area of circle pi = 3.14 Take radius as input from user Print the area of circle""" pi = 3.14 radius = int(input("Enter the radius of circle")) area = pi*(radius**2) #(**)Operator is used for the power of a given number print("Area of circle = ",area)
# -*- coding: utf-8 -*- """ Created on Thu Oct 31 16:55:59 2019 @author: user4 """ # Importing required libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #Importing the dataset df = pd.read_csv('Position_Salaries.csv') X = df.iloc[:,1:2].values y = df.iloc[:,2].values # Creating a linear regression and fitting our data perfectly from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X,y) y_pred = regressor.predict(X) plt.plot(X,y_pred,'r') plt.plot(X,y,'bo') #Ouch, That didn't go at all as we expected, let's try polynomial features for gods sake # Creating polynomial features for the dataset from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree = 4) X_poly = poly.fit_transform(X) # Creating a linear regression on polynomial features i.e. polynomial linear regression :p from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_poly,y) y_pred_poly = regressor.predict(X_poly) plt.plot(X,y_pred_poly,'r') plt.plot(X,y,'bo') #Welll, I hope that's a good way to use a polynomial Linear Regression
import sys from functools import wraps _caches = [] class _Cache(dict): """A dict() subclass that appends a self-reference to _caches""" def __init__(self, *args, **kwargs): super(_Cache, self).__init__(*args, **kwargs) _caches.append(self) def cache(*keys): """cache decorator Caches input and output of a function. If arguments are passed to the decorator, take those as key for the cache. Otherwise use the function arguments and sys.argv as key. sys.argv is used here because of user-written code like this: import sys my_variable = sys.argv[1] def my_function(): print(my_variable) Depending on the state of sys.argv during execution of the module, the outcome of my_function() changes. """ def cacheWrapper(func): localCache = _Cache() @wraps(func) def cachedFuncWrapper(*args, **kwargs): if keys: key = str(keys) else: key = str(args) + str(kwargs) + str(sys.argv) if key not in localCache: localCache[key] = func(*args, **kwargs) return localCache[key] return cachedFuncWrapper return cacheWrapper def clearAllCaches(): for cache in _caches: cache.clear()
"""Toosl dealing with time, such as timing a function and plotting a progress bar.""" import time as _time import datetime as _datetime import sys as _sys class Progress(object): """Simple progress bar implementation""" def __init__(self, message, number_of_iterations, output_period=1.0): self._message = message self._number_of_iterations = number_of_iterations self._tasks_completed = 0 self._time = _time.time() self._last_iteration_time = 0.0 self._expected_time_left = 0.0 self._last_output_time = 0.0 self._last_output_index = 0 self._max_output_period = output_period def start(self): """Call before starting task.""" self._tasks_completed = 0 self._time = _time.time() self._last_output_time = self._time def finished(self): """Call when task is done.""" _sys.stdout.write("\n") def iteration_completed(self): """Call after every iteration. This function plots the otuput if a significant time passed since last plot.""" self._tasks_completed += 1 new_time = _time.time() self._last_iteration_time = new_time - self._time self._time = new_time self._expected_time_left = self._last_iteration_time * (self._number_of_iterations - self._tasks_completed) def print_message(self, always_output=False): new_time = self._time if always_output or new_time > (self._last_output_time + self._max_output_period): bar_length = 50 done_length = int(float(self._tasks_completed) / float(self._number_of_iterations) * bar_length) not_done_length = bar_length - done_length _sys.stdout.write("\r[{done}{not_done}] {time_left} seconds left".format(done="#"*done_length, not_done="-"*not_done_length, time_left=int(self._expected_time_left))) _sys.stdout.flush() self._last_output_time = new_time self._last_output_index = self._tasks_completed @property def time_left(self): return self._expected_time_left class StopWatch(object): """Uses wall time.""" def __init__(self): self._running = False self._start_time = None self._end_time = None self._time_diff = None def start(self): """Start watch""" self._running = True self._start_time = _time.time() def stop(self): """Stop and reset watch""" if not self._running: raise RuntimeError("Timer needs to be running to be stopped") self._running = False self._end_time = _time.time() self._time_diff = self._end_time - self._start_time def time(self): """The time in seconds that the clock was running.""" if self._running: self._time_diff = _time.time() - self._start_time return self._time_diff def time_string(self): """Nicely formated string of the time the clock was running.""" time_diff = self.time() if time_diff < 1.: return "{0} ms".format(time_diff*1000.) else: return str(_datetime.timedelta(seconds=time_diff))
miles = float(input()) cost_per_gallon = float(input()) miles20 = 20 * (1.0 / miles) * cost_per_gallon miles75 = 75 * (1.0 / miles) * cost_per_gallon miles500 = 500 * (1.0 / miles) * cost_per_gallon print('{:.2f} {:.2f} {:.2f}'.format(miles20, miles75, miles500))
# 获取元组的一些基本信息 tuple1 = (9, 1, -4, 3, 7, 11, 3) print('tuple1的长度 =', len(tuple1)) print('tuple1里的最大值=', max(tuple1)) print('tuple1里的最小值 =', min(tuple1)) print('tuple1里3这个元素一共出现了{}次'.format(tuple1.count(3))) # 元组的改变???? # tuple2 = ('a', 'c', 'd') # # tuple2[1] = 2 # 元组翻转 ?? # tuple3 = (1, 2, 3) # tuple3.reverse() # 元组排序 ?? # # tuple4 = (9, 1, -4, 3, 7, 11, 3) # tuple4.sort(reverse=True) print(tuple1.index(9))
# import pickle # # class People: def __init__(self, name, age): self.name = name self.age = age def sayhi(self): print("Hi, my name is {}, and I'm {}".format( self.name, self.age )) # # # p1 = People(name='Jack', age=30) # f = open('p1', 'wb') # pickle.dump(p1, f) # f.close() # 序列化对象的加载 import pickle f = open('p1', 'rb') p2 = pickle.load(f) f.close() print(p2, p2.name, p2.age) p2.sayhi()
a = [1, 2, 3, 4] # def f(x, y): # return x + y # print([item for item in map(lambda x: x * x, a)]) # from functools import reduce # # # a = reduce(lambda x, y: x + y, a) # # print(a) # a = filter(lambda x: x % 2 == 1, a) # # print([item for item in filter(lambda x: x % 2 == 1, a)]) # print([item for item in a if item % 2 == 1])
# a = [1, 2, 3, 4] # # print(max(a)) def demo(): print('hello world') print('demo') def demo1(a, b): print(a, b) def sum(a, b): return a + b def my_max(a): if not a: return None max_value = a[0] for item in a: if item > max_value: max_value = item return max_value a = [1, 4, 5, 2,3,8,10] print(my_max(a))
ghit = int(input("Enter Your Height(cm) ? ")) weight = int(input("Enter Your Weight(kg) ? ")) height = ghit / 100 BMI = weight / (height*height) if BMI < 16 : print("You are Severely underweight!") elif 16 < BMI < 18.5 : print("You are underweight!") elif 18.5 < BMI < 25 : print("You are normal!") elif BMI >= 30 : print("You are obese!") print(BMI, "is your BMI. ")
numb_1 = int(input("Введите первое целое число: ")) numb_2 = int(input("Введите второе целое число: ")) if numb_1 != numb_2: print("Числа не равны") if numb_1 > numb_2: print("Первое число больше второго") elif numb_2 < numb_1: print("Первое число меньше второго") elif numb_1 == numb_2: print("Числа равны")
#!/usr/bin/env python # coding: utf-8 # In[3]: import json import sys # In[4]: #Returns the team higher in the ladder and the difference in places between the pair. def bestestTeam (teamIDs, standings): homeName=""; awayName=""; #Clunky, generate a team/ID lookup table to be imported into all bots. homePoints=-1; awayPoints=-1 for team in standings['standings'][0]['table']: if team['team']['id'] == teamIDs[0]: homeName = team['team']['name'] homePoints = team['points'] elif team['team']['id'] == teamIDs[1]: awayName = team['team']['name'] awayPoints = team['points'] if(homePoints < 0 or awayPoints < 0): return "Unable to grab points for one or both teams" if(homePoints > awayPoints): return (homeName, homePoints - awayPoints) elif(homePoints < awayPoints): return (awayName, awayPoints - homePoints) else: return ("Draw", 0) # In[2]: #Takes the schedule and standing parsed dictionaries. Runs through the schedule, pulling out team-ids and running the #bestestTeam function to return the higher team. Returns a list of pairs returned from the iterated bestestTeam function. #i.e. (Winning team name, points seperating) def doTableBotPredict(matchday, standings): predictions=[] for match in matchday['matches']: predictions.append( bestestTeam((match['homeTeam']['id'], match['awayTeam']['id']), standings) ) return predictions # In[5]: #Runs the prediction. The argument is a list of standings .json file and schedule .json file to be parsed in. Prints the #resulting predictions in formatted strings. def main(args): with open (args[0], 'r') as f: matchday = json.load(f) with open (args[1], 'r') as g: standings = json.load(g) for p in doTableBotPredict(matchday,standings): print ("%s, %d point(s) seperate the teams" % (p[0], p[1])) # In[7]: #If run as a standalone script. Note the argv[1:] skips the first argument which is the script name if __name__=="__main__": main(sys.argv[1:]) # In[ ]:
#!/usr/bin/env python3 # # egg.py # Egg timer program in Python. # Does not employ using C executables exported functions # import time import sys import os PATH_FILE = "/tmp/egg.data" menu = """ 1. Start Egg Timer 2. Elapsed Time 3. Time Remaining 4. Stop Egg Timer Enter Choice: """ def get_menu_selection(): while True: response = input(menu) try: value = int(response) if value >= 1 and value <= 4: return value except: continue def start_egg_timer(duration = 60): """ 1. Start Egg Timer Write a timestamp and a cooking duration to a tmp file: """ ts = int(time.time()) #1590824805.3866053 1590824805 s = "{},{}".format(ts,duration) with open(PATH_FILE, "w") as fout: fout.write(s) print("Egg Cooking Duration: {}".format(duration)) def elapsed_time(): """ 2. Elapsed Time Read the data from /tmp/egg.data Calculate the elapsed time """ try: with open(PATH_FILE, "r") as fin: data = fin.read() data_list = data.split(",") ts_begin = int(data_list[0]) ts_now = int(time.time()) return (ts_now - ts_begin) except: return 0 def time_remaining(): """ 3. Time Remaining(): Read the data from /tmp/egg.data Calculate the remaining time """ try: with open(PATH_FILE, "r") as fin: data = fin.read() data_list = data.split(",") ts_begin = int(data_list[0]) ts_duration = int(data_list[1]) ts_now = int(time.time()) return ((ts_begin + ts_duration) - ts_now) except: return 0 def stop_egg_timer(): """ 4. Stop Egg Timer If it exists delete the /tmp/ file """ try: os.remove(PATH_FILE) except: pass sys.exit("Enjoy your eggs.") def main(): while True: value = get_menu_selection() print() #"value:", value) if value == 1: """ 1. Start Egg Timer """ try: if len(sys.argv) > 1: duration = int(sys.argv[1]) start_egg_timer(duration) else: start_egg_timer() except: start_egg_timer() if value == 2: """ 2. Elapsed Time """ elapsed = elapsed_time() print("Elapsed Time: {}".format(elapsed)) if value == 3: """ 3. Time Remaining """ remain = time_remaining() print("Time Remaining: {}".format(remain)) if value == 4: """ 4. Stop Egg Timer """ stop_egg_timer() if __name__ == "__main__": main()
#!/usr/bin/env python3 # -*- config: utf-8 -*- from tkinter import * root = Tk() text = Text(width=100, height=10) text.pack(side=LEFT) scroll = Scrollbar(command=text.yview) scroll.pack(side=LEFT, fill=Y) text.config(yscrollcommand=scroll.set) root.mainloop()
# implementation of selection sort # s is the array to be sorted def selectionsort(s): for i in range(len(s)): min = i; for j in range(i, len(s)): if s[j] < s[min]: min = j s[i], s[min] = s[min], s[i] return s # driver code to test above s = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] print 'Given array is ', s selectionsort(s) print '\nSorted array is ', s
slova=[] s=input('Введите слово:') while s: slova.append(s) s=input('Введите слово:') with open ('freq.txt','r+',encoding='utf-8') as f: t=f.readlines() for slovo in slova: x=0 for line in t: c=0 for i in line: if i=='|': c+=1 if c==2: word,part,freq=line.split('| ') if word==slovo+' 'or word==slovo: print(part,freq,sep=';',end='\n') x=1 if x==0: print('Слово '+slovo+' в словаре отсутствует.')
""" Plot Bands of Satellite Imagery with EarthPy ================================================================== Learn how to use the EarthPy ``plot_bands()`` function to quickly plot raster bands for an image. ``Plot_bands()`` can be used to both plot many bands with one command with custom titles and legends OR to plot a single raster layer with (or without) a legend. """ ############################################################################### # Plot Raster Data Layers Using EarthPy # -------------------------------------- # # .. note:: # The examples below will show you how to use the ``plot_bands()`` function # to plot individual raster layers in images using python. To plot rgb data, # read help documentation related to ``ep.plot_rgb()``. # # In this vignette, you will use Landsat 8 data. To begin, you will create a # stack of bands using Landsat 8 data. You will then plot the raster layers. ############################################################################### # Import Packages # --------------- # # In order to use the ``plot_bands()`` function with Landsat 8 data, the # following packages need to be imported. import os from glob import glob import matplotlib.pyplot as plt import earthpy as et import earthpy.spatial as es import earthpy.plot as ep ############################################################################### # Import Example Data # ------------------- # # To get started, make sure your directory is set. Then, create a stack from # all of the Landsat .tif files (one per band). # Get data for example data = et.data.get_data("vignette-landsat") # Set working directory os.chdir(os.path.join(et.io.HOME, "earth-analytics")) # Stack the Landsat 8 bands # This creates a numpy array with each "layer" representing a single band # You can use the nodata= parameter to mask nodata values landsat_path = glob( os.path.join( "data", "vignette-landsat", "LC08_L1TP_034032_20160621_20170221_01_T1_sr_band*_crop.tif", ) ) landsat_path.sort() array_stack, meta_data = es.stack(landsat_path, nodata=-9999) ############################################################################### # Plot All Bands in a Stack # -------------------------- # # When you give ``ep.plot_bands()`` a three dimensional numpy array, # it will plot all layers in the numpy array. You can create unique titles for # each image by providing a list of titles using the ``title=`` parameter. # The list must contain the same number of strings as there are bands in the # stack. titles = ["Ultra Blue", "Blue", "Green", "Red", "NIR", "SWIR 1", "SWIR 2"] # sphinx_gallery_thumbnail_number = 1 ep.plot_bands(array_stack, title=titles) plt.show() ############################################################################### # Plot One Band in a Stack # ------------------------ # # If you give ``ep.plot_bands()`` a one dimensional numpy array, # it will only plot that single band. You can turn off the # colorbar using the ``cbar`` parameter (``cbar=False``). ep.plot_bands(array_stack[4], cbar=False) plt.show() ############################################################################### # Turn On Scaling # ----------------- # # ``ep.plot_bands()`` does not scale imagery to a 0-255 scale by default. # However, often this range of values makes it easier for matplotlib to plot # the data. To turn on scaling, set the scale parameter to ``True``. Below you # plot band 5 of the satellite imagery with scaling turned on in order to see # the data without the values being modified. ep.plot_bands(array_stack[4], cbar=False, scale=True) plt.show() ############################################################################### # Adjust the Number of Columns for a Multi Band Plot # --------------------------------------------------- # # The number of columns used while plotting multiple bands can be changed in # order to change the arrangement of the images overall. ep.plot_bands(array_stack, cols=2) plt.show()
""" Calculate and Classify Normalized Difference Results with EarthPy ================================================================== Learn how to calculate and classify normalized difference indices in Python using EarthPy. This example shows how to calculate and classify the normalized difference vegetation index (NDVI) using Landsat 8 data. """ ############################################################################### # Calculating Normalized Difference in Python Using EarthPy # --------------------------------------------------------- # # .. note:: # The examples below will show you how to use the ``normalized_diff()`` function # to calculate the normalized difference vegetation index (NDVI), a commonly # used remotely sensed index for quantifying vegetation health. # # The example below walks you through a typical workflow for calculating the normalized # difference vegetation index (NDVI) using Landsat 8 data with EarthPy. NDVI provides # a measure of healthy vegetation and ranges in value from -1 to 1. Values closer to # 1 represent healthy, green vegetation. NDVI can be calculated from Landsat 8 data # using band 4 (red) and band 5 (near-infrared). # # First, you will create a stack of bands using Landsat 8 data and then calculate # NDVI using the ``normalized_diff()`` function. Then, you will plot the NDVI results # using a colorbar legend with continuous values. Last, you will classify the NDVI # results using threshold values and plot the classified data with a categorical legend. ############################################################################### # Import Packages # --------------- # # To begin, import the needed packages. You will use a combination of several EarthPy # modules including spatial and plot. import os from glob import glob import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import earthpy as et import earthpy.spatial as es import earthpy.plot as ep # Get data and set your home working directory data = et.data.get_data("vignette-landsat") ############################################################################### # Import Example Data # ------------------- # # To get started, make sure your directory is set. Then, create a stack from all of # the Landsat .tif files (one per band). The nodata value for Landsat 8 is # ``-9999`` so you can use the ``nodata=`` parameter when you call the # ``stack()`` function. os.chdir(os.path.join(et.io.HOME, "earth-analytics")) # Stack the Landsat 8 bands # This creates a numpy array with each "layer" representing a single band landsat_path = glob( "data/vignette-landsat/LC08_L1TP_034032_20160621_20170221_01_T1_sr_band*_crop.tif" ) landsat_path.sort() arr_st, meta = es.stack(landsat_path, nodata=-9999) ############################################################################### # Calculate Normalized Difference Vegetation Index (NDVI) # ------------------------------------------------------- # # You can calculate NDVI for your dataset using the # ``normalized_diff`` function from the ``earthpy.spatial`` module. # Math will be calculated (b1-b2) / (b1 + b2). # Landsat 8 red band is band 4 at [3] # Landsat 8 near-infrared band is band 5 at [4] ndvi = es.normalized_diff(arr_st[4], arr_st[3]) ############################################################################### # Plot NDVI With Colorbar Legend of Continuous Values # ---------------------------------------------------- # # You can plot NDVI with a colorbar legend of continuous values using the # ``plot_bands`` function from the ``earthpy.plot`` module. titles = ["Landsat 8 - Normalized Difference Vegetation Index (NDVI)"] # Turn off bytescale scaling due to float values for NDVI ep.plot_bands(ndvi, cmap="RdYlGn", cols=1, title=titles, vmin=-1, vmax=1) ############################################################################### # Classify NDVI # ------------- # # Next, you can categorize (or classify) the NDVI results into useful classes. # Values under 0 will be classified together as no vegetation. Additional classes # will be created for bare area and low, moderate, and high vegetation areas. # Create classes and apply to NDVI results ndvi_class_bins = [-np.inf, 0, 0.1, 0.25, 0.4, np.inf] ndvi_landsat_class = np.digitize(ndvi, ndvi_class_bins) # Apply the nodata mask to the newly classified NDVI data ndvi_landsat_class = np.ma.masked_where( np.ma.getmask(ndvi), ndvi_landsat_class ) np.unique(ndvi_landsat_class) ############################################################################### # Plot Classified NDVI With Categorical Legend - EarthPy Draw_Legend() # -------------------------------------------------------------------- # # You can plot the classified NDVI with a categorical legend using the # ``draw_legend()`` function from the ``earthpy.plot`` module. # Define color map nbr_colors = ["gray", "y", "yellowgreen", "g", "darkgreen"] nbr_cmap = ListedColormap(nbr_colors) # Define class names ndvi_cat_names = [ "No Vegetation", "Bare Area", "Low Vegetation", "Moderate Vegetation", "High Vegetation", ] # Get list of classes classes = np.unique(ndvi_landsat_class) classes = classes.tolist() # The mask returns a value of none in the classes. remove that classes = classes[0:5] # Plot your data fig, ax = plt.subplots(figsize=(12, 12)) im = ax.imshow(ndvi_landsat_class, cmap=nbr_cmap) ep.draw_legend(im_ax=im, classes=classes, titles=ndvi_cat_names) ax.set_title( "Landsat 8 - Normalized Difference Vegetation Index (NDVI) Classes", fontsize=14, ) ax.set_axis_off() # Auto adjust subplot to fit figure size plt.tight_layout()
from math import * def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('请输入正确的年龄') if x > 70: return '你老了' elif x > 30: return '你成年了' else: return '小孩别闹' # y = int(input('age')) # print(my_abs(y)) def quadratic(a, b, c): delta = b**2 - 4 * a * c if not isinstance(a, (int, float)) and not isinstance( b, (int, float)) and not isinstance(c, (int, float)): raise TypeError('请输入正确的系数') if delta >= 0: x1 = (-b + sqrt(delta)) / (2 * a) x2 = (-b - sqrt(delta)) / (2 * a) return x1, x2 else: return '无解,b的平方是小于4ac的' # x = float(input('请输入2次项系数a')) # y = float(input('请输入1次项系数b')) # z = float(input('请输入常数项系数c')) # print('解为:', quadratic(x,y,z)) # 初始值 def add_end(L=None): if L is None: L = [] L.append('END') return L print(add_end(), add_end([1, 2, 3])) # 可变参数 # 定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号 def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc(1, 2, 3, 4)) # 把list或tuple的元素变成可变参数传进去 nums = [1, 2, 3] print(calc(*nums)) print(calc(*(1, 2, 3))) # 关键字参数 def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) person('Michael', 30) person('Bob', 35, city='Beijing') extra = {'city': 'Beijing', 'job': 'Engineer'} person('Jack', 24, **extra) # 命名关键字参数 # *后面的参数被视为命名关键字参数。 # 命名关键字参数必须传入参数名 # 使用命名关键字参数时,要特别注意,如果没有可变参数, # 就必须加一个*作为特殊分隔符。如果缺少*, # Python解释器将无法识别位置参数和命名关键字参数 def person(name, age, *, city, job): print(name, age, city, job) person('Jack', 24, city='Beijing', job='Engineer') # 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了: def person(name, age, *args, city, job): print(name, age, args, city, job) person('Bob', 35, 33, city='Beijing', job='Engineer') # 参数组合 # 必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用 def f1(a, b, c=0, *arga, **kw): print('a=', a, 'b=', b, 'c=', c, 'arga=', arga, 'kw=', kw) def f2(a, b, c=0, *, d, **kw): print('a=', a, 'b=', b, 'c=', c, 'd=', d, 'kw=', kw) f1(1, 2) f1(1, 2, c=3) f1(1, 2, 3, 'a', 'b') f1(1, 2, 3, 'a', 'b', x=99) f2(1, 2, d=99, ext=None) args = (1, 2, 3, 4) kw = {'d': 99, 'x': '#'} f1(*args, **kw) args = (1, 2, 3) kw = {'d': 88, 'x': '#'} f2(*args, **kw) # 要注意定义可变参数和关键字参数的语法: # *args是可变参数,args接收的是一个tuple; # **kw是关键字参数,kw接收的是一个dict。 # 可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过*args传入:func(*(1, 2, 3)); # 关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过**kw传入:func(**{'a': 1, 'b': 2})。 # 递归函数 def fact(n): if n == 1: return 1 return n * fact(n - 1) print(fact(1), fact(5)) # 尾递归 def fact(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product) print(fact(5)) # 汉诺塔:2^n – 1 # 若n为偶数,按顺时针方向依次摆放 A B C # 若n为奇数,按顺时针方向依次摆放 A C B。 def move(n, a, b, c): if n == 1: print('%s --> %s' % (a, c)) return else: pass if n % 2 == 1: move(n - 2, a, b, c) print('%s --> %s' % (a, b)) move(n - 2, c, a, b) print('%s --> %s' % (a, c)) move(n - 2, b, c, a) print('%s --> %s' % (b, c)) return move(n - 2, a, b, c) else: move(n - 1, a, c, b) print('%s --> %s' % (a, c)) return move(n - 1, b, a, c) move(2, 'A', 'B', 'C') def func1(): global x print('x is', x) x = 2 print('changed local x to', x) x = 50 func1() print('value of x is', x) # print(divmod(13, 5)) # 返回(2,3) def foo(nums): evens = [] for num in nums: if num % 2 == 0: evens.append(nums) return evens foo([10, 2, 4, 5, 7]) def foo(length, width, height=1.0): return length * width * height
# coding=utf-8 """ Created on 2017-11-28 @author: Palesnow 功能:访问者模式 网址:https://yq.aliyun.com/articles/71075?utm_campaign=wenzhang&utm_medium=article&utm_source=QQ-qun&2017315&utm_content=m_13628 实例:药房业务系统 """ # 药品类 class Medicine: name = "" price = 0.0 def __init__(self, name, price): self.name = name self.price = price def getName(self): return self.name def getPrice(self): return self.price def accept(self, visitor): pass # 抗生素 class Antibiotic(Medicine): def accept(self, visitor): visitor.visit(self) # 感冒药 class Coldrex(Medicine): def accept(self, visitor): visitor.visit(self) # 工作人员类 class Visitor: name = "" def setName(self, name): self.name = name def visit(self, medicine): pass # 药品划价员 class Charger(Visitor): def visit(self, medicine): print("CHARGER: %s lists the Medicine %s. Price: %s" % (self.name, medicine.getName(), medicine.getPrice())) # 药房管理员 class Pharmacy(Visitor): def visit(self, medicine): print("PHARMACY: %s offers the Medicine %s. Price: %s" % (self.name, medicine.getName(), medicine.getPrice())) # 药方类 class ObjectStructure: pass class Prescription(ObjectStructure): medicines = [] def addMedicine(self, medicine): self.medicines.append(medicine) def rmvMedicine(self, medicine): self.medicines.remove(medicine) def visit(self, visitor): for medc in self.medicines: medc.accept(visitor) if __name__ == "__main__": yinqiao_pill = Coldrex("Yinqiao Pill", 2.0) penicillin = Antibiotic("Pencillin", 3.0) doctor_prsrp = Prescription() doctor_prsrp.addMedicine(yinqiao_pill) doctor_prsrp.addMedicine(penicillin) charger = Charger() charger.setName("Doctor Strange") pharger = Pharmacy() pharger.setName("Doctor Wei") doctor_prsrp.visit(charger) doctor_prsrp.visit(pharger)
#导入库 import turtle import random p = turtle #定义画圆函数 def drawCircle(x, y, c='red'): p.pu() # 抬起画笔 p.goto(x, y) # 绘制圆的起始位置 p.pd() # 放下画笔 p.color(c) # 绘制c色圆环 p.circle(30, 360) #绘制圆:半径,角度 #绘制雪花 def snow(snow_count): p.hideturtle() p.speed(500) p.pensize(2) for i in range(snow_count): r = random.random() g = random.random() b = random.random() p.pencolor(r, g, b) p.pu() p.goto(random.randint(-350, 350), random.randint(1, 270)) p.pd() dens = random.randint(8, 12) snowsize = random.randint(10, 14) for _ in range(dens): p.forward(snowsize) p.backward(snowsize) p.right(360 / dens) #绘制地面 def ground(ground_line_count): p.hideturtle() p.speed(500) for i in range(ground_line_count): p.pensize(random.randint(5, 10)) x = random.randint(-400, 350) y = random.randint(-280, -1) r = -y / 280 g = -y / 280 b = -y / 280 p.pencolor(r, g, b) p.penup() p.goto(x, y) p.pendown() p.forward(random.randint(40, 100)) #主函数 def main(): #绘制五环图 # p.pensize(3) # drawCircle(0, 0, 'blue') # drawCircle(60, 0, 'black') # drawCircle(120, 0, 'red') # drawCircle(90, -30, 'green') # drawCircle(30, -30, 'yellow') # p.done() #雪花飘飘 p.setup(800, 600, 0, 0) p.bgcolor('black') snow(30) ground(30) p.mainloop() main()
def NextWordProbability(sampletext,word): splited_memo = sample_memo.split() counted = {} for i in range(1,len(splited_memo)): #finding the key in dict this_word = splited_memo[i] word_before = splited_memo[i-1] if word_before == word: if counted.get(this_word,-1) == -1: #not exist then add to the dict counted[this_word] = 1 else: #exist then increase the logged number counted[this_word] += 1 return counted
def membership(): ''' Function to register the user as a member Takes in user input to determine which membership to register the user under ''' user_membership=None #User has no membership yet try: if user_status=='new user':#if the user is a newly registered user registration()#first register the user before becoming a member elif user_status=='existing user': ask=input('Would you like to join our basic membership program or our Loyalty membership program? ' )#Asks which membership program they would like to join if ask=='Basic': user_membership='Basic Member' print('You will have to pay a one off fee') payment()#a one off payment is required to become a basic member if booked_sessions>=10:#Member can upgrade their membership after booking 10 sessions upgrade=input('Would you like to upgrade to the loyalty membership?' ) elif ask=='Loyal' or 'Loyalty': user_membership='Loyalty Member' print('You will have to pay an annual fee') except TypeError: if not ask.isalpha(): print('Only use letters to type in your membership preference')
from typing import List, Tuple def get_numbers(input_filename: str) -> List[int]: with open(input_filename, 'r') as f: return [int(i) for i in f.readlines()] def find_complements_to(n: int, into: List[int]) -> Tuple[int, int]: while into: f = into.pop() try: i = into.index(n - f) return into[i], f except ValueError: continue def solve_two(input_filename: str) -> int: inputs = get_numbers(input_filename) to_find, c = find_complements_to(2020, inputs) return to_find * c def solve_three(input_filename: str) -> int: inputs = get_numbers(input_filename) while inputs: n = inputs.pop() remains = list(filter(lambda i: i < 2020 - n, inputs)) try: to_find, c = find_complements_to(2020 - n, remains) return n * to_find * c except TypeError: continue
import password def test_password_is_valid_according_to_occurency_policy(): input = '1-3 a: abcde' policy, pwd = input.split(': ') assert password.validate_occurences(policy, pwd) def test_password_is_invalid_according_to_occurency_policy(): input = '1-3 b: cdefg' policy, pwd = input.split(': ') assert not password.validate_occurences(policy, pwd) def test_count_valid_password_in_file_input(): assert 2 == password.count_valids_occurences('2/test_input.txt') def test_password_is_valid__according_to_position_policy(): input = '1-3 a: abcde' policy, pwd = input.split(': ') assert password.validate_position(policy, pwd) def test_count_valid_positions_password_in_file_input(): assert 1 == password.count_valids_positions('2/test_input.txt')
# Name: Royer V. Zamudio # UCID: rvz2 # Section: 003 # Programming Assignment 3: Simple HTTP Client and Server using TCP sockets # Server from socket import * import datetime, time import os.path serverIP = "127.0.0.1" serverPort = 12000 responseLen = 1000000 # Welcome client contact # Create socket serverSocket = socket(AF_INET, SOCK_STREAM) # Bind socket (address, port) serverSocket.bind((serverIP, serverPort)) # Listening socket serverSocket.listen(1) # Receive request from client while True: # Create a new socket to communicate with client # Accept connection with client connectionSocket, address = serverSocket.accept() # Receive request from client receivedData = connectionSocket.recv(responseLen) # Process request receivedData = receivedData.decode() receivedData = receivedData.split('\r\n') commandLine = receivedData[0] commandLine = commandLine.split(' ') command = commandLine[0] filename = commandLine[1] hostLine = receivedData[1] endLine = receivedData[2] if (endLine == ''): conGET = False else: condPart = endLine.split(': ') condPart = condPart[0] if (condPart == "If-Modified-Since"): conGET = True # Check if file exists try: # If file exists tempfileN = filename[1:] fResult = open(tempfileN, "rt") content = fResult.read() # Prepare HTTP GET response if (conGET == False): # If GET request t = time.time() t = time.gmtime(t) date = time.strftime("%a, %d %b %Y %H:%M:%S %Z\r\n", t) secs = os.path.getmtime(tempfileN) t2 = time.gmtime(secs) last_mod_time = time.strftime("%a, %d %b %Y %H:%M:%S GMT\r\n", t2) dataLen = len(content) responseGET = "HTTP/1.1 200 OK\r\nDate: "+date+"Last-Modified: "+last_mod_time+"\r\nContent-Length: "+str(dataLen)+"\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n"+content # Send response to client connectionSocket.send(responseGET.encode()) # Close socket connectionSocket.close() else: # If Conditional GET request # Check if file has been modified # Extract If-Modified-Since date and convert to tuple endLine = endLine.split(': ') datePart = endLine[1] t = time.strptime(datePart, "%a, %d %b %Y %H:%M:%S %Z\r\n") secs = time.mktime(t) # Get file's last modified time secs2 = os.path.getmtime(tempfileN) t2 = time.gmtime(secs2) # Compare times if (t2 > t): # If file has been modified # Prepare GET response t = time.time() t = time.gmtime(t) date = time.strftime("%a, %d %b %Y %H:%M:%S %Z\r\n", t) secs = os.path.getmtime(tempfileN) t2 = time.gmtime(secs) last_mod_time = time.strftime("%a, %d %b %Y %H:%M:%S GMT\r\n", t2) dataLen = len(content) responseGET = "HTTP/1.1 200 OK\r\nDate: "+date+"Last-Modified: "+last_mod_time+"\r\nContent-Length: "+str(dataLen)+"\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n"+content # Send response to client connectionSocket.send(responseGET.encode()) # Close socket connectionSocket.close() else: # If file has NOT been modified # Prepare conditional GET response t = time.time() t = time.gmtime(t) date = time.strftime("%a, %d %b %Y %H:%M:%S %Z\r\n", t) responseGET = "HTTP/1.1 304 Not Modified\r\nDate: "+date+"\r\n\r\n" # Send response to client connectionSocket.send(responseGET.encode()) # Close socket connectionSocket.close() except IOError: # If file does not exist # Prepare NOT FOUND response t = time.time() t = time.gmtime(t) date = time.strftime("%a, %d %b %Y %H:%M:%S %Z\r\n", t) responseGET = "HTTP/1.1 404 Not Found\r\nDate: "+date+"\r\n\r\n" # Send response to client connectionSocket.send(responseGET.encode()) # Close socket connectionSocket.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # basic data tye: string, byte, floating, integer, boolean(True/False), None print("hello, world") print(123e15) print('I\'m "ok"') print('\\\\ok') print(r'\\\\ok') print('''different lines ok?''') print(r'''different lines ok?''') print(3 > 2) print(3 > 2 or 2 > 3 and 5 > 4) print(not 3 > 2) print(None) # practice n = 123 f = 456.789 s1 = 'hello,world' s2 = 'hello,\'adam\'' # here 'r' is used to stop ESC(escape character) take into effect s3 = r'hello,\'bart\'' # it should be same no matter with 'r' or without 'r' s4 = r'''hello, lisa!''' print("practice") # string '+' number doesn't work print("n:", n) print("f:", f) # string '+' string still work with concat effect print("s1:" + s1) print("s2:" + s2) print("s3:" + s3) print("s4:" + s4) # string coding translation print(ord('A')) print(ord('中')) print(chr(66)) print(chr(25991)) # string encode # [string -> byte] (ascii - 1 byte, unicode - 2 bytes, utf-8 - 1-6 bytes(english - 1 byte, chinese - 3 bytes)) print('ABC') # ABC print(b'ABC') # b'ABC', use one byte to store one character # print('中文'.encode('ascii')) this will not work since ascii has not encoded chinese print('ABC'.encode('ascii')) # b'ABC', 使用ascii把ABC编码成bytes print('ABC'.encode('utf-8')) # b'ABC', 使用utf-8把ABC编码成bytes, 由于是纯英文字符,所以utf-8与ascii一样每个字符都只占用一个byte print('中文'.encode('utf-8')) # b'\xe4\xb8\xad\xe6\x96\x87', 非英文字符会转变成16进制编码,每个中文字符占用三个bytes print('中ABC文'.encode('utf-8')) # b'\xe4\xb8\xadABC\xe6\x96\x87' # print('中文'.encode('unicode')) this will not work since python has already encoded string with unicode in default # String decode # [byte -> string] print(b'ABC'.decode('ascii')) # print(b'\xe4\xb8\xad\xe6\x96\x87'.decode('ascii')) these bytes can't be decoded as ascii print(b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')) # string/bytes length print("'ABC''s length is", len('ABC')) print("'中文''s length is", len('中文')) print("b'ABC' are bytes, its length is", len(b'ABC')) print(r"b'\xe4\xb8\xadABC\xe6\x96\x87' are bytes, its length is", len(b'\xe4\xb8\xadABC\xe6\x96\x87')) # usage of % print('%%s') # there is no problem to use % in string without any format attached print('%s' % 'format string') # when there is mapping value outside, then % take into effect print('%s %%' % 'format string') # %% will escape % print('%s' % 15) # string print('%d' % 15) # integer print('%x' % 15) # hexadecimal print('%f' % 15) # floating print('%s %d %x %f' % (15, 15, 15, 15)) # combined print('%s %s %s %s %s' % (True, b"i'm byte", 15, 15.2, None)) # all other basic type can be translated to string # list (索引从0开始对应第一个元素,然后递增,或者从-1开始对应最后一个元素,然后递减) classmates = ['maple', 'wang', 'feng'] print(classmates) print("length:", len(classmates)) print(classmates[0]) print(classmates[1]) print(classmates[2]) print(classmates[-1]) print(classmates[-2]) print(classmates[-3]) classmates.append(15) # list是一个可变的有序表,所以,可以往list中追加元素到末尾,注意返回值为None print(classmates) classmates.insert(1, 16) # 可以把元素插入到指定的位置,比如索引号为1的位置,注意返回值为None print(classmates) print(classmates.pop()) # 删除list末尾的元素,返回值为最后一个元素 print(classmates.pop(1)) # 返回值为指定的删除的元素 print(classmates) classmates2 = [1, 2, 3] print(classmates + classmates2) # 两个list可以相加,注意python中+两边的数据类型必须一致才能生效 classmates.append(classmates2) # list的元素可以是不同的数据类型,当然也包括list print(classmates) print(classmates[0][0], classmates[1][2], classmates[2][3], classmates[3][2]) # 字符串也相当于是一个list # tuple (元组:另一种有序列表,tuple和list非常类似,tuple一旦初始化就不能修改) classmates = ('maple', 'wang', 'feng') print(classmates) emptyTuple = () # empty tuple print(emptyTuple) # 因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算 # Python在显示只有1个元素的tuple时,也会加一个逗号,,以免你误解成数学计算意义上的括号 oneElementTuple = ('maple',) print(oneElementTuple) print(oneElementTuple[0]) # tuple是一种有序列表 tupleInList = [oneElementTuple, classmates] print(tupleInList) print(tupleInList[0][0][0]) classmates2 = ('x', 'y') print(classmates + classmates2) # tuple可以直接相加 # practice L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] # print Apple print(L[0][0]) # print Python print(L[1][1]) # print Lisa print(L[2][2]) # 条件判断 conditional judgement # 只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。 age = 6 print("your age is", age) if age >= 18: print('adult') elif age >= 10: print("juvenile") else: print("teenager") # birth = input('birth: ') is string, can be used to compare with int # birth = int(input('birth: ')) birth = 1985 if birth < 2000: print('00前') else: print('00后') # practice height = 1.75 weight = 80.5 bmi = weight / (height * height) if bmi < 18.5: print("underweight") elif bmi < 25: print("normal") elif bmi < 28: print("overweight") elif bmi < 32: print("obesity") else: print("severe obesity") # 循环 cycle for x in [19, 'maple', True]: print(x) sum = 0 for x in range(101): # 0~100, 也可以list(range(101)) sum += x print(sum) sum = 0 x = 100 while x > 0: sum += x x -= 1 # 不能用--x或者x--吗? print(sum) # practice for x in ['Bart', 'Lisa', 'Adam']: print("Hello,", x) # dict: python中的map,key-value,key的集合是一个set,一个key只对应一个value d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print(d) print(d['Bob']) # 通过key来找value,方法1 print(d.get('Bob')) # 通过key来找value,方法2 d['Bob'] = 14 # set value print(d['Bob']) if 'Maple' in d: # 判断key是否存在的方法1 print("Maple is in", d) else: print("maple is not in", d) if d.get('maple'): # 判断key是否存在的方法2, 没有会返回None print("Maple is in", d) else: print("maple is not in", d) d.pop('Bob') # 删除一个key-value pair print(d) d2 = {'maple': 10, 'wang': 20} print(d2) # print(d+d2) 不支持两个dict之间相加 # print(d&d2) 不支持两个dict之间与 # print(d|d2) 不支持两个dict之间或 ''' 请务必注意,dict内部存放的顺序和key放入的顺序是没有关系的。 和list比较,dict有以下几个特点: 查找和插入的速度极快,不会随着key的增加而变慢; 需要占用大量的内存,内存浪费多。 而list相反: 查找和插入的时间随着元素的增加而增加; 占用空间小,浪费内存很少。 所以,dict是用空间来换取时间的一种方法。 dict可以用在需要高速查找的很多地方,在Python代码中几乎无处不在,正确使用dict非常重要,需要牢记的第一条就是dict的key必须是不可变对象。 这是因为dict根据key来计算value的存储位置,如果每次计算相同的key得出的结果不同,那dict内部就完全混乱了。这个通过key计算位置的算法称为哈希算法(Hash)。 ''' # set : set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。 s = {1, 1, 2, 2, 3, 3} # 创建set方法1,没有value的dict,重复的元素会被自动过滤 # s = {[1,1,2,2,3,3]} # list是可变数据类型,不能作为set的元素 s = set([1, 1, 2, 2, 3, 3]) # 创建set方法2,输入一个list print(s) s.add('maple') # 为set add一个元素,如重复会自动过滤,注意返回为None print(s) s.remove('maple') # 删除一个元素,返回为None print(s) s2 = {'maple', 'wang'} print(s2) # print(s+s2) 两个set不能直接相加 print(s & s2) # 两个set可以与 print(s | s2) # 两个set可以或 # practice d = {(1, 2, 3): 20} a = (1, 2, 3) print(d[a]) a = ('maple', 'wang') s = {a} print(s) print({(1, 2), (1, 2, 3)}) # tuple可以为set的元素,也可以为dict的key # print({(1,2),(1,[2,3])}) 即使(1,[2,3])为tuple,但是它里面含有list,为可变对象,就不能使用 ''' 不可变对象: 所有的基本数据类型(string, None, boolean, integer, floating, byte), tuple(元素可以为任意的) 可变对象: list(元素可以为任意的), set(元素必须是完全不可变对象,比如tuple中元素也要为不可变对象), dict(key必须要是不可变对象,value可以为任意的) ''' # built-in functions https://docs.python.org/3/library/functions.html # built-in constants https://docs.python.org/3/library/constants.html # built-in type https://docs.python.org/3/library/stdtypes.html # define function def test(x): print(x) return test("just test function") ''' 请注意,函数体内部的语句在执行时,一旦执行到return时,函数就执行完毕,并将结果返回。因此,函数内部通过条件判断和循环可以实现非常复杂的逻辑。 如果没有return语句,函数执行完毕后也会返回结果,只是结果为None。 return None可以简写为return ''' def nop(): pass # 占位符,如果缺少return,必须要有pass才行 return nop() def returnMultipleValues(): return 1, 2, 3 print(returnMultipleValues()) # 实际返回的是一个tuple # parameter type for function # 位置参数:指的是必选参数,调用的顺序必须要和定义的顺序相同 def power(x): return x * x print(power(x=10)) # 位置参数可以带参数名称,但是带不带参数名称是可选的 print(power(10)) def power(x, n): s = 1 while n > 0: n -= 1 s *= x return s print(power(10, 4)) # 默认参数:定义的参数可以有默认值,所以是可选参数,必须定义在所有必选参数之后 def power2(x, n=2): s = 1 while n > 0: n -= 1 s *= x return s print(power2(10)) print(power2(10, 3)) ''' 从上面的例子可以看出,默认参数可以简化函数的调用。设置默认参数时,有几点要注意: 一是必选参数在前,默认参数在后,否则Python的解释器会报错(思考一下为什么默认参数不能放在必选参数前面); 二是如何设置默认参数。 当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。 ''' def enroll(name, gender, age=6, city='Shanghai'): print(name) print(gender) print(age) print(city) enroll('maple', 'male') # 不带参数名,参数的位置必须与定义的一致 enroll(gender='male', name='maple', age=30) # 如果带上参数名,那么参数的位置不必为定义的顺序 enroll('maple', 'male', city='Hangzhou') # 如果默认参数有多个,而调用的时候又不全部调用,那么最好把调用参数的名称写上 def addEnd(L=[]): L.append('end') return L print(addEnd()) print(addEnd()) print(addEnd()) ''' Python函数在定义的时候,默认参数L的值就被计算出来了,即[], 因为默认参数L也是一个变量,它指向对象[],每次调用该函数, 如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。 ''' # 定义默认参数要牢记一点:默认参数必须指向不变对象! def addEnd(L=None): if L is None: L = [] L.append('end') return L print(addEnd()) print(addEnd()) print(addEnd()) # 可变参数:传入的参数的个数是可变的,所有的传入的参数被组合成一个tuple def calc(*num): s = 0 for x in num: s += pow(x, 2) return s print(calc(1, 2, 3, 4)) ''' 在函数内部,参数num接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数 ''' def printNum(*num): print(num) # num会是一个tuple for x in num: print(x) # num的元素可以是任意的类型 printNum(1, 3, True, [1, 2], {"maple": 10, "wang": 20}, {10, 20}) num = (1, 3, True, [1, 2], {"maple": 10, "wang": 20}, {10, 20}) # 如果已经得到了一个tuple,而要用一个可变参数的函数 printNum(num) # 只被认为是一个tuple元素 printNum(*num) # *num会被解析一个列表 print(*num) # *num会是一个参数列表 printNum() # 0个参数即为() # 关键字参数:传入的参数的个数是可变的,并且允许带参数名称,在函数内部,会被组装成dict def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) person("maple", 24) person("maple", 24, height=172, weight=65) person(height=172, name="maple", weight=65, age=24) # 使用了参数名,顺序不用和定义的一样 # 如果dict已经组装好,则使用**来作为参数输入 others = {'height': 172, 'weight': 65} person("feng", 30, **others) # 命名关键字参数:和关键字参数**kw不同,定义的时候,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数 def person2(name, age, *, city, job): print(name, age, city, job) person2("maple", 15, city='shanghai', job='free') # 都是必选的参数,与位置参数不同的是命名关键字参数在调用的时候必须带有参数名 def person3(name, age, *, city='hangzhou', job='engineer'): # 命名关键字参数可以是默认参数 print(name, age, city, job) person3('maple', 16) ''' 参数组合 在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数, 这5种参数都可以组合使用,除了可变参数无法和命名关键字参数混合。 但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数/命名关键字参数和关键字参数。 ''' # this is just change for test
# -*- coding: utf-8 -*- from __future__ import unicode_literals from collections import defaultdict #type : list multidict d=defaultdict(list) d['a'].append(1) d['a'].append(2) d['a'].append(2) d['b'].append(4) print d #type : set multidict b=defaultdict(set) b['a'].add(1) b['a'].add(2) b['a'].add(2) #set not same element b['b'].add(1) print b #setdefault() 可以避免使用multidict 但是又可以动态添加element m={} m.setdefault('a',[]).append(1) m.setdefault('a',[]).append(2) m.setdefault('b',[]).append(4) print m
##################################################################### # # ORIGINAL PROBLEM: # Sum the digits of an integer N, printing out each summation until # N is only one digit in length. # # For more information, see the original prompt at # http://www.reddit.com/r/dailyprogrammer/comments/1fnutb/06413_challenge_128_easy_sumthedigits_part_ii/ # ##################################################################### def sum_digits(num): while len(str(num)) > 1: num = sum(int(digit) for digit in list(str(num))) print num if __name__ == "__main__": num = raw_input() sum_digits(num)
##################################################################### # # ORIGINAL PROBLEM: # Given an inclusive range of years, count the number of years with no repeated digits. # BONUS: Count the number of years in the longest consecutive run of years with # repeated digits and years without repeated digits, from 1000 to 2013. # # For more information, see the original prompt at # http://www.reddit.com/r/dailyprogrammer/comments/10l8ay/9272012_challenge_101_easy_nonrepeating_years/ # ##################################################################### def num_unrepeated_years(start, end): return len([x for x in xrange(start, end+1) if len(set(str(x))) == len(str(x))]) def longest_years(start, end): repeated = [x for x in xrange(start, end+1) if len(set(str(x))) == len(str(x))] unrepeated = [x for x in xrange(start, end+1) if len(set(str(x))) != len(str(x))] return longest_consecutive_years(unrepeated), longest_consecutive_years(repeated) def longest_consecutive_years(years): longest, current = 0, 0 for year in years: current = current + 1 if longest == 0 or year - previous == 1 else 1 previous = year longest = current if current > longest else longest return longest print num_unrepeated_years(1980, 1987) print longest_years(1000, 2013)
##################################################################### # # ORIGINAL PROBLEM: # Given an N-valued coin that converts to 3 coins of values N/2, # N/3 and N/4, calculate the number of 0-valued coins eventually # received for that coin if all positive-valued coins are converted. # # For more information, see the original prompt at # http://www.reddit.com/r/dailyprogrammer/comments/19mn2d/030413_challenge_121_easy_bytelandian_exchange_1/ # ##################################################################### return_dict = {0: 1} def dp_perpetual_coin_return(coin): if coin not in return_dict: return_dict[coin] = dp_perpetual_coin_return(coin/2) + dp_perpetual_coin_return(coin/3) \ + dp_perpetual_coin_return(coin/4) return return_dict[coin] if __name__ == "__main__": print dp_perpetual_coin_return(int(raw_input())) ##################################################################### # The code below does not use memoization, and is much slower. ##################################################################### # def perpetual_coin_return(coin): # return 1 if coin == 0 else perpetual_coin_return(coin/2) + perpetual_coin_return(coin/3) + perpetual_coin_return(coin/4) # # if __name__ == "__main__": # print perpetual_coin_return(int(raw_input()))
##################################################################### # # ORIGINAL PROBLEM: # Calculate the perimeter of a polygon, given that it has N sides # and a circumradius of R (the distance between the center of the # polygon to any of its vertices). # # For more information, see the original prompt at # http://www.reddit.com/r/dailyprogrammer/comments/1tixzk/122313_challenge_146_easy_polygon_perimeter/ # ##################################################################### import math n, r = map(float, raw_input().split()) print round(n*r*2*math.sin(math.pi/n), 3)
##################################################################### # # ORIGINAL PROBLEM: # Write a program that prints out each step that McCarthy's function # will perform for a given integer N. # # For more information, see the original prompt at # http://www.reddit.com/r/dailyprogrammer/comments/1f7qp5/052813_challenge_127_easy_mccarthy_91_function/ # ##################################################################### def mccarthy_91(n, num_times): if n > 100: print ("M(" * num_times) + str(n-10)+ (")" * num_times) + " since {n} is greater than 100".format(n=n) return n - 10 else: print ("M(" * 2) + str(n+11) + (")" * 2) + " since {n} is equal to or less than 100".format(n=n) return mccarthy_91(mccarthy_91(n+11, 1), 0) n = int(raw_input()) print "M({n})".format(n=n) print mccarthy_91(n, 1)
#define dictionaries to be stored in shelves locations = {0: {"desc": "You are sitting in front of a computer learning Python", "exits": {}, "namedExits": {}}, 1: {"desc": "You are standing at the end of a road before a small brick building", "exits": {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0}, "namedExits": {"2": 2, "3": 3, "5": 5, "4": 4}}, 2: {"desc": "You are at the top of a hill", "exits": {"N": 5, "Q": 0}, "namedExits": {"5": 5}}, 3: {"desc": "You are inside a building, a well house for a small stream", "exits": {"W": 1, "Q": 0}, "namedExits": {"1": 1}}, 4: {"desc": "You are in a valley beside a stream", "exits": {"N": 1, "W": 2, "Q": 0}, "namedExits": {"1": 1, "2": 2}}, 5: {"desc": "You are in the forest", "exits": {"W": 2, "S": 1, "Q": 0}, "namedExits": {"2": 2, "1": 1}} } vocabulary = {"QUIT": "Q", "NORTH": "N", "SOUTH": "S", "EAST": "E", "WEST": "W", "ROAD": "1", "HILL": "2", "BUILDING": "3", "VALLEY": "4", "FOREST": "5"} import os, shelve #set working directory os.chdir(r'C:\Users\...\My Python Scripts') #only have to shelve 2 dictionaries here #but what if there were 10 or 100 dictionaries that needed #to be shelved? #use a scalable and flexible approach by #storing references to global dicts in a list dict_list = [locations, vocabulary] #create a SINGLE shelve object to store all dictionaries #to get the name of the dictionary without knowing its #name in advance (i.e. don't hard code the names), #use a hack with globals() dictionary #store a copy of globals() in a temp variable because #iterating through it directly will fail with a #RuntimeError: dictionary changed size during iteration temp_globals = globals().copy() #"frozen" copy of globals() #now use JUST ONE FILE to store both (or however many we want) #dictionaries! with shelve.open('game_data') as shelve_data: for item in dict_list: for k, v in temp_globals.items(): ''' #find the value in the globals() dictionary that matches #the value of an item in dict_list #not a good strategy for primitives like ints, however, ​ #unless each primitive has a different value''' if v == item: #now we know the name of the dict as a string dict_name = k #--------------original approach in challenge specification-----------# #the shelve file will have the name of the dictionary object #in dict_list that's being accessed #key of first (and only) entry in shelve_data file #will be the same as the name of the dictionary (e.g. locations), which #is also the name of the file #filename: locations[.dat|.bak|.dir] on Windows #first item is shelve_data['locations'] #name of dictionary: locations #--------------------------new approach--------------------------------# #that's too confusing! #why not use ONE shelve with TWO entries, one for each dictionary? shelve_data[dict_name] = v #done with this iteration through globals #now find the name of the next item in dict_list break #now print the shelve file with shelve.open('game_data') as shelve_data: for k, v in shelve_data.items(): print('shelve_data[{}] = {}'.format(k, v)) #test to ensure you can access each dictionary in the shelve object #using its literal name #print(shelve_data['locations']) #print(shelve_data['vocabulary']) #(it works!)
from bs4 import BeautifulSoup import requests import sys import os def show_lyrics(): artist = input("enter the name of the ARTIST : ") artist = artist.lower().replace(" ","-") track = input("enter the name of the TRACK : ") track = track.lower().replace(" ","-") url = 'http://www.metrolyrics.com/' + track + '-lyrics-' + artist + '.html' r = requests.get(url) soup = BeautifulSoup(r.content) lyrics = soup.find_all("p", {"class":"verse"}) for i in lyrics: print(i.text) show_lyrics()
# Launch the interactive pyspark shell # $ pyspark # Declare column variables auctionid = 0 bid = 1 bidtime = 2 bidder = 3 bidderrate = 4 openbid = 5 price = 6 itemtype = 7 daystolive = 8 # Load the data auctionRDD = sc.textFile("/headless/Desktop/next-level-python-big-data/spark-dev3600/data/auctiondata.csv").map(lambda line: line.split(",")) # See the first element of the RDD auctionRDD.first() # First five element of the RDD auctionRDD.take(5) # What is the total number of bids? auctionRDD.count() # What is the total number of distinct items that were auctioned? auctionRDD.map(lambda line: line[auctionid]).distinct().count() # What is the total number of item types that were auctioned? auctionRDD.map(lambda line: line[itemtype]).distinct().count() # What is the total number of bids per item type? auctionRDD.map(lambda x: (x[itemtype], 1)).reduceByKey(lambda x, y: x + y).collect() # What is the total number of bids per auction? auctionRDD.map(lambda x: (x[auctionid], 1)).reduceByKey(lambda x, y: x + y).collect() # Across all auctioned items, what is the max number of bids? bids_auctionRDD = auctionRDD.map(lambda x: (x[auctionid], 1)).reduceByKey(lambda x, y: x + y) bids_auctionRDD.map(lambda x: x[bid]).reduce(max) # Across all auctioned items, what is the minimum of bids? bids_auctionRDD = auctionRDD.map(lambda x: (x[auctionid], 1)).reduceByKey(lambda x, y: x + y) bids_auctionRDD.map(lambda x: x[bid]).reduce(min) # What is the average bid? totbids = auctionRDD.count() totitems = auctionRDD.map(lambda line: line[auctionid]).distinct().count() totbids / totitems # Exit the pyspark shell exit()
#!/usr/bin/env python from datetime import datetime from datetime import time welcome_message = "" def main(): global welcome_message global request_heading welcome_message = get_welcome_heading() def get_welcome_heading(): name = "Joe" today = datetime.now() month = today.month day = today.day t = datetime.now().strftime("%A, %B %d, %Y - %I:%M %p") seasonal_msg = "" if month == 10: seasonal_msg = "Get your costume ready for Halloween!" if day < 31 else "Trick or treat!" elif month == 11: seasonal_msg = "Get your turkey and ham ready for Thanksgiving!" elif month == 12: if day < 25: seasonal_msg = "Get ready for Merry Christmas" elif day == 25: seasonal_msg = "Merry Christmas!" elif day > 25: seasonal_msg = "Have a Happy New Year!" welcome_heading = "Hello " + name + "! <br>" + t + "<br>" + seasonal_msg return "<p>" + welcome_heading + "</p>" main() print welcome_message
import turtle screen_width = 400 screen_hieght = 400 turtle.setup(screen_width, screen_hieght) the_turtle = turtle.Turtle() white = (255,255,255,) black = (0,0,0) red = (255,0,0) green = (0,255,0) blue = (0,0,255) window = turtle.Screen() turtle.colormode(255) window.title("Turtle Graphics Screen") print("Please enter a starting x and y coordinate") while True: try: start_coord = [int(i) for i in input().split(' ')] print("Valid Input, Check Turtle Window.") break except: print("Invalid input.") the_turtle.setposition(start_coord[0],start_coord[1]) the_turtle.penup() while True: print("Please enter an end point x, y coordinate") try: end_coord = [int(i) for i in input().split(' ')] break except: print("Invalid input") while True: print("Please choose an obstacle type") print("S = Rectangle, T = Triangle") try: ob_type = input() break except: print("Invalid Input") while True: if ob_type.lower() == 's': pass elif ob_type.lower == 't': pass turtle.exitonclick()
# function explode(string, separator) # Menghasilkan Array substring dengan memisahkan string oleh separator # Contoh : explode("a.bc.d.efg.h", ".") -> ["a", "bc", "d", "efg", "h"] def explode(string, separator): # KAMUS LOKAL # arr : list # el : string # char : string (1-character string) # ALGORITMA arr = [] el = "" for char in string: if char != separator: el += char else: arr.append(el) el = "" arr.append(el) return arr
import random guesses = 10 number = (random.randint(1, 100)) guess = None print(f"The computer has generated a number, you have {guesses} guesses") while guess != number: valid = False while not valid: guess = input(f"Enter a whole number between 1 and 100. \n") try: guess = int(guess) if guess < 1 or guess > 100: print("That is invalid, Retry") else: valid = True except ValueError: print("That is invalid, Retry") if guess < number: print("That number is too low") if guess > number: print("That number is too high") if guess == number: print(f"Good job my guy! You got it right! \n You had {guesses} guesses left") break if guesses <= 1: print("Oh no, you got rekt, no more guesses for you") break guesses -= 1 print(f"you have {guesses} guesses left")
digits = [] starting = 2**1000 print(starting) while starting > 0: digits.append(starting%10) starting = starting//10 print(digits) print(sum(digits))
from fractions import Fraction # too slow primes = {2: 3, 3: 5} def gen_primes(): i = 2 yield i while True: if i in primes: yield primes[i] i = primes[i] continue is_prime = True for k,v in primes.items(): if i % k == 0: is_prime = False if is_prime: previous_prime = 0 for v in primes.values(): if v > previous_prime: previous_prime = v primes[previous_prime] = i yield primes[previous_prime] i += 1 amor = {} def factor(n): if n == 1: return {1: 1} original_n = n if n in amor: return amor[n] else: factors = {} while n != 1: for i in gen_primes(): if n % i == 0: # i divides n evenly if i in factors: factors[i] += 1 else: factors[i] = 1 n //= i # Remove the factor from n if i > n: break amor[original_n] = factors return amor[original_n] def find_fraction_group_order(group): counting_set = set() for d in range(1,group+1): for n in range(1,d): counting_set.add(Fraction(n,d)) return len(counting_set) for i in range(1,5): thingy = find_fraction_group_order(10**i) print(f"{10**i} gives {thingy} = {factor(thingy)}")
# Coverts images with the JPG extension and saves them as PNG # Takes 2 imputs from terminal # 1. Folder Name of where the image is located # 2. File name of the size that you want # 3. File name of that you want to resize # Terminal command example: # python JPGtoPNGConverter.py FolderName\ fileName.jpg fileName2.jpg # python JPGtoPNGConverter.py Pokedex\ pikachu.jpg bulbasaur.jpg import sys #Importing System Module import os #Importing OS Module from PIL import Image #Importing Pillow Module #Grabbing first and second parameters, Folder name and New folder name folder_name = sys.argv[1] file_name1 = sys.argv[2] #Assigning first parameter(Orgin Folder) to folder_name file_name2 = sys.argv[3] #Assigning second parameter(New Folder or existing) to output_folder #Check if new folder exists, if not create # if not os.path.exists(output_folder): # os.makedirs(output_folder) image1 = Image.open(f'{folder_name}{file_name1}') #Stores the first image image2 = Image.open(f'{folder_name}{file_name2}') #Stores the Second image image_size = image1.size #Grabs the size of the first image print (image_size) image_size2 = image2.size #Grabs the size of the second image print (image_size2) image2 = image2.resize((image_size), Image.LANCZOS) #Resizes the second image to match the first print (image2.size) clean_name = os.path.splitext(file_name2)[0] image2.save(f'{folder_name}{clean_name}-resize.jpg') #Saving resized second image, preserving the original.
import matplotlib.pyplot as plt class Circle(object): def __init__(self, radius=3, color='blue'): self.radius = radius self.color = color def add_radius(self, r): self.radius = self.radius + r return self.radius def draw_circle(self): plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color)) plt.axis("scaled") plt.show() RedCircle = Circle(10, 'red') print(dir(RedCircle)) print(RedCircle) print(RedCircle.radius) print(RedCircle.color) RedCircle.radius = 5 print(RedCircle.radius) # RedCircle.draw_circle() print('Radius of object:', RedCircle.radius) RedCircle.add_radius(2) print('Radius of object of after applying the method add_radius(2):', RedCircle.radius) RedCircle.add_radius(5) print('Radius of object of after applying the method add_radius(5):', RedCircle.radius) BlueCircle = Circle(radius=100) # BlueCircle.draw_circle() class Rectangle(object): def __init__(self, width=2, height=3, color='r'): self.width = width self.height = height self.color = color def draw_rectangle(self): plt.gca().add_patch(plt.Rectangle((0, 0), self.width, self.height, fc=self.color)) plt.axis('scaled') plt.show() SkinnyBlueRectangle = Rectangle(2, 10, 'blue') print(SkinnyBlueRectangle.height) print(SkinnyBlueRectangle.width) print(SkinnyBlueRectangle.color) SkinnyBlueRectangle.draw_rectangle() FatYellowRectangle = Rectangle(20, 5, 'yellow') FatYellowRectangle.draw_rectangle()
w1 = "Hello" w2 = "World" print(w1, w2) w3 = "Hello World" print(w3) print("Hello" + "World") list = [1, 2, 3, 4] print(list)
i = 1 while(i < 10): print(i) i += 1 # do - while q = 1 w = 1 while (q < 10): while (w < 10): print("w = ", w) w+=1 if (w == 8): continue q+=1 print("q = ", q)
# Thomas Marshall # SalesForce.py # Purpose - This program builds a class that gets a person's ID number, name # and list of sales made, set a person's name, add more sales to an individual, calculate # a person's total sales, decide if an individual's quota was met, and compare the total # sales of two sales people # I certify this lab is my own work, but I discussed it with Nick Mancabelli. # Class name class SalesPerson: # Initializer def __init__(self, tag, name, salesList): # Declares the ID number the ID number self.tag = tag # Declares the sale person's the sales person's self.name = name # Declares the list of sales self.salesList = salesList # Function to get the person's name def getName(self): # Returns their name return self.name # Function to get the person's ID number def getID(self): # Returns their ID number return self.tag # Function to set the person's name def setName(self, name): # Returns their name self.name = name # Function to add another sale to the list of a person's sales def enterSale(self, aSale): # Adds another sale to the list of a person's sales self.salesList.append(aSale) # Function to add up a person's sales def totalSales(self): # Set up a sum total = 0 # Range built to add all the sales for i in range(len(self.salesList)): # Adds each sale total += float(self.salesList[i]) # Returns sale total return total # Function to get the person's list of sales def getSales(self): # Returns their sales list return self.salesList # A function to find out if the quota was met def metQuota(self, quota): # Returns if the quota was met return self.totalSales() >= quota # A function that compares two people's total sales def compareTo(self, otherPerson): # Person 1 total sales personTotal = self.totalSales() # Person 2 total sales otherPerson = otherPerson.totalSales() # Person 1 had more if personTotal > otherPerson: # Returns positive return 1 # Person 2 had more elif personTotal < otherPerson: # Returns negative return -1 # They had the same amount elif personTotal == otherPerson: # Returns 0 return 0 # String of info def __str__(self): # Returns ID number, name, and total sales return ("Sales Person:\n\tI.D. Number: " + str(self.tag) + "\n\tName: " + self.name + "\n\tTotal Sales: " + str(self.totalSales()))
from matplotlib import pyplot as plt from matplotlib import style x = [1,2,3,4,5,6] y = [7,5,6,7,8,9] x2 = [1,2,3,4,5,6] y2 = [3,6,5,7,8,6] #algoritma style.use('dark _background') plt.plot(x,y,label = 'LIne one') plt.plot(x2,y2,label = 'LIne two') plt.xlabel('x axis') plt.ylabel('y axis') plt.title('Simple Chart') plt.legend() plt.show()
# raising and exception def fun(level): if level < 1 : raise Exception(level) return level try : # l = fun(5) l = fun(-5) print ("level : ",l) except Exception as e: print ("Error in level argument",e.args[0]) else : print ("no exception caught") finally : print ("In finally block")
a = input("enter your first name:") b = input("enter your surname:") print (a,b)
# function return example def sum (arg1,arg2): total = arg1+arg2 print ("Inside the fun:",total) return total total = sum (10,20) print ("outside the function :",total)
# Program to sort alphabetically the words form a paragraph provided by the user my_str = "Hello this Is an Example With cased letters" #my_str = input("Enter a paragraphs: ") words = my_str.split() words.sort() print("The sorted words are:") for word in words: print(word)
# TODO: Convert the 'what' script to a 'normal' formula. # TODO: Modify for practice. # Add Function def add(a, b): print "ADDING %d + %d" % (a, b) return a + b # Subtract Function def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b # Multiply Function def multiply(a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b # Divide Function def divide(a, b): print "DIVING %d / %d" % (a, b) return a / b print "Let's do some math with just functions!" # Sets variables that calls functions with set parameters. age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) # A puzzle for the extra credit, type it in anyway. print "Here is a puzzle." what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print "That becomes: ", what, "Can you do it by hand?"
"""**************************************************************************** * File: RSA_key_generator.py * Project: RSA Key, Generation and Decryption * Author: Everest Brooks (everest1@umbc.edu) RSA Key Generation This program will generate RSA public and private keys. The program will accept the desired modulus size in bits as a parameter (e.g. 1024, 2048, 4096) and write the keys, clearly labeled, to stdout. The Extended Euclidean Algorithm is used to compute modular inverses and Miller-Rabin performs the test for probable primes. ****************************************************************************""" import math import random from datetime import datetime # helper function for finding e, etc def gcd(a, b): while a != 0: a1 = a a = b % a b = a1 return b #int EUCLID(int a, int b){ # if(b == 0) # return a; # else # return EUCLID(b, a % b); #} def EXT_EUCLID(x, y): if gcd(x, y) != 1: return None a, b, c = 1, 0, x d, e, f = 0, 1, y while f != 0: z = c // f d, e, f, a, b, c = (a-z * d), (b-z * e), (c-z * f), d, e, f return a % y def MILLER_RABIN(n, s): # for j in range(1, s): # a = random.randrange(1, n-1) # if WITNESS(a, n): # return "COMPOSITE" # return "PRIME" # create num to compute with d = n-1 while d % 2 == 0: d = d // 2 # test s times, can be changed for i in range(s): a = random.randrange(2, n-1) # pow is a^d % n t = pow(a, d, n) if t == 1 or t == n-1: return "PRIME" # square value until 1 or n-1 reached while d != n-1: t = (t * t) % n d = d * 2 if t == 1: return "COMPOSITE" if t == n-1: return "PRIME" return "COMPOSITE" def main(): # get modulus size from user size = 0 valid = False while valid == False: size = int(input("Enter the modulus size in number of bits (1024, 2048, 4096):")) if size == 1024 or size == 2048 or size == 4096: valid = True else: print("Enter 1024, 2048 or 4096.") # Create the primes p and q primality = "" tests = 7 #print("creating p") while primality != "PRIME": random.seed(datetime.now()) p = random.randrange(2**(size-1), 2**(size)) primality = MILLER_RABIN(p, tests) primality = "" #print("creating q") while primality != "PRIME": random.seed(datetime.now()) q = random.randrange(2**(size-1), 2**(size)) primality = MILLER_RABIN(q, tests) n = p * q # compute relatively prime e using (p-1)*(q-1) factor = 0 #print("creating e") while factor != 1: e = random.randrange(2**(size-1), 2**(size)) factor = gcd(e, (p-1) * (q-1)) # compute d using e and ext_euclid #print("creating d") d = EXT_EUCLID(e, (p-1)*(q-1)) publicKey = (n, e) privateKey = (n, d) print('Public key:', publicKey) print('Private key:', privateKey) M = "This message has been encoded into RSA." x = 0 for c in M: x = x << 8 x = x ^ ord(c) M_RSA = pow(x, d, n) print("The message is signed as:", M_RSA) main()
""" Write code that asks the user to provide a score for an exam as input, and checks what grade the score is associated with. (Example: a score higher than 90 is an A.)""" # gather input from the user grade = int(input("enter a grade:\n")) # checking my work to see if the proper data type is set which is confirmed set to int print(type(grade)) # here i will create my conditions to group grades if grade >= 90: print("you have an A") elif grade >= 80: print("you have a B") elif grade >= 70: print("you have a C") elif grade >= 60: print("you have a D") elif grade >= 0 or grade <= 59: print("you have a F") else: print("enter a valid input") exit()
class menuItem: """ Represents a single menu item, that stores the item number, the description of the item and the prie of the item """ def __init__(self, itemNum, itemDescription, itemPrice): """ Creates a menu item using the constructor parameters :param itemNum: Order number :param itemDescription: Type of pizza :param itemPrice: Price of pizza """ # Constructor, initializes each of the item number, description, and price to their corresponding parameters self.itemNum = itemNum self.itemDescription = itemDescription self.itemPrice = itemPrice def encode(self): """ Turns menuItem into string variable :return: String version of menu item """ encode = str(self.itemNum) + " " + str(self.itemDescription) + " $" + str(self.itemPrice) return encode def getitemPrice(self): """ :return: The price of the item is returned """ return self.itemPrice
from collections import defaultdict class Graph(): ''' Defines a graph instance ''' def __init__(self, adj_list=defaultdict(list)): self.amnt_vertices = len(adj_list.keys()) self.adj_list = adj_list self.amnt_components = 0 def init_pajek_graph(self, filename): ''' Reads a graph from a pajek formated file ''' with open(filename, "r") as fp: self.amnt_vertices = int(fp.readline().split(" ")[1]) # Amount gets the amount of vertices type = fp.readline() # Unnecessary line while True: line = fp.readline().strip() if not line: break # Gets edges/arcs vertices = list(map(int, line.split(" "))) self.adj_list[vertices[0]].append(vertices[1]) # Type can be `*Edges` or `*Arcs` depending if is a directed or undirected graph if type == "*Edges\n": self.adj_list[vertices[1]].append(vertices[0]) for i in range(1, self.amnt_vertices): # Initializes any unconnected vertices if i not in self.adj_list.keys(): self.adj_list[i] def get_connected_components(self): ''' Gets the amount of connected components of a graph and the amount of vertices each of them has''' amnt_labels, labeled_vertices = self._label_vertices() label_conter = [0] * amnt_labels for label in labeled_vertices: label_conter[label] += 1 return amnt_labels, label_conter def _label_vertices(self): ''' Labels each connected vertice of a graph ''' labeled_vertices = [-1] * (self.amnt_vertices + 1) label = 0 for i in range(1, self.amnt_vertices): if labeled_vertices[i] == -1: self._labeling_dfs(labeled_vertices, i, label) label += 1 # Ignores index 0, since pajek graph starts at 1 return label, labeled_vertices[1:] def _labeling_dfs(self, labeled_vertices, start, label): ''' Dfs algorithm that labels the connected components of a graph ''' stack = [start] labeled_vertices[start] = label while stack: cur = stack.pop() neighbors = self.adj_list[cur] for n in neighbors: if not labeled_vertices[n] != -1: stack.append(n) labeled_vertices[n] = label def main(): filename = input() filename.strip() graph = Graph() graph.init_pajek_graph(filename) amnt_labels, label_conter = graph.get_connected_components() print(amnt_labels) # Sorts and prints the amount of vertices in each component label_conter.sort(reverse=True) for l in label_conter: print(l) main()
""" This program display a triangle with rigth angle. * ** *** **** ***** ****** ******* ******** ********* """ size = int(input("Enter the size of the triangle (> 1) \n")) cpt = 1 print("Your rigth trinagle") print("=======================") while cpt <= size: print(cpt*"*") cpt += 1
# This program draw a square of certain side according the entered value by the user #import signal from turtle import * side = int(input("Enter the side of the square :\n")) color('blue') width(5) cpt = 1 while cpt <= 4: forward(side) left(90) cpt += 1 # We can put the program on pause using signal.pause() stop = input("Type ENTER to stop the program :\n") exit()
#!/usr/bin/python3.6 #-*- coding:utf8 -*- #This program draw multiple lines from random import randrange from tkinter import * # Functions definitions def drawline(): """ Function to draw a line. """ global x1, y1, x2, y2, color canv.create_line(x1,y1,x2,y2,fill=color) y1, y2 = y1 + 10, y2 -10 def change_color(): """ Function to change the line color. """ global color colors_list = ['red','orange','yellow','green','blue','indigo','purple','pink'] color = colors_list[randrange(8)] # Main Program x1, y1, x2, y2, color = 10, 190, 190, 10, 'dark green' wind = Tk() canv = Canvas(wind, bg='dark grey', width=200, height=200) canv.pack(side=LEFT) btn_quit = Button(wind, text="Quit", command=wind.quit) btn_quit.pack(side=BOTTOM) btn_draw_line = Button(wind, text="Draw a new line", command=drawline) btn_draw_line.pack() btn_change_color = Button(wind, text="Change line color", command=change_color) btn_change_color.pack() wind.mainloop() wind.destroy()
import sys class Library: def __init__(self, list_of_books): self.availablebooks = list_of_books def displayAvailablebooks(self): print("The books we have in our library are as follows:") print("================================") for book in self.availablebooks: print(book) def lend_Book(self, requested_Book): if requested_Book in self.availablebooks: print("The book you requested has now been borrowed") self.availablebooks.remove(requested_Book) else: print("Sorry the book you have requested is currently not in the library") def add_Book(self, returned_Book): self.availablebooks.append(returned_Book) print("Thanks for returning your borrowed book") class Student: def request_Book(self): print("Enter the name of the book you'd like to borrow>>") self.book = input() return self.book def return_Book(self): print("Enter the name of the book you'd like to return>>") self.book = input() return self.book def main(): library = Library(["Munni ki Badnami","Sheela ki Jawani","Hasinao ki Manmani"]) student = Student() done = False while done == False: print(""" ======LIBRARY MENU======= 1. Display all available books 2. Request a book 3. Return a book 4. Exit """) choice = int(input("Enter Choice:")) if choice == 1: library.displayAvailablebooks() elif choice == 2: library.lend_Book(student.request_Book()) elif choice == 3: library.add_Book(student.return_Book()) elif choice == 4: sys.exit() main()
# 从第一个非安全局面出发,根据规律往后找新的非安全局面, # 直到查找范围到达了目标石头数,然后判断是否符合非安全局面 import time import copy # 对于先取者来说是否安全 def nim(n, m): if n == m: return True # 保持n小于m if n > m: n = n + m m = n - m n = n - m exist = [0] recursion = 1 a = 0 b = 0 while a < n: # find min which doesn't exist in the list n_min = find_lack_min(exist, min(a,b)) # print('n_min: ', n_min) a = n_min b = a + recursion recursion += 1 exist.append(a) exist.append(b) print('a: ', a, ' b: ', b) # 如果相等的话,说明现在是非安全情况,先取者必输 if a == n and b == m: return False else: return True def find_lack_min(l, begin): # 当l数组过大时查找耗时, if len(l) > 100: for comp in l: if comp < begin: l.remove(comp) while True: if not begin in l: break begin += 1 return begin if __name__ == '__main__': start = time.time() print(nim(15975, 9873)) print('time: ', time.time()-start)
class Employee: company = "Google" def __init__(self, name, salary,subunit): print("Emplpyee is created ") self.name = name self.salary = salary self.subunit = subunit def getdetails(self): print(f"the name of employee is {self.name}") print(f"the salary of employee is {self.salary}") print(f"the subunit of employee is {self.subunit}") def getsalary(self,signature): print(f"salary for this employee working {self.company} is {self.salary}\n{signature}") @staticmethod def greet(): print("good morning sir") @staticmethod def time(): print("the time is 10am morning") harry = Employee("Harry",100,"youtube") harry.getdetails()
a = 54 #global variable def func1(): global a print(f"print statement 1:{a}") a=8 #local variable if global keyword is not used print(f'print statement 2:{a}') func1() print(f'print statement 3:{a}')
myDict = { "fast":"in quick manner", "Kaif":"a coder", "marks":{1,2,3}, "anotherdict":{'Kaif':'player'} } print(myDict['fast']) print(myDict['Kaif']) myDict['marks']=[22,44] print(myDict['marks']) print(myDict['anotherdict']['Kaif'])
# a=34 # b="Kaif's" #use this if you have single quotes in your strings # b='''Kaif"s i's''' #use this if you have single quotes in your strings # print(a,b) # # print(type(a)) # print(type(b)) # greeting = " Good morning " # name = "Kaif bhai" # print(type(name)) # conatenating the string # c=greeting + name # print(greeting + name) # print(c) # print(name[-1]) #negative index for checking last character # print(name[:9]) #is same as [0:4] # print(name[2:]) #is same as [0:9] # print(name[-4:-1]) name="kaif" d=name[1:4:3] #it will skip the words if 2 print(d)
fruits = ['banana','watermealon','grapes','mangoes'] for item in fruits: print(item)
# def farh(cel): # return (cel*(9/5))+32 # c=0 # f = farh(c) # print("Farehenite temperature is" + str(f)) # print("hello", end=" ") # print("hello", end=" ") # print("hello", end=" ") # print("hello", end=" ") def natural_liter(n): sum = 1 for i in range(n): sum = sum + (i+1) return sum def natural_recurssive(n): if n==1 or n==0: return 1 return n+ natural_recurssive(n-1) a= natural_recurssive(6) print(a)
a= [3,6,9,2,4,23,343,45,44,66] # b=[] # for item in a: # if item%2==0: # b.append(item) # print(b) b= [i for i in a if i%2==0] print(b) # set comperihenison t = [1,2,3,4,1,4,3] s= {i for i in t} print(s)
# Add two numbers # a = 4 # b=455 # print( "the sum of a and b",a+b) # # Reminder when a is divided by b # a=458 # b=15 # print("The remainder when a is divided by b is",a%b) # # use comaprison operator # a=45 # b=4 # print(a<b) # average of two numbers a = input("Enter the first number:") # b = input("Enter the second number:") a= int (a) # b= int (b) sqr=a*a print("The square of a is",sqr)
try: a= int(input("Enter a number")) c=1/a print(c) except ValueError as e: print("Please enter the valid value") print(e) except ZeroDivisionError as e: print("Make sure you are not dividing by zero") print(e) print('thanks for using this code')
# for i in range(1,8): # print(i) for i in range (10): print(i) else: print("This is inside else of for")
class complex: def __init__(self,r,i): self.real = r self.imaginary = i def __add__(self,c): return complex(self.real+c.real, self.imaginary+c.imaginary) def __mul__(self,c): mulReal = self.real*c.real - self.imaginary*c.imaginary mulImg = self.real*c.imaginary + self.imaginary*c.real return complex(mulReal,mulImg) def __str__(self): return f"{self.real} +{self.imaginary}i" c1 = complex(3,2) c2 = complex(1,7) print(c1+c2) print(c1*c2)
#coding: utf-8 peso = float(input("Digite o peso do boxeador: ")) if (peso < 65): print("Categoria Pena") elif (peso >= 65 and peso < 72): print("Categoria Leve") elif (peso >= 72 and peso < 79): print("Categoria Ligeiro") elif (peso >= 79 and peso < 86): print("Categoria Meio Médio") elif (peso >= 86 and peso < 93): print("Categoria Médio") elif (peso >= 93 and peso < 100): print("Categoria Meio Pesado") elif (peso >= 100): print("Categoria Pesado")
#coding: utf-8 n = int(input("Digite um número inteiro: ")) total = 0.0 i = 0 while i < n: valor = float(input("Digite um número real positivo: ")) if (valor > 0): total += valor i += 1 print("Total: {}").format(total)
planets = ["earth", "saturn", "jupiter", "mars", "pluto", "venus"] # The first and second items (index zero and one) first = planets[0:2] # Third and fourth items (index two and three) middle = planets[2:4] # The last two items (index four and five) last = planets[4:6] print(planets) print(first) print(middle) print(last)
num = int(input("Enter a number: ")) if num % 3 == 0: print ("The inputted integer is divisible by 3") else: print ("The inputted integer is not divisible by 3")
import random def read(file_path): """ This function is used to read file. Convert file format into my data structure. Each element in x list is a line in the file. """ x = [] with open(file_path, 'r') as file: for line in file: line = line.strip() # print(line) if line != '': x.append([int(n) for n in list(line)]) return x def gen(file_path, number): """ This function is used to generate fake file. """ with open(file_path, 'w') as file: for _ in range(number): for __ in range(random.randint(0, 50)): file.write('{}'.format(random.randint(0,1))) file.write('\n') if __name__ == '__main__': # gen('test.txt', 10) x = read('test.txt') print(x)
def reorderArrayWithEvenFirst(reorderedArray): next_even, next_odd = 0, len(reorderedArray) - 1 while next_even < next_odd: if reorderedArray[next_even] % 2 == 0: next_even += 1 else: reorderedArray[next_even], reorderedArray[next_odd] = reorderedArray[next_odd], reorderedArray[next_even] next_odd -= 1 def transform_string_to_list_using_for(symbols): returnSeq = [] for symbol in symbols: returnSeq.append(ord(symbol)) return returnSeq def transform_string_to_list_using_listcomp(symbols): return [ord(symbol) for symbol in symbols] def generate_cartesian_product_list_from_two_lists(color_list, size_list): cartesian_product_list = [(color, size) for color in color_list for size in size_list] return cartesian_product_list
def bouncing_balls(height, bounce, window): bounce_count = 1 if float(height) <= 0 or float(bounce) >= 1 or float(bounce) <= 0 or float(window) >= float(height): return -1 else: while height > window: height = height * bounce if height > window: bounce_count += 2 return bounce_count print(bouncing_balls(1.5, 0.66, 1.5)) print(bouncing_balls(3, 1, 1.5))
def openOrSenior(data): """Senior members must be 55 years or older, handicap greater than 7.""" category = [] for member in data: age = member[0] handicap = member[1] if age >= 55 and handicap > 7: category.append("Senior") else: category.append("Open") return category def openOrSenior(data): return ["Senior" if age >= 55 and handicap >= 8 else "Open" for (age, handicap) in data] newMember([[18, 20],[45, 2], [61, 12], [37, 6], [21, 21],[78, 9]])
def FirstFactorial(num): factorial = 1 for i in range(1, num+1): factorial *= i return factorial print(FirstFactorial(22))
#!/usr/bin/env python3 # -*- coding utf-8 -*- #循环 names=['king','lin'] for name in names: print(name) #计算1-10的整数之和 sum=0 for x in [1,2,3,4,5,6,7,8,9,10]: sum+=x print(sum) # range(5) = [0,5) # range(5)生成的序列是从 0 开始小于 5 的整数 print(list(range(5))) #1+2+...+100 sum=0 for x in range(101): sum+=x print(sum) #100以内奇数之和 sum=0 n=99 while n>0: sum+=n n-=2 print(sum) #练习 list=['king','jun','lin'] for name in list: print('Hello:',name)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 使用dict和set ############ dict ################################# # 1. dict 全称 dictionary,在其他语言中也称为 map, 键-值( key-value) # 2. dict 可以用在需要高速查找的很多地方 # 3. 需要牢记的第一条就是 dict 的 key 必须是不可变对象 # 在 Python 中,字符串、整数等都是不可变的,因此,可以放心地作为 key。而 list 是可变的,就不能作为 key. dict={'king':95,'lin':100,'Bob':85} # dict 内部存放的顺序和 key 放入的顺序是没有关系的。 print(dict) print(dict['king']) #修改 dict['king']=90 print(dict['king']) #判断key是否存在 # in print('king' in dict) # get print(dict.get('King')) print(dict.get('King',-1)) #删除一个key dict.pop('Bob') print(dict) ############set#################################### # set 和 dict 的唯一区别仅在于没有存储对应的value s=set([1,2,3]) print(s) # add(key) s.add(4) print(s) # remove(key) s.remove(4) print(s) #两个set 交集、并集 s1=set([1,2,3]) s2=set([2,3,4]) print(s1&s2) print(s1|s2) ########### 再议不可变对象 ############## # str 是不变对象,而 list 是可变对象。 # list list = ['c', 'b', 'a'] print ("list.sort: ", list.sort()) # str str1 = 'abc' print ("origin str1: ", str1) print ("str1.replace('a', 'A'): ", str1.replace('a', 'A')) print ("now str1 = ", str1) str2 = str1.replace('a', 'A') print ("str2 = str1.replace('a', 'A'): ", str2) #练习 key=(1,2,3) d={key} print(d) key=(1,[2,3]) d={key} print(d)
#!/usr/bin/env python3 #-*- coding: utf-8 -*- try: print('try...') r=10/0 print('result:',r) except ZeroDivisionError as e: print('except:',e) finally: print('finally...') print('END') #可以有多个except来捕获不同类型的错误: try: print('try...') r=10/int('a') print('result:',r) except ValueError as e: print('ValueError:',e) except ZeroDivisionError as e: print('ZeroDivisionError:',e) else: print('no error.') finally: print('finally...') print('END') #记录错误 #Python内置的logging模块可以非常容易地记录错误信息: # err_logging.py import logging def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('2') except Exception as e: logging.exception(e) main() print('END') #####调试################## #断言 print('#####断言####') def foo(s): n=int(s) assert n!=0, 'n is zero!' return 10/n def main(): foo(0) #main() print('###logging###') #logging import logging logging.basicConfig(level=logging.INFO) s='1' n=int(s) logging.info('n=%d' % n) print(10/n) print('###pdb###') #pdb s='1' n=int(s) print(10/n) #pdb.set_trace() import pdb s=0 pdb.set_trace() #断点 print(10/s)
#encoding = utf-8 """ @version:0.1 @author: jorian @time: 2020/12/4 13:20 """ def find_prime(num): if num > 1: # 查看因子 for i in range(2, num): if (num % i) == 0: print(num, "is not prime numer") print(i, "*", num//i, "=", num) break else: print(num, "is prime number") else: # 如果输入的数字小于或等于 1,直接返回不是质数 print(num, "is not prime number") num = int(input("please one number: ")) find_prime(num)
#encoding = utf-8 """ @version:0.1 @author: jorian @time: 2020/12/4 16:25 """ def levenshtein_distance(first_word, second_word): if len(first_word) < len(second_word): return levenshtein_distance(second_word, first_world) if len(second_word) == 0: return len(first_word) previous_row = range(len(second_word)+1) for i, c1 in enumerate(first_word): current_row = [i+1] for j, c2 in enumerate(second_word): # 计算增加,删除,修改次数 insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) # 得到最小值,添加到current_row current_row.append(min(insertions, deletions, substitutions)) # 储存previous_row previous_row = current_row # 返回最后的编辑距离 return previous_row[-1]
import random def busqueda_binaria(lista, start, end, objetivo): print(f"Buscando: {objetivo} entre {lista[start]} y {lista[end - 1]}") if start > end: return False medio = (start + end) // 2 if lista[medio] == objetivo: return True elif lista[medio] < objetivo: return busqueda_binaria(lista, medio + 1, end, objetivo) else: return busqueda_binaria(lista, start, medio - 1, objetivo) if __name__ == "__main__": tamano_lista = int(input("De que tamaño será la lista?: ")) objetivo = int(input("Qué número quieres encontrar?: ")) lista = sorted([random.randint(0,100) for i in range(tamano_lista)]) encontrado = busqueda_binaria(lista, 0, len(lista), objetivo) print(lista) print(f"El elemento {objetivo} {'está' if encontrado else 'no está'} en la lista")
words = "It's thanksgiving day. It's my birthday, too!" # finding and replacing print words.find("day") new_string = words.replace("day", "month") print words x = [2, 54, -2, 7, 12, 98] # finding min and max values print min(x) print max(x) y = ['hello', 2, 54, -2, 7, 12, 98, 'world'] # making new list with first and print y[0] # last values of old list print y[len(y)-1] new_list = [] new_list.append(y[0]) new_list.append(y[len(y)-1]) print new_list x = [19, 2, 54, -2, 7, 12, 98, 32, 10, -3, -6] # sorting, splitting, re-inserting x = sorted(x) y = x[:len(x)/2] z = x[len(x)/2:] z.insert(0, y) print z