text
stringlengths
37
1.41M
""" Задание 1""" my_int = 4 print(type(my_int)) my_float = 1.5 print(type(my_float)) a = input ("Введите число:") print(a) number = int(input('Введите число от 0 до 100: ')) while number >= 100 or number < 0: number = int(input('Введите число от 0 до 100: ')) print('Число введено корректно') real_name = 'Яковлева Т.А' p = input('Введите ФИО:') if p == real_name: print('Добро пожаловать!') """ Задание 2""" seconds = int(input ('Введите значение в секундах:')) minutes = seconds // 60 hours = minutes // 60 print("%02d:%02d:%02d" % (hours, minutes % 60, seconds % 60)) """ Задание 3""" number = input('Введите число n: ') comp = int(number) + int(number + number) + int(number + number + number) print('Итоговая сумма:', comp) """ Задание 4""" p = int(input('Введите положительное число:')) Max = int(p % 10) p = int(p / 10) while p > 0: if int(p % 10) > Max: Max = int(p % 10) p = int(p / 10) print('Наибольшее число:', Max) """ Задание 5""" p = float(input("Введите выручку фирмы ")) c = float(input("Введите издержки фирмы ")) if p > c: print(f"Фирма работает с прибылью. Рентабельность выручки {p / c:.2f}") w = int(input("Введите количество сотрудников фирмы ")) print(f"Прибыль в расчете на одного сторудника {p / w:.2f}") elif p == c: print("Фирма работает в ноль") else: print("Фирма работает в убыток") """ Задание 6""" a = int(input("Введите результаты пробежки первого дня в км ")) b = int(input("Введите желаемый результат в км ")) result_day = 1 print(result_day,"-й день: ",a) while a < b: a = a + (0.1 * a) result_day += 1 print(result_day,"-й день: %.2f" % a) print("Вы достигнете желаемых показателей на %.d день" % result_day)
import random arrays = [[1,2,4,3],[1,4,2,3],[1,4,3,2],[1,3,4,2],[1,3,2,4],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,1,3],[2,4,3,1],[3,1,2,4],[3,1,4,2],[3,2,1,4],[3,2,4,1],[3,4,1,2],[3,4,2,1],[4,1,2,3],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2],[4,3,2,1]] average = 0 b = 0 while b<23: a = arrays[b] isSorted = False count = 0; print a while (not isSorted): isSorted = True random.seed() index1 = random.randint(0,3) index2 = random.randint(0,3) temp = a[index1] a[index1] = a[index2] a[index2] = temp for i in range(len(a) - 1): if(a[i] > a[i+1]): isSorted = False count+=1 average += count print count b += 1 print average,"/24=",average/24.0
import os import argparse from Crypto.Cipher import AES # Check arguments used parser = argparse.ArgumentParser() parser.add_argument("iv", help="The iv to use to decrypt", type=str) parser.add_argument("key", help="The key to use to decrypt", type=str) parser.add_argument("-d", "--directory", help="Directory to decrypt", type=str, default=".") args = parser.parse_args() # Get arguments iv = args.iv.encode("utf-8") key = args.key.encode("utf-8") directory = args.directory os.chdir(directory) print("Current directory : {}".format(os.getcwd())) # List files from the current directory filename_list = os.listdir(directory) print("Decryption starts") for filename in filename_list: # Check whether the file should be decrypt if filename.split(".")[-1] == "lock": # If yes # Open ".lock" file and create the corresponding original file filename_original = ".".join(filename.split(".")[:-1]) print(filename_original) file_encrypt = open(filename, "rb") file_decrypt = open(filename_original, "wb") # Read datas, decrypt them and write then into the file data_encrypt = file_encrypt.read() cipher = AES.new(key, AES.MODE_CFB, iv=iv) data_decrypt = cipher.decrypt(data_encrypt) file_decrypt.write(data_decrypt) # Close files file_encrypt.close() file_decrypt.close() os.remove(filename) print("Finish")
def print_two(*args): arg1,arg2,arg3 =args print (f"arg1 :{arg1},arg2 {arg2},arg3 {arg3}.") def print_two_again(arg1, arg2): print(f"arg1: {arg1},agr2: {arg2}") def print_one(arg1): print(f"arg1: {arg1}") def print_none(): print("I got nothing") print_two("shibil","ahamed","just checking") print_two_again("shibil","ahamed") print_one("first") print_none()
print (""" MULTIPLICATION TABLE BETWEEN 1 & 1OO""") print ("enter the which number multiplication table what display") num=int(input(">>>>")) while num!=0: table=range(0,100,num) list=['multiplication table of - {}'.format(num)] list.extend(table) print (list) exit() if num==0: print("dont know how to type a number") exit()
import matplotlib import pandas as pd import matplotlib.pyplot as plt import numpy as np import random import math #Import the dataset df = pd.read_csv("kmeans.csv") #Recording # of rows of the data set rows = df.shape[0] #Recording # of rows of the data set cols = df.shape[1] #Records all the points in the graph points = [] #Number of centroid updating rounds N = 25 #Record the scores for each value of k: scores = [] #Number of k we test for k = 6 #Now label every point based on the point it is closed to. def distance(x,y,centroid = []): #x and y coordinates of the centroid a = centroid[0] b = centroid[1] #Applying the pythagorean theorem. Where k is the distance bewteen #the centroid and the point in question. i = abs(b-y) j = abs(a-x) k = math.sqrt(i ** 2 + j ** 2) return k #The label on each point corresponds with the index of the centroids. #Using an array for each point and updating the 3rd position with the label would work. def label_point(x,y,centroids = []): minimum_distance = 100000 label = 1 counter = 1 for i in centroids: d = distance(x,y,i) if d < minimum_distance: label = counter minimum_distance = d counter += 1 return label #The label on each point corresponds with the index of the centroids. #Using an array for each point and updating the 3rd position with the label works. def get_labels(points = []): labels = [] for i in points: labels.append(i[2]) return labels #Start of program print("Computing the k-Means Elbow Graph from k = 1 to k = " + str(k) + ".") for k_round in range(k): centroids = [] for i in range(N): a = round(random.uniform(0,df.mean()[0]),1) b = round(random.uniform(0, df.mean()[1]),1) centroid = [a,b] centroids.append(centroid) #Label points and put them into array. for i in range(rows): point = df.iloc[i,:] x = point[0] y = point[1] label = label_point(x,y,centroids) point = [x,y,label] points.append(point) #Update centroids N times. for i in range(N): for j in range(len(centroids)): centroid = centroids[j] x_avg = 0 y_avg = 0 count = 0 for t in points: if t[2] == j + 1: x_avg += t[0] y_avg += t[1] count += 1 if count == 0: count = 2 x_avg = x_avg / count y_avg = y_avg / count centroids[j][0] = x_avg centroids[j][1] = y_avg for i in range(len(points)): point = points[i] x = point[0] y = point[1] label = label_point(x,y,centroids) points[i][2] = label #Calculating how good the clustering was. for point in points: score = 0 x = point[0] y = point[1] centroid = centroids[point[2]-1] d = distance(x,y,centroid) score += d ** 2 score = score/(k_round+1) print("The " + str(k_round + 1) + "th round has been computed.") score_array = [(k_round+1),score] scores.append(score_array) for i in range(len(scores)): plt.scatter(scores[i][0],scores[i][1],c='black') plt.xlabel('k-value', fontsize=10) plt.ylabel('Sum of distances to centroid squared over k-value', fontsize=10) plt.show()
from math import log def atwo(n): """If n is power of two, just print it. Otherwise print it with the closest power of two""" if n == 0: print 0, 1 return logn = int(log(n,2)) if 2**logn == n: print n else: print n, 2**(logn+1) if __name__ == '__main__': t = int(raw_input()) for i in xrange(t): n = int(raw_input()) atwo(n)
def binary_to_text(b): def bin_to_char(b): n = int(b,2) if n == 0: return ' ' return chr(ord('A') + n - 1) s = '' for i in xrange(0, len(b), 5): b_char = b[i:i+5] s += bin_to_char(b_char) return s def decrypt(msg, r, c): matrix = [[None for j in xrange(c)] for i in xrange(r)] filled = [[0 for j in xrange(c)] for i in xrange(r)] for i in xrange(r): for j in xrange(c): matrix[i][j] = msg[i*c+j] s = "" x = 0 y = 0 direction = 'r' # right num_read = 0 while num_read < r*c: s += matrix[x][y] num_read += 1 filled[x][y] = 1 if direction=='r': if y<c-1 and filled[x][y+1]==0: y += 1 else: x += 1 direction='d' # down elif direction=='d': if x<r-1 and filled[x+1][y]==0: x += 1 else: y -= 1 direction='l' # left elif direction=='l': if y>0 and filled[x][y-1] == 0: y -= 1 else: x -= 1 direction='u' # up elif direction=='u': if x>0 and filled[x-1][y] == 0: x -= 1 else: y += 1 direction = 'r' return s if __name__ == '__main__': t = int(raw_input()) for i in xrange(t): r, c, s = raw_input().split() print i+1, binary_to_text(decrypt(s, int(r), int(c)))
def amusing(k): num_digits = 1 while 2**num_digits < k: k -= 2**num_digits num_digits += 1 # the number has <num_digits> digits num = '' k -= 1 for i in xrange(num_digits): if k % 2 == 1: num += '6' k -= 1 else: num += '5' k /= 2 return num[::-1] if __name__ == '__main__': t = int(raw_input()) for i in xrange(t): n = int(raw_input()) print amusing(n)
if __name__ == '__main__': t = int(raw_input()) for i in xrange(t): n, unit = raw_input().split() n = float(n) print i+1, if unit=='kg': print '%.4f lb' % (n*2.2046) elif unit=='l': print '%.4f g' % (n*0.2642) elif unit=='lb': print '%.4f kg' % (n*0.4536) elif unit=='g': print '%.4f l' % (n*3.7854)
T = int(raw_input()) while T > 0: T -= 1 N = int(raw_input()) words = raw_input().split() eng_words = [w for w in words if not w.startswith('#')] if not eng_words: print " ".join(words) else: eng_word = eng_words[0] index = words.index(eng_word) for x in xrange(index+1, len(words)): print words[x], print words[index], for x in xrange(index): print words[x], print ""
"""http://www.spoj.com/problems/TEST/""" def test(): while True: x = int(raw_input()) if x == 42: break print x test()
# Odd number from 1 to 1000 for i in range(1,1000,2): print i # Multiples of 5 from 5 to 1,000,000 for i in range (5, 1000000, 5): print i # Sum of all in an array a = [1, 2, 5, 10, 255, 3] sum = 0 for data in a: sum = sum + data print "sum:", sum # Average of array avg = sum/len(a) print "Average: ", avg
#coding=utf8 test_str = '[(({[]{}}))]' test_str2 = '[(({[]{}}))]]' def opposite(c): d = {'(': ')', '[': ']', '{': '}'} return d[c] def valid(string): stack = [] for c in string: if len(stack) < 1: stack.append(c) else: if opposite(stack[-1]) == c: stack.pop() else: stack.append(c) return False if stack else True print(valid(test_str)) print(valid(test_str2))
def bubble_sort(items): length = len(items) for i in range(0,length): swapped = False for element in range(0,length-i-1): if items[element]> items[element + 1]: hold= items[element + 1] items[element + 1]=items[element] items[element]= hold swapped= True if not swapped:break return items def merge_sort(items): """ Return array of items, sorted in ascending order """ if len(items) >1: mid = len(items)//2 #Finding the mid of the array L = items[:mid] # Dividing the array elements R = items[mid:] # into 2 halves merge_sort(L) # Sorting the first half merge_sort(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: items[k] = L[i] i+=1 else: items[k] = R[j] j+=1 k+=1 # Checking if any element was left while i < len(L): items[k] = L[i] i+=1 k+=1 while j < len(R): items[k] = R[j] j+=1 k+=1 return items def quick_sort(items,index=-1): '''Return array of items, sorted in ascending order''' len_i = len(items) if len_i <= 1: # Logic Error # identified with test run [1,5,4,3, 2, 6, 5, 4, 3, 8, 6, 5, 3, 1] # len <= 1 return items pivot = items[index] small = [] large = [] dup = [] for i in items: if i < pivot: small.append(i) elif i > pivot: large.append(i) elif i == pivot: dup.append(i) small = quick_sort(small) large = quick_sort(large) return small + dup + large i2 = merge_sort(items[mid_point:]) return merge(i1, i2)
#!/usr/bin/env python '''Provides the basic implementation for the pairwise interaction segment activity coefficient (SAC) equations. This code favors readability, please check the accompayning article for the equation numbers cited here. ''' from abc import abstractmethod import math from copy import deepcopy from numpy import zeros RGAS = 0.001985875279 '''Gas constant in kcal/mol/K.''' RGAS_SI = 8.314462618153 '''Gas constant in J/mol/K.''' DEFAULT_Q_EFF = math.pi * 1.2**2 '''Default contact surface area in AA2''' class SAC: ''' This is a basic code for a system consisting in pairwise interacting surface segments. The user should derive this class and provide an implementation for the interaction energies, `calc_u` method. Optionally, a `calc_du_dT` should also be provided. ''' def __init__(self, Q_eff=DEFAULT_Q_EFF, tol=1e-8, max_iter=400): self.tol = tol; self.max_iter = max_iter self.Q_eff = Q_eff; @abstractmethod def calc_u(self, T, i, j, m, n): ''' This method should calculate the interaction energy for the pair `m-n`. The segment `m` is from molecule `i` and `n` from molecule `j`. Different model variants should implement this method. The returned value is expected to be in `kcal/mol`. ''' pass def calc_du_dT(self, T, i, j, m, n): ''' Override this method and calculate the derivative of the interaction energy with respect to the temperature (in case it depends on it). ''' return 0 def set_compounds(self, Q): ''' Sets the compound list by actually sending the segment areas in AA2 of each compound in the Q argument. An example on how to build the Q argument for a binary mixture with 1 compound with 3 segments and another with just 1 segment follows: ``` Q_1 = [20.167, 21.97, 80.23] Q_2 = [191.93] Q = [Q_1, Q_2] ``` ''' self.ncomps = len(Q) self.Q = Q # Allocate the theta arrays, same size the given compound areas (Q) self.theta = deepcopy(Q) self.theta_pure = deepcopy(Q) # The segment gammas we initialize all as 1.0 self.seg_gamma = [[1.0]*len(Q[i]) for i in range(self.ncomps)] self.seg_gamma_pure = [[1.0]*len(Q[i]) for i in range(self.ncomps)] # Psi and u have 4 dimensions [i][j][m][n], the first 2 we allocate here self.psi = [[0 for x in range(self.ncomps)] for y in range(self.ncomps)] self.u = [[0 for x in range(self.ncomps)] for y in range(self.ncomps)] # The compound total areas self.q = [0]*self.ncomps for i in range(self.ncomps): # Calculating the compound total areas for m in range(len(Q[i])): self.q[i] += Q[i][m] # Calculating the area fractions for pure compounds (theta_pure, Eq. 28) for m in range(len(self.theta_pure[i])): self.theta_pure[i][m] = Q[i][m]/self.q[i] # Allocate the psi array for [i][j][m][n] for j in range(self.ncomps): psi_ij = [[0] * len(Q[j]) for i in range(len(Q[i]))] self.psi[i][j] = psi_ij u_ij = [[0] * len(Q[j]) for i in range(len(Q[i]))] self.u[i][j] = u_ij # By default 298.15 K and equimolar (if not overriden later) self.set_temperature(298.15) self.set_composition([1.0/self.ncomps] * self.ncomps) def set_temperature(self, T): ''' Sets the temperature for all future calculations. This will update all u and psi elements as well as solve all the pure compound gammas (as they depend only on temperature). ''' self.T = T; self.inv_RT = 1/(RGAS * T) # Update the psi array for i in range(self.ncomps): for j in range(self.ncomps): psi_ij = self.psi[i][j] u_ij = self.u[i][j] for m in range(len(self.Q[i])): for n in range(len(self.Q[j])): u_ij[m][n] = self.calc_u(T, i, j, m, n) # These are the Boltzmann factors, Eq. 2 psi_ij[m][n] = math.exp(-u_ij[m][n] * self.inv_RT) # Converge the pure compound segment gammas, they depend only on temperature self.__solve_gamma(True, self.theta_pure, self.seg_gamma_pure) def set_composition(self, z): ''' Sets the molar fraction array z, the elements must sum 1. ''' self.z = z # Reset the segment gammas we initialize all as 1.0 self.seg_gamma = [[1.0]*len(self.theta[i]) for i in range(self.ncomps)] # First calculate the mixture average area q_avg = 0 for i in range(self.ncomps): q_avg += z[i] * self.q[i] # Calculate theta for the mixture, Eq. 6 for i in range(self.ncomps): for m in range(len(self.Q[i])): self.theta[i][m] = z[i] * self.Q[i][m] / q_avg self.q_avg = q_avg def calc_ln_gamma(self): ''' Calculates the logarithm of the activity coefficients. Assumes the composition and temperature are already set. This method will also solve all the gamma's for the mixtre and has to be called before asking for helmholtz or internal energies. ''' # First we converge the mixture gammas self.__solve_gamma(False, self.theta, self.seg_gamma) # Initialize the ln gamma vector with all zeros and then add the # contribution of all segments for every compound. ln_gamma = [0] * self.ncomps; for i in range(self.ncomps): Q_i = self.Q[i] for m in range(len(Q_i)): ln_seg_gamma = math.log(self.seg_gamma[i][m]) ln_seg_gamma_pure = math.log(self.seg_gamma_pure[i][m]) nu_i_m = Q_i[m]/self.Q_eff # Compound activities, Eq. 27 ln_gamma[i] += nu_i_m * (ln_seg_gamma - ln_seg_gamma_pure) return ln_gamma def __solve_gamma(self, for_pure, theta, seg_gamma): ''' Method to solve the "self-consistency" equation (Eq. 10) by successive substitution. This method should not be called directly by the user. We use the same implementation for mixtures and pure compounds, given the theta and seg_gamma arrays. The only difference for pure compounds is that we skip the cross-compound interactions so we can have a single code base for this. ''' niter = 0 gamma_norm = 0 while True: niter = niter+1 gamma_norm_new = 0 for i in range(self.ncomps): seg_gamma_i = seg_gamma[i] for m in range(len(seg_gamma_i)): # The sum we need to invert in Eq 10 theta_gamma_psi_sum = 0.0 for j in range(self.ncomps): if for_pure and i!=j: continue # when converging the pure substance only i==j matters theta_j = theta[j] seg_gammaj = seg_gamma[j] psi_ij = self.psi[i][j] for n in range(len(theta_j)): psi_mn = psi_ij[m][n] if len(theta_j) == 1 and for_pure: # Successive substitution can have problems to converge correctly # for a pure component with single segment area, but for this case: # seg_gamma = sqrt(1/psi_mn), so then the sum is as follows: theta_gamma_psi_sum = 1.0/math.sqrt(1.0/psi_mn) else: theta_gamma_psi_sum += theta_j[n] * seg_gammaj[n] * psi_mn # succesive substitution according to Eq. 10 damped with the latest value seg_gamma_i[m] = (seg_gamma_i[m] + 1.0/theta_gamma_psi_sum)/2 # calculate a norm2 with our gamma's to check the convergence gamma_norm_new += seg_gamma_i[m]**2 # finish the norm calculation and check for convergence gamma_norm_new = math.sqrt(gamma_norm_new) if abs((gamma_norm_new - gamma_norm)/gamma_norm_new) <= self.tol: break gamma_norm = gamma_norm_new; if niter > self.max_iter: raise Exception(f"Maximum number of iterations when solving gamma: {self.max_iter}") def get_helmholtz(self): ''' Returns the residual Helmholtz energy (divided by RT) for the mixture. ''' a = 0 for i in range(self.ncomps): seg_gamma_i = self.seg_gamma[i] Q_i = self.Q[i] for m in range(len(seg_gamma_i)): nu_i_m = Q_i[m]/self.Q_eff # Eq. 23 a += self.z[i] * nu_i_m * math.log(seg_gamma_i[m]) return a def __get_partial_helmholtz(self, i, for_pure): ''' Returns the residual partial Helmholtz energy (divided by RT) for the compound i. If the `for_pure` flag is `True`, then returns the pure compound version. ''' ai = 0 seg_gamma_i = self.seg_gamma_pure[i] if for_pure else self.seg_gamma[i] Q_i = self.Q[i] for m in range(len(seg_gamma_i)): nu_i_m = Q_i[m]/self.Q_eff # Eq. 25 ai += nu_i_m * math.log(seg_gamma_i[m]) return ai def get_helmholtz_partial(self, i): ''' Returns the residual partial Helmholtz energy (divided by RT) for the compound i. ''' return self.__get_partial_helmholtz(i, False); def get_helmholtz_pure(self, i): ''' Returns the residual partial Helmholtz energy (divided by RT) for the compound i. ''' return self.__get_partial_helmholtz(i, True); def get_energy_pure(self, i): ''' Returns the residual internal energy (divided by RT) for the pure compound i. ''' ui = 0 seg_gamma_i = self.seg_gamma_pure[i] theta_i = self.theta_pure[i] nu_i = self.q[i]/self.Q_eff for j in range(self.ncomps): if i!=j: continue # it is pure, only i==j matters for m in range(len(seg_gamma_i)): theta_j = self.theta_pure[j] seg_gamma_j = self.seg_gamma_pure[j] psi_ij = self.psi[i][j] u_ij = self.u[i][j] for n in range(len(theta_j)): # Eq. 7 theta_mn = theta_i[m]*seg_gamma_i[m] * theta_j[n]*seg_gamma_j[n] * psi_ij[m][n] du_dT = self.calc_du_dT(self.T, i, j, m, n) # Eq. 35 (see also Eq. 32) ui += nu_i/2 * theta_mn * (u_ij[m][n] - self.T*du_dT) return ui * self.inv_RT def get_energy(self): ''' Returns the residual internal energy (divided by RT) for the mixture. ''' u = 0 nu = self.q_avg/self.Q_eff for i in range(self.ncomps): seg_gamma_i = self.seg_gamma[i] theta_i = self.theta[i] for j in range(self.ncomps): for m in range(len(seg_gamma_i)): theta_j = self.theta[j] seg_gamma_j = self.seg_gamma[j] psi_ij = self.psi[i][j] u_ij = self.u[i][j] for n in range(len(theta_j)): # Eq. 7 theta_mn = theta_i[m]*seg_gamma_i[m] * theta_j[n]*seg_gamma_j[n] * psi_ij[m][n] du_dT = self.calc_du_dT(self.T, i, j, m, n) # Eq. 35 (see also Eq. 32) u += nu/2 * theta_mn * (u_ij[m][n] - self.T*du_dT) return u * self.inv_RT def get_nonrandom(self): ''' Returns the nonrandom factors for every segment pair. ''' alpha = deepcopy(self.psi) for i in range(self.ncomps): seg_gamma_i = self.seg_gamma[i] theta_i = self.theta[i] for j in range(self.ncomps): for m in range(len(seg_gamma_i)): theta_j = self.theta[j] seg_gamma_j = self.seg_gamma[j] psi_ij = self.psi[i][j] for n in range(len(theta_j)): # Eq. 8 alpha[i][j][m][n] = seg_gamma_i[m]*seg_gamma_j[n]*psi_ij[m][n] return alpha
''' 두 정수(a, b)를 입력받아 a가 b보다 크면 1을, a가 b보다 작거나 같으면 0을 출력하는 프로그램을 작성해보자. 두 정수(a, b)를 입력받아 a와 b가 같으면 1을, 같지 않으면 0을 출력하는 프로그램을 작성해보자. 두 정수(a, b)를 입력받아 b가 a보다 크거나 같으면 1을, 그렇지 않으면 0을 출력하는 프로그램을 작성해보자. 두 정수(a, b)를 입력받아 a와 b가 서로 다르면 1을, 그렇지 않으면 0을 출력하는 프로그램을 작성해보자. ''' a, b = map(int, input().split()) print(int(a>b)) ''' a, b = map(int, input().split()) print(int(a==b)) ''' ''' a, b = map(int, input().split()) print(int(b>=a)) ''' ''' a, b = map(int, input().split()) print(int(b!=a)) '''
''' 단어를 1개 입력받는다. 입력받은 단어(영어)의 각 문자를 한줄에 한 문자씩 분리해 출력한다. ''' a = input() for i in a: print("\'{}\'".format(i))
''' 두 개의 참(1) 또는 거짓(0)이 입력될 때, 모두 참일 때에만 참을 출력하는 프로그램을 작성해보자. 두 개의 참(1) 또는 거짓(0)이 입력될 때, 하나라도 참이면 참을 출력하는 프로그램을 작성해보자. 두 가지의 참(1) 또는 거짓(0)이 입력될 때, 참/거짓이 서로 다를 때에만 참을 출력하는 프로그램을 작성해보자. 두 개의 참(1) 또는 거짓(0)이 입력될 때, 참/거짓이 서로 같을 때에만 참이 계산되는 프로그램을 작성해보자. 두 개의 참(1) 또는 거짓(0)이 입력될 때, 모두 거짓일 때에만 참이 계산되는 프로그램을 작성해보자. ''' a, b = map(int, input().split()) print(int(a and b)) ''' a, b = map(int, input().split()) print(int(a or b)) ''' ''' a, b = map(int, input().split()) print(int(a ^ b)) ''' ''' a, b = map(int, input().split()) print(int(not(a ^ b))) ''' ''' a, b = map(int, input().split()) print(int(not(a or b))) '''
''' 실수(float) 1개를 입력받아 저장한 후, 저장되어 있는 값을 소수점 셋 째 자리에서 반올림하여 소수점 이하 둘 째 자리까지 출력하시오. ''' a = float(input()) print('%.2f' %a)
#---------------------------------------------- #--------- Strings methds II ---------- #---------------------------------------------- # Str.split() => devide the string on word based on the space(defultSepartor) between words # # Str.split("Separtor",Number) => Separtor == , or - ... Number == 2, 3, 4... # Str.rsplit(",",Number) => like the preveous one but start from the right side a = "I love C And Python and Sql" print(a.split()) # it return a list of items print(type(a.split())) b = "I love C And Python and Sql" print(b.rsplit( " ", 4)) # it will return a list of 3 items and the rest as another Item c = "I-love-C-And-Python-and-Sql" print(c.split("-", 3)) # it return a list of items listOfItem = c.split("-") print("the value of this item is : " + listOfItem[0] + " " + listOfItem[1] + " " + listOfItem[2]) # Str.center(Number) ==> take a NumberParameter and retuen the string arounded by the charterParameter or the defult (Space) # Str.center(Number,"charterPara") ==> take a NumberParameter and retuen the string arounded by the charterParameter name = "zakaria" print(name.center(11)) # ==> " zakaria " print(name.center(11, "&")) # ==> "&&zakaria&&" # Str.count() ==> return the number of word specific inside the string # Str.count("charter", Start, End) ==> countVariable = "I c love and python but forver c" print(countVariable.count("c")) print(countVariable.count("c", 2, 15)) # it return one which is the first C # Str.swapcade() ==> it change charter from capital to small and vice versa aa = "i loVe Python AND c" bb = "I LOVE python and C" print(aa.swapcase()) # => I LOvE pYTHON and C print(bb.swapcase()) # => i love PYTHON AND c # startwith() ("Charter", Start, End) ==> return booleen value if the charter exist # endtwith() ("Charter", Start, End) ==> return booleen value if the charter exist sWith = "i love c language" print(sWith.startswith("i")) # true print(sWith.startswith("l", 4, 10)) # false print(sWith.startswith("c", -10, -1)) # true eWith = "i love c language" print(eWith.endswith("age")) print(eWith.endswith("c", 1, -9))
uppercase=0 lowercase=0 result_dict={'Lowercase':0,'Uppercase':0} with open("test.txt",'r') as file1: list1 = file1.read() for i in list1: if i.islower(): lowercase+=1 result_dict['Lowercase']+=1 elif i.isupper(): uppercase+=1 result_dict['Uppercase']+=1 print(uppercase,lowercase) print(result_dict)
l1=[1,2,3,4,5] l2=list([x**2 for x in l1]) print(l2) l3=[1,2,3,4,5] l4=[3,4,5,6,7] set1=set(l3) set2=set(l4) set3=set1.intersection(set2) print(set3)
x=input("Enter word: ") y=[] y=list(x) print(x) z=y[::-1] print(z) a=x[::-1] print(a)
class MyVehicle: def __init__(self,make,model,year): self.make = make self.model = model self.year = year def vehicle_name(self): print("This car is : " + str(self.make) + " " + str(self.model) + " " + str(self.year)) v1 = MyVehicle("Alfa","Milano",1987) print(v1.make,v1.model,v1.year) v1.vehicle_name()
st="nneigheigh" snd = "neigh" x = {v: k for k, v in enumerate(snd)} print(x) for i in range(len(st)): print(str(st[i]) + str(x.get(st[i])))
dict1={} num_stu=int(input("Enter number of students: ")) print(num_stu) for i in range(0,num_stu): stu_name = input("Enter student name: ") stu_age = input("Enter student age: ") stu_grade = input("Enter student grade: ") dict1[stu_name]={stu_age,stu_grade} print (dict1)
#L=[] #print(L) fruit = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] #print(len(fruit)) #print(fruit[1]) #print(fruit[-1]) #print(fruit[2:5]) #print(fruit[-1:-6:-2]) #fruit[1]="pappaya" #print(fruit) #for x in fruit: # print(x) #if "apple" in fruit: # print("Yes, 'apple' is in the fruits list") #else: # print("No, 'apple' is not in the fruits list") #fruit.append("guava") #print(fruit) #fruit.insert(3,"plum") #print(fruit) #print(fruit.count("banana")) #fruit.sort(reverse=True) #print(fruit) #fruit.reverse() #print(fruit) #fruit.remove("plum") #print(fruit) #print(fruit.pop()) #print(fruit) #print(fruit.pop(2)) #print(fruit) #del fruit[0] #print(fruit) #list1 = ["a", "b" , "c"] #list2 = [1, 2, 3] #list1.extend(list2) #print(list1) #list1 = ["a", "b" , "c"] #list2 = [1, 2, 3] #print(list1+list2) #print(list2 * 3) #print(list1 == list2) #print(list1 > list2) #list1 = ["a", "b", "c"] #list2=['a', 'b','ca'] #print(list1>list2) list1 = ["abc", ["b", "c"], 42] print(list1[0][1]) print(list1[1][1]) print(list1[2][1]) list1 = [[1,2,3],[4,5,6],[7,8,9]] print(list1[2][1])
maarks=eval(input("enter elements in ():")) sum=0 n=len(marks) for i in range(n): sum=sum+marks[i] print("Sum of all marks=",sum) print("average of the course=",sum/n) print('highest mark=",max(marks)) print('lowest mark=',min(marks))
class School(): okulTuru= "okul tipi" def __init__(self, okulAdı, okulTuru, ogretmen, ogrenci, sınıf): self.okulAdı = okulAdı self.okulTuru = okulTuru self.ogretmen = ogretmen self.ogrenci = ogrenci self.sınıf = sınıf O1 = School("Gazi Şahin", "İlkÖğretim Okulu", 16, 300, 20) O2 = School("Keçiören", "Anadolu Lisesi", 22, 452, 37) O3 = School("Hacettepe", "Üniversitesi", 32, 1200, 54) Schools = [O1, O2, O3] for okul in Schools: print(okul.okulAdı, okul.okulTuru, okul.ogretmen, okul.ogrenci, okul.sınıf)
def add(x,y): z=x+y print(z) def sub(x,y): z=x-y print(z) a=100 b=50 add(a,b) sub(a,b)
F = input() C = (float(F)- 32) / 1.8 C_S = str(C) F_S = str(F) print ("{}F is equal to {}C.".format(F,C))
num = input("Enter a number:") word= input("Enter a noun:") space = " " if num == "1": print (num + space + word) elif num > "1" or num < "1": if word[-2:] == "fe": word2 = word[:-2] ves = "ves" print(num + space + word2 + ves) elif word[-2:] == "sh" or "ch": es="es" print(num + space + word + es) elif word[-2:] == "ay" or word[-2:] == "oy" or word[-2:] =="uy" or word[-2:] == "ey": s = "s" print( num + space + word + s)
import time import sys ##setting recursion limit for testing large numbers of n later sys.setrecursionlimit(1000000) ##f, 2**n ##Using recursion for benefit of memoization def f(n): ##anything to power of 0 is 1 if n==0: return 1 ##2 to power of 1 is 2 elif n==1: return 2 ##2 to power of n = 2*2 to power of n-1 else: return 2*f(n-1) ##g: g(n) = g(n-1)+2*g(n-2) def g(n): ##g(0)==0 if n == 0: return 0 ##g(1)==1 elif n==1: return 1 ##g(n)== g(n-1)+2*g(n-2) else: return (g(n-1)*(g(n-1)+(2*(g(n-2))))) ##Task 2 ##Function F ##n=1000: memoized function is approx .0005 seconds quicker ##n=750: memoized function approx .00048 seconds quicker ##n=2500: memoized function approx .0015 seconds quicker ##Function G ##n=20: memoized function is approx 6.8 seconds quicker ##n=22: memoized function approx 39 seconds quicker ##n=25: memoized function approx 1.15 seconds quicker #basic memoize function def memoize(f): #stores results in cache dictionary cache = {} #helper function to fill cache def helper(n): if n not in cache: cache[n] = f(n) return cache[n] return helper ##applying memoize function to mf, a duplicate of f @memoize def mf(n): if n==0: return 1 elif n==1: return 2 else: return 2*mf(n-1) ##applying memoize function to mg, a duplicate of g @memoize def mg(n): if n == 0: return 0 elif n==1: return 1 else: return mg(n-1)*(mg(n-1)+(2*(mg(n-2)))) ##Loops I used for checking times for both functions print("Function F:") for i in range(20): a = time.time() f(1000) b = time.time() mf(1000) c = time.time() if (c-b) < (b-a): print("memoized function was",(b-a)-(c-b),"seconds quicker") elif (c-b)==(b-a): print("Both functions took approx the same time.") else: print("regular function was",(c-b)-(b-a),"seconds quicker") print("\nFunction G:") for i in range(20): a = time.time() g(20) b = time.time() mg(20) c = time.time() if (c-b) < (b-a): print("memoized function was",(b-a)-(c-b),"seconds quicker") elif (c-b)==(b-a): print("Both functions took approx the same time.") else: print("regular function was",(c-b)-(b-a),"seconds quicker")
# Prompting user for number and then multipies that number by itself user_number = input("Enter a number: ") print("Your number squared is: " + str(int(user_number) ** 2))
#s = "Ivan" #print(s[2::-1]) s = "abcdefigh" for index in range(len(s)): if s[index] == 'i' or s[index] == 'u': print("There is an i or u") for char in s: if char == 'i' or char =='u': print("There is an i or u")
from directions import Directions def introductoryMessage(): print("\n\n") print("Welcome to the python driving directions web service app") print("To get driving directions, enter a starting point and an ending destination") print("\n") def applicationInstructions(): print("Acceptable formats:") print(" ### street, city, state ( optional: zip/postal )") print(" city, state ( optional: zip/postal )") print(" city") print(" zip/postal ") print("\n") input("Press Enter to begin") print("\n") def main(): #print introduction and instructions introductoryMessage() applicationInstructions() running = True while running: # gather start and endpoints start = input("Enter a start address: ")#"Thomaston, CT" end = input("Enter a destination address: ")#"burrlington, CT" print("\n") #create directions instance d = Directions(start,end) #make REST request treeRoot = d.requestData() #extract data d.extractData(treeRoot) #print results try: print(d.getStartPoint()) print(d.getDirections()) print(d.getTotalMiles()) print(d.getEndPoint()) except: print("Something has gone wrong. Directions cannot be retrieved") print("check the start or destination address") print("\n") cont = input("Press Enter to get more directions or enter 0 to quit: ") if cont == "0": running = False print("Good Bye\n") if __name__ == "__main__": main()
''' Created on Feb 19, 2015 @author: Ankur ''' import pygame, math,random import numpy as np from sympy.mpmath import unitvector class Color(): white=(255,255,255) blue = (0,255,255) red = (255,0,0) snow = (205,201,201) palegreen= (152,251,152) def __init__(self): pass def randomcolor(self): randcolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) return randcolor width,height = (700,530) screen = pygame.display.set_mode((width, height)) debug = False class Ball(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("./resource/ball.gif") self.rect = self.image.get_rect() #this is the first position from where the ball would be loaded, #need to randomize it self.rect.centerx,self.rect.centery = (100,100) self.speedx = 0.5 self.speedy = 2 self.angle = math.pi/2 def update(self): global screen #check if adding this speed makes the coordinates go beyond the limits of circle radius = 250 dist = math.hypot(self.rect.x+self.speedx - 266 ,self.rect.y+self.speedy -266) if(dist < radius): self.rect.x +=self.speedx self.rect.y +=self.speedy else: #fix the position here print "reaching outside------------>" screen.blit(self.image, self.rect) self.collisionwithcircle() def collisionwithcircle(self): #this the direction vector of the ball dx,dy = (self.rect.centerx -266,self.rect.centery-266) #dx and dy are the direction vectors from center of circle dist = (dx**2 +dy**2)**0.5 maxdist = 250 - self.rect.size[0]/2 +1 #print dist, maxdist, self.rect.center # self.speedx , self.speedy are the velocity vectors if(dist > maxdist): print "collision occurred" magofdirection = math.hypot(dx, dy) if(magofdirection == 0): magofdirection = 1 unitvectorx = float(dx/magofdirection) unitvectory = float(dy/magofdirection) dotproduct = self.speedx*unitvectorx + self.speedy*unitvectory self.speedx = -2*dotproduct*unitvectorx + self.speedx self.speedy = -2*dotproduct*unitvectory + self.speedy print self.speedx, self.speedy def display(self): global screen #pygame.draw.circle(screen, self.color, (self.x,self.y), self.size, self.width) class Background(): def __init__(self,(x,y),size,width,color): self.colorobj = Color() self.size = size self.width = width self.color = color self.myimage = pygame.image.load("./resource/bg4.png") self.imagerect = self.myimage.get_rect() self.imagerect.x,self.imagerect.y = ( 10, 10) self.x,self.y = self.imagerect.center def update(self): global screen screen.blit(self.myimage, self.imagerect) #use it to produce game-over effects for few seconds #self.color = self.colorobj.randomcolor() pygame.draw.circle(screen, self.color, (self.x,self.y), self.size, self.width) class Bat(pygame.sprite.Sprite): def __init__(self,color,batdimension,startpos,speed): pygame.sprite.Sprite.__init__(self) self.color = color self.width = width self.image = pygame.Surface(batdimension) self.image.fill(Color.white) self.image.set_colorkey(Color.white) self.x= 0 self.y =0 self.angle = 1 self.theta = 0 self.speed = speed self.batdimx, self.batdimy = batdimension self.image = pygame.image.load("./resource/bat_100_20.png") if(debug): pygame.draw.rect(self.image, self.color, (self.x,self.y,self.batdimx, self.batdimy ), self.width) self.rot = pygame.transform.rotate(self.image,self.angle ) self.rect = self.rot.get_rect() self.rect.center = (266,266) def findPointOnCircle(self,deg): """ Give an angle in degrees and we will get a corresponding point on circle w.r.t to this angle in clockwise. """ rad = np.deg2rad(deg) y = 266 - 250 * math.sin(rad) x = 266 + 250 * math.cos(rad) return int(x),int(y) def update(self): global screen #self.theta += self.speed if(self.theta > 360): self.theta = 0 self.angle = float(self.theta) - float(self.batdimx/213) self.rot = pygame.transform.rotate(self.image,self.angle) self.rect = self.rot.get_rect() self.rect.center = self.findPointOnCircle(self.theta) screen.blit(self.rot,self.rect) def moveBat(self,js_hor,js_vert): #here took -0.1 since the buffer is not being cleared properly, values is being set to -0.000003 if(js_vert < -0.1): self.theta += self.speed if(js_vert >0.0 ): self.theta -=self.speed def display(self): global screen #pygame.draw.line(screen, self.color, self.start_pos, self.end_pos, 5) # pygame.draw.rect(self.rot, self.color, (self.x,self.y,20,20), self.width) all_sprites = pygame.sprite.Group() class GameState: RUNNING, PAUSED, RESETTED, STOPPED = range(0, 4) class CMain(): def __init__(self): self.bat1 = None self.bat2 = None self.gamestate = None self.color = Color() pygame.init() pygame.joystick.init() self.joystickCount = pygame.joystick.get_count() for i in range(self.joystickCount): #We need to initialize the individual joystick instances to receive the events pygame.joystick.Joystick(i).init() def main(self): self.gamestate = GameState.STOPPED running = True backg = Background((width/2,height/2),253,5,Color.palegreen) bat1 = Bat(Color.red,(10,90),(512,253),10) bat2 = Bat(Color.blue,(10,50),(0,253),-5) ball = Ball() all_sprites.add(bat1) all_sprites.add(bat2) all_sprites.add(ball) clock = pygame.time.Clock() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.JOYBUTTONDOWN: if(self.gamestate == GameState.STOPPED): self.gamestate = GameState.RUNNING #when the player presses start button then the joystick gets activated #game state will change here to started. self.bat1 = pygame.joystick.Joystick(event.joy) if event.type == pygame.JOYAXISMOTION: if(self.gamestate == GameState.RUNNING): jy_bat1_horizontal = (self.bat1.get_axis(0)) jy_bat1_vertical = (self.bat1.get_axis(1)) #print jy_bat1_horizontal,jy_bat1_vertical bat1.moveBat(jy_bat1_horizontal, jy_bat1_vertical) #just clearing the variables jy_bat1_horizontal = 0 jy_bat1_vertical = 0 ''' if(jy_bat1_horizontal < 0 ): print "horizontal negative" elif(jy_bat1_horizontal > 0 ): print "horizontal positive" elif( jy_bat1_vertical <0 ): print "vertical positive" elif(jy_bat1_vertical >0 ): print "vertical negative" ''' screen.fill(Color.white) backg.update() all_sprites.update() pygame.display.flip() clock.tick(60) pygame.quit() if __name__ == "__main__": obj = CMain() obj.main()
import turtle def draw_snake(rad, angle, len, neckrad): for i in range(len): turtle.circle(rad, angle) turtle.circle(-rad, angle) turtle.circle(rad, angle / 2) turtle.fd(rad) turtle.circle(neckrad + 1, 180) turtle.fd(rad * 2 / 3) def draw_tangle(length,seths): for i in range(3): turtle.fd(length) turtle.seth(seths) seths +=seths def main(): turtle.setup(1300, 800, 0, 0) pythonsize = 20 turtle.pensize(pythonsize) turtle.pencolor("lightgreen") turtle.seth(0) # draw_snake(40, 80, 5, pythonsize / 2) 画蛇 draw_tangle(100,120) #画三角 main()
import threading def add_up(): return local_add.x1 + local_add.x2 def run_thread(x, y): print('Thread {0} is running...'.format(threading.current_thread().name)) lock.acquire() try: local_add.x1, local_add.x2 = x, y print('The finally result is {0} in {1}'.format(add_up(), threading.current_thread().name)) finally: lock.release() if __name__ == '__main__': print('Thread {0} is running...'.format(threading.current_thread().name)) th_1 = threading.Thread(target=run_thread, args=(1, 2)) th_2 = threading.Thread(target=run_thread, args=(4, 9)) local_add = threading.local() lock = threading.Lock() th_1.start() th_2.start() result_1 = th_1.join() result_2 = th_2.join() print('Thread {0} end'.format(threading.current_thread().name))
from constants import graph1, graph2 def dfs_recursive(graph, start_node, visited=[]): """ * Add to the visited array * Call the dfs method recursively, with the next non-visited node by looping through all the nodes connected to it. """ visited.append(start_node) for next_node in graph[start_node]: if next_node not in visited: dfs_recursive(graph, next_node, visited) return visited def dfs_stack(graph, start_node): visited, stack = [], [start_node] while stack: vertex = stack.pop() if vertex not in visited: visited.append(vertex) stack.extend(graph[vertex]) return visited #print dfs_recursive(graph2, '0') #print dfs_stack(graph2, '0') print dfs_recursive(graph1, 'C') print dfs_stack(graph1, 'C')
class c1: def add(self,a,b): """ a,b: int: a+b a,b: str: concate a: int, b:str: None """ try: return a+b except: return None def mul(a,b): return a*b
from random import random import tkinter as tk WIDTH, HEIGHT = 480, 480 x1, y1 = WIDTH // 2, HEIGHT // 2 def create_rectangle(): rectangle = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill='green') return rectangle def move_rectangle(): rnd = random() x = 0 y = 0 pos = canvas.coords(rectangle) if rnd > 0 and rnd < 0.25 and pos[0] <= 440: x = 30 elif rnd > 0.25 and rnd < 0.5 and pos[0] >= 30: x = -30 elif rnd > 0.5 and rnd < 0.75 and pos[1] <= 440: y = 30 elif rnd > 0.75 and rnd < 1 and pos[1] >= 30: y = -30 canvas.move(rectangle, x, y) root.after(5, move_rectangle) root = tk.Tk() tk.Button(root, text='start', command=move_rectangle).pack() canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="cyan") canvas.pack() rectangle = create_rectangle() root.mainloop()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #On Python3,the default input type is str s1 = int(input('输入去年的成绩:')) s2 = int(input('输入今年的成绩:')) delta = (s2 - s1)/s1*100 #print(delta) if delta > 0.0: print('小明今年比去年提升了%.1f%%'%delta) elif delta < 0.0: print('小明今年比去年退步了%.1f%%'%delta) else: print('小明的成绩在原地踏步')
import itertools import itertools as it def erat2a(): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: # old code here: # x = p + q # while x in D or not (x&1): # x += p # changed into: x = q + 2*p while x in D: x += 2*p D[x] = p def erat3(): D = { 9: 3, 25: 5 } yield 2 yield 3 yield 5 MASK= 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, MODULOS= frozenset( (1, 7, 11, 13, 17, 19, 23, 29) ) for q in it.compress( it.islice(it.count(7), 0, None, 2), it.cycle(MASK)): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: x = q + 2*p while x in D or (x%30) not in MODULOS: x += 2*p D[x] = p def primes_less_than(N): # make `primes' a list of known primes < N primes = [x for x in (2, 3, 5, 7, 11, 13) if x < N] if N <= 17: return primes # candidate primes are all odd numbers less than N and over 15, # not divisible by the first few known primes, in descending order candidates = [x for x in xrange((N-2)|1, 15, -2) if x % 3 and x % 5 and x % 7 and x % 11 and x % 13] # make `top' the biggest number that we must check for compositeness top = int(N ** 0.5) while (top+1)*(top+1) <= N: top += 1 # main loop, weeding out non-primes among the remaining candidates while True: # get the smallest candidate: it must be a prime p = candidates.pop( ) primes.append(p) if p > top: break # remove all candidates which are divisible by the newfound prime candidates = filter(p._ , candidates) # all remaining candidates are prime, add them (in ascending order) candidates.reverse( ) primes.extend(candidates) return primes def eratosthenes( ): '''Yields the sequence of prime numbers via the Sieve of Eratosthenes.''' D = { } # map each composite integer to its first-found prime factor for q in itertools.count(2): # q gets 2, 3, 4, 5, ... ad infinitum p = D.pop(q, None) if p is None: # q not a key in D, so q is prime, therefore, yield it yield q # mark q squared as not-prime (with q as first-found prime factor) D[q*q] = q else: # let x <- smallest (N*p)+q which wasn't yet known to be composite # we just learned x is composite, with p first-found prime factor, # since p is the first-found prime factor of q -- find and mark it x = p + q while x in D: x += p D[x] = p
from __future__ import print_function import os def dragon_curve(data): rev_data = ''.join('0' if x == '1' else '1' for x in reversed(data)) return data + '0' + rev_data def calc_checksum(data): checksum = [] for i in range(0, len(data), 2): x, y = data[i], data[i+1] if x == y: checksum.append('1') else: checksum.append('0') return ''.join(checksum) def solve(data, length): fill_data = data # Generate data while len(fill_data) < length: fill_data = dragon_curve(fill_data) # Truncate truncated = fill_data[:length] # Generate checksum checksum = calc_checksum(truncated) while len(checksum) % 2 == 0: checksum = calc_checksum(checksum) return checksum if __name__ == '__main__': data = '10111011111001111' print('The correct checksum for size 272 disk is', solve(data, 272)) print('The correct checksum for size 35651584 disk is', solve(data, 35651584))
#!/usr/bin/python # -*- coding: utf-8 -*- from random import random, randint, uniform from cellVariables import * class Cell(): numCells = 1 ArrayCells = [] deadFactor = 0.1 # kind = tipo de celula # x = posicion X # y = posicion Y # size = area (radio) # veloProg = velocidad de propagacion # colour = color de celula # thickness = colorea (0) o solo dibuja linea (1) # speed = velocidad de movimiento # angle = angulo al iniciar movimiento # idCell = id de celula # numChild = numero de hijos # state = determina si ya se dividio # = 1; listo para dividir # = 0; recien nacido # = -1; ya se dividio y empieza a morir # eat = si puede comer o no def __init__(self, name,colour,(x, y),velProg,angle=uniform(0.0,2*math.pi),size=5,speed=0.1,caneat=False): self.kind = name self.x = x self.y = y self.size = size self.vel = velProg self.colour = colour self.thickness = 0 self.speed = speed self.angle = angle self.idcell = Cell.numCells self.numChild = 2 self.state = 0 self.caneat = caneat Cell.numCells+=1 Cell.ArrayCells.append(self) # ciclo de vida de la celula def lifeCycleCell(self): self.move() nearFood = self.findFoodNearly() self.followFood(nearFood) # si esta en el area, come # si no consigue comida en un tiempo, muere # si llega a llenarse, come # si llega a clonarse lo suficiente muere if(self.state==0 and self.caneat): if self.kind == "Benigna": self.colour = yellow elif self.kind == "Cancer": self.colour = purple self.eatCell() elif(self.state==0 and not self.caneat): if self.kind == "Benigna": self.colour = darkYellow elif self.kind == "Cancer": self.colour = darkPurple self.deadCell() elif(self.state==1): if self.kind == "Benigna": self.colour = yellow elif self.kind == "Cancer": self.colour = purple self.cellClone() elif(self.state==-1): if self.kind == "Benigna": self.colour = darkYellow elif self.kind == "Cancer": self.colour = darkPurple self.deadCell() # clonar celula def cellClone(self): if(self.numChild==2): self.numChild = self.numChild-1 self.state = 0 elif(self.numChild==1): self.numChild = self.numChild-1 self.state = -1 copia = Cell(self.kind,self.colour,(self.x,self.y),self.vel) # cantidad de comida ingerida # comen segun velocidad de propagacion def eatCell(self): eat = self.vel*round(random(),2) self.size += eat if(self.size>=10): self.size=5 self.state=1 # van muriendo lentamente ... :( def deadCell(self): dead = Cell.deadFactor*round(random(),2) self.size -= dead if(self.size<=0): print "celula tipo: ", self.kind," numero: ",self.idcell," muerta !!" Cell.ArrayCells.remove(getIndexCell(self.idcell)) def display(self): pygame.draw.circle(screen, self.colour, (int(self.x), int(self.y)), int(self.size), self.thickness) def move(self): (self.angle, self.speed) = addVectors((self.angle, self.speed), gravity) self.x += math.sin(self.angle) * self.speed self.y -= math.cos(self.angle) * self.speed self.speed *= drag # define las fronteras def bounce(self): if self.x > width - self.size: self.x = 2*(width - self.size) - self.x self.angle = - self.angle self.speed *= elasticidad elif self.x < self.size: self.x = 2*self.size - self.x self.angle = - self.angle self.speed *= elasticidad if self.y > height - self.size: self.y = 2*(height - self.size) - self.y self.angle = math.pi - self.angle self.speed *= elasticidad elif self.y < self.size: self.y = 2*self.size - self.y self.angle = math.pi - self.angle self.speed *= elasticidad # sigue comida def followFood(self,food): if self.x > food.x: self.x = self.x - 1 elif self.x < food.x: self.x = self.x + 1 if self.y > food.y: self.y = self.y -1 elif self.y < food.y: self.y = self.y + 1 if self.findFood(food): self.caneat = True else: self.caneat = False # busca comida def findFood(self,food): dx = self.x - food.x dy = self.y - food.y dist = math.hypot(dx, dy) if dist < self.size + food.size: return True else: return False # encuentra la celula con menor distancia def findFoodNearly(self): foods = getAllFoods() miniD = math.hypot(foods[0].x-self.x, foods[0].y-self.y) for p in foods: d = math.hypot(p.x-self.x, p.y-self.y) if d <= miniD: miniD = d idfoo = p.idfood return getIndexFood(idfoo) # obtiene la celula que esta en el index num en el ArrayCells def getIndexCell(num): cells = getAllCells() for cell in cells: if(cell.idcell==num): return cell return None # obtiene el numero de celulas def getNumCells(): return len(Cell.ArrayCells) # obtiene el array de celulas def getAllCells(): return Cell.ArrayCells # obtiene el numero de celulas segun su tipo def getTypeCells(name): cells = getAllCells() count = 0 for cell in cells: if(cell.kind == name): count+=1 return count # anade los vectores direcciones luego de los choques def addVectors((angle1, length1), (angle2, length2)): x = math.sin(angle1) * length1 + math.sin(angle2) * length2 y = math.cos(angle1) * length1 + math.cos(angle2) * length2 angle = 0.5 * math.pi - math.atan2(y, x) length = math.hypot(x, y) return (angle, length) # encuentra la celula con menor distancia def findCell(cells, x, y): for p in cells: if math.hypot(p.x-x, p.y-y) <= p.size: return p return None # choque entre las celulas def collide(p1, p2): dx = p1.x - p2.x dy = p1.y - p2.y dist = math.hypot(dx, dy) if dist < p1.size + p2.size: tangent = math.atan2(dy, dx) angle = 0.5 * math.pi + tangent angle1 = 2*tangent - p1.angle angle2 = 2*tangent - p2.angle speed1 = p2.speed*elasticidad speed2 = p1.speed*elasticidad (p1.angle, p1.speed) = (angle1, speed1) (p2.angle, p2.speed) = (angle2, speed2) p1.x += math.sin(angle) p1.y -= math.cos(angle) p2.x -= math.sin(angle) p2.y += math.cos(angle) # imprime las celulas y sus caracteristicas def printCells(cells): for cell in cells: print "\n#########################################" print "#\tCelula N.",cell.idcell,": ", cell.kind,"\t#" print "#########################################" print "#\tX: ", cell.x,"\t\t\t\t#" print "#\tY: ", cell.y,"\t\t\t\t#" print "#\tarea: ", cell.area,"\t\t\t#" print "#\testado de vida", cell.state,"\t\t#" print "#########################################\n\n" # crecen hasta ser una generacion ( 2^x ) def initGenerations(numcell): cellTotal = getAllCells() while(len(cellTotal)<(2**numcell)): for cell in cellTotal: print "\n#########################################" print "#\tCelula N.",cell.idcell,": ", cell.kind,"\t#" print "#########################################" print "#\tX: ", cell.x,"\t\t\t\t#" print "#\tY: ", cell.y,"\t\t\t\t#" print "#\tnumero de crias: ",cell.numChild,"\t\t#" print "#\tarea: ",cell.area,"\t\t\t#" print "#\testado: ",cell.state,"\t\t\t#" print "#########################################\n\n" cell.lifeCycleCell() # ########################################################### # Funciones extras ( uso por ahora ) def divCells(cells): cellsaux = [] for cell in cells: cellaux = cell._cellClone() cellsaux.append(cellaux) return cellsaux def reprodCells(cells): cellsaux = divCells(cells) for cell in cellsaux: cells.append(cell) return cells def genCells(cells,num): for i in range(0,num): cells=reprodCells(cells) return cells
#!/usr/bin/env python from math import * from auxFuncRoots import * # ------------------------------------------------------------ # 1.8 METODO DE STEFFENSEN def steffensen(f,a,printText = 1,tol=1e-7,NMAX=100): if (f(a)-a)==0: return a correct=True for i in range(NMAX): p1 = f(a) p2 = f(p1) if printText: print "a=%s\tp1=%s\tp2=%s\tf(a)=%s"%(a,p1,p2,f(a)) if (p2-2*p1+a)==0: return p2 p = a - (p1-a)*(p1-a)/(p2-2*p1+a) if abs(p-a)<tol: return p a=p try :k = d1f(f,a) except FloatingPointError: correct = False if not correct or k >= 1: print("No existe la derivada o DIVERGE! ") return None print("No fueron suficientes iteraciones") return None # ------------------------------------------------------------
#!/usr/bin/env python from math import * from auxFuncRoots import * # ------------------------------------------------------------ # 1.11 METODO DE HOUSEHOLDER ( 3er ORDEN ) def householderRoots(f,d1f,d2f,d3f,x0,printText = 1,tol=1e-9, NMAX=100): if f(x0)==0: return x0 n=1 while n<=NMAX: df0 = f(x0) df1 = d1f(f,x0) df2 = d2f(f,x0) df3 = d3f(f,x0) dx = (6*df0*df1*df1 - 3*df0*df0*df2)/( 6*df1*df1*df1 - 6*df0*df1*df2 + df0*df0*df3 ) x1 = x0 - dx if printText: print "x0=%s\tx1=%s\tf(x1)=%s"%(x0,x1,f(x1)) if abs(x1 - x0) < tol: return x1 else: x0 = x1 print("No fueron suficientes iteraciones") return None # ------------------------------------------------------------
#!/usr/bin/env python from math import * from auxFuncRoots import * # ------------------------------------------------------------ # 1.4 METODO DE NEWTON def newton(f, d1f, x0,printText=1, tol=1e-9, NMAX=100): if f(x0)==0: return x0 n=1 while n<=NMAX: try: dx = f(x0)/d1f(f,x0) except ZeroDivisionError: return x0 x1 = x0 - dx if printText: print "x0=%s\tx1=%s\tf(x1)=%s"%(x0,x1,f(x1)) if abs(x1 - x0) < tol: return x1 else: x0 = x1 print("No fueron suficientes iteraciones") return None # ------------------------------------------------------------
#!/usr/bin/env python from math import * from auxFuncRoots import * # ------------------------------------------------------------ # 1.1 METODO BISECCION def bisection(f, a, b, switch = 0,tol=1e-9): if a>=b: print("Error, a > b") return None if f(a)==0: return a elif f(b) ==0: return b elif f(a)*f(b) > 0: print("f(a) y f(b) son del mismo signo") return None n=int(ceil(log(abs(b-a)/tol)/log(2.0))) for i in range(n): c = (a+b)*0.5 if switch==0: print "a=%s\tb=%s\tc=%s\tf(c)=%s"%(a,b,c,f(c)) if (switch==1) and (abs(f(c)) > abs(f(a))) and (abs(f(c)) > abs(f(b))): return None if f(c)==0 or (b-a)/2.0 < tol: return c elif f(c)*f(a) < 0: b=c else: a=c print("No fueorn suficiente iteraciones") return None # ------------------------------------------------------------
audi=float(0) visual=float(0) kine=float(0) idk=float(0) print("Bienvenido al programa de la encuestas de este modulo escolar, donde el estudante podra concentrar sus puntos debiles de estudios para que al final el profesor guie al alumno con un nuevo sistema de aprendizaje") print("En caso de no poner los incisos indicados, se los tomara como NO RESPONDIDOS") print("\nCOMENZAMOS\n") print("Pregunta 1: Cual de las siguientes actividades disfrutas mas?") print("a) Escuchar musica") print("b) Ver peliculas") print("c) Bailar con buena musica") r=input("Ingresa un inciso: ") if (r == "a"): audi = audi + 1 elif (r == "b"): visual = visual + 1 elif (r == "c"): kine = kine + 1 else: idk = idk + 1 print("\nPregunta 2: Que programa de television prefieres?") print("a) Reportajes de descubrimientos y lugares") print("b) Comico y de entretenimiento") print("c) Noticias del mundo") r=input("Ingresa un inciso: ") if (r == "a"): visual = visual + 1 elif (r == "b"): kine = kine + 1 elif (r == "c"): audi = audi + 1 else: idk = idk + 1 print("\nPregunta 3: Cuando conversas con otra persona, tu") print("a) La escuchas atentamente") print("b) La observas") print("c) Tiendes a tocarla") r=input("Ingresa un inciso: ") if (r == "a"): audi = audi + 1 elif (r == "b"): visual = visual + 1 elif (r == "c"): kine = kine + 1 else: idk = idk + 1 print("\nPregunta 4: Si pudieras adquirir uno de los siguientes articulos, cual elegirias?") print("a) Un jacuzzi") print("b) Un estereo") print("c) Un televisor") r=input("Ingresa un inciso: ") if (r == "a"): kine = kine + 1 elif (r == "b"): audi = audi + 1 elif (r == "c"): visual = visual + 1 else: idk = idk + 1 print("\nPregunta 5: Que prefieres hacer un sabado en la tarde?") print("a) Quedarte en casa") print("b) Ir a un concierto") print("c) Ir al cine") r=input("Ingresa un inciso: ") if (r == "a"): kine = kine + 1 elif (r == "b"): audi = audi + 1 elif (r == "c"): visual = visual + 1 else: idk = idk + 1 print("\nPregunta 6: Que tipo de examenes te facilitan mas?") print("a) Examen oral") print("b) Examen escrito") print("c) Examen de opcion multiple") r=input("Ingresa un inciso: ") if (r == "a"): audi = audi + 1 elif (r == "b"): visual = visual + 1 elif (r == "c"): kine = kine + 1 else: idk = idk + 1 print("\nPregunta 7: Como te orientas mas facilmente?") print("a) Mediante el uso de un mapa") print("b) Pidiendo indicaciones") print("c) A traves de la intuicion") r=input("Ingresa un inciso: ") if (r == "a"): visual = visual + 1 elif (r == "b"): audi = audi + 1 elif (r == "c"): kine = kine + 1 else: idk = idk + 1 print("\nPregunta 8: En que prefieres ocupar tu tiempo en un lugar de descanso?") print("a) Pensar") print("b) Caminar por los alrededores") print("c) Descansar") r=input("Ingresa un inciso: ") if (r == "a"): audi = audi + 1 elif (r == "b"): visual = visual + 1 elif (r == "c"): kinr = kine + 1 else: idk = idk + 1 print("\nPregunta 9: Que te halaga mas?") print("a) Que te digan que tienes buen aspecto") print("b) Que te digan que tienes un trato muy agradable") print("c) Que te digan que tienes una conversacion interesante") r=input("Ingresa un inciso: ") if (r == "a"): visual = visual + 1 elif (r == "b"): kine = kine + 1 elif (r == "c"): audi = audi + 1 else: idk = idk + 1 print("\nPregunta 10: Cual de estos ambientes te atrae mas?") print("a) clima agradable") print("b)olas del mar") print("c) hermosa vista al oceano") r=input("Ingresa un inciso: ") if (r == "a"): kine = kine + 1 elif (r == "b"): audi = audi + 1 elif (r == "c"): visual = visual + 1 else: idk = idk + 1 if (idk == 0): from matplotlib import pyplot lenguajes = ("Audio", "Visual", "Kinestesico") slices = (audi, visual, kine) colores = ("Red", "Blue", "Green") pyplot.pie(slices, colors=colores, labels=lenguajes, autopct='%1.1f%%') pyplot.axis("Equal") pyplot.title("Resultados de la evaluacion") # pyplot.legend(labels=lenguajes) pyplot.show() else: from matplotlib import pyplot lenguajes = ("Audio", "Visual", "Kinestesico", "INVALIDO") slices = (audi, visual, kine, idk) colores = ("Red", "Blue", "Green", "Gray") pyplot.pie(slices, colors=colores, labels=lenguajes, autopct='%1.1f%%') pyplot.axis("Equal") pyplot.title("Resultados de la evaluacion") # pyplot.legend(labels=lenguajes) pyplot.show() print("\t\t\t Sumas y Restas \n") print("\t\t Kinesico \n") if (kine == 1): print("https://www.youtube.com/watch?v=35arstsomnc \n") elif (kine == 2): print("https://www.youtube.com/watch?v=12IQZnWsL8E \n") print("https://www.youtube.com/watch?v=35arstsomnc \n") elif (kine == 3): print("https://www.youtube.com/watch?v=boNv5VhAr7E \n") print("https://www.youtube.com/watch?v=12IQZnWsL8E \n") print("https://www.youtube.com/watch?v=d1U8Cke2oAE \n") elif (kine == 4): print("https://www.youtube.com/watch?v=35arstsomnc \n") print("https://www.youtube.com/watch?v=i8Wbwf39Ti0 \n") print("https://www.youtube.com/watch?v=_tqjU_P_HlM \n") print("https://www.youtube.com/watch?v=86tboGybGcI \n") elif (kine == 5): print("https://www.youtube.com/watch?v=boNv5VhAr7E \n") print("https://www.youtube.com/watch?v=d1U8Cke2oAE \n") print("https://www.youtube.com/watch?v=12IQZnWsL8E \n") print("https://www.youtube.com/watch?v=i8Wbwf39Ti0 \n") print("https://www.youtube.com/watch?v=_tqjU_P_HlM \n") elif (kine == 6): print("https://www.youtube.com/watch?v=35arstsomnc \n") print("https://www.youtube.com/watch?v=boNv5VhAr7E \n") print("https://www.youtube.com/watch?v=d1U8Cke2oAE \n") print("https://www.youtube.com/watch?v=12IQZnWsL8E \n") print("https://www.youtube.com/watch?v=i8Wbwf39Ti0 \n") print("https://www.youtube.com/watch?v=_tqjU_P_HlM \n") elif (kine == 7): print("https://www.youtube.com/watch?v=12IQZnWsL8E \n") print("https://www.youtube.com/watch?v=35arstsomnc \n") print("https://www.youtube.com/watch?v=boNv5VhAr7E \n") print("https://www.youtube.com/watch?v=d1U8Cke2oAE \n") print("https://www.youtube.com/watch?v=i8Wbwf39Ti0 \n") print("https://www.youtube.com/watch?v=JMTI_3ay-Og \n") print("https://www.youtube.com/watch?v=JMTI_3ay-O7 \n") elif (kine == 8): print("https://www.youtube.com/watch?v=AMNACNvN8vc \n") print("https://www.youtube.com/watch?v=JMTI_3ay-Og \n") print("https://www.youtube.com/watch?v=f4f37hjiWc4 \n") print("https://www.youtube.com/watch?v=86tboGybGcI \n") print("https://www.youtube.com/watch?v=_tqjU_P_HlM \n") print("https://www.youtube.com/watch?v=i8Wbwf39Ti0 \n") print("https://www.youtube.com/watch?v=d1U8Cke2oAE \n") print("https://www.youtube.com/watch?v=12IQZnWsL8E \n") elif (kine == 9): print("https://www.youtube.com/watch?v=boNv5VhAr7E \n") print("https://www.youtube.com/watch?v=d1U8Cke2oAE \n") print("https://www.youtube.com/watch?v=i8Wbwf39Ti0 \n") print("https://www.youtube.com/watch?v=_tqjU_P_HlM \n") print("https://www.youtube.com/watch?v=86tboGybGcI \n") print("https://www.youtube.com/watch?v=f4f37hjiWc4 \n") print("https://www.youtube.com/watch?v=JMTI_3ay-Og \n") print("https://www.youtube.com/watch?v=AMNACNvN8vc \n") print("https://www.youtube.com/watch?v=12IQZnWsL8E \n") elif (kine == 10): print("https://www.youtube.com/watch?v=35arstsomnc \n") print("https://www.youtube.com/watch?v=12IQZnWsL8E \n") print("https://www.youtube.com/watch?v=boNv5VhAr7E \n") print("https://www.youtube.com/watch?v=d1U8Cke2oAE \n") print("https://www.youtube.com/watch?v=i8Wbwf39Ti0 \n") print("https://www.youtube.com/watch?v=_tqjU_P_HlM \n") print("https://www.youtube.com/watch?v=86tboGybGcI \n") print("https://www.youtube.com/watch?v=f4f37hjiWc4 \n") print("https://www.youtube.com/watch?v=JMTI_3ay-Og \n") print("https://www.youtube.com/watch?v=AMNACNvN8vc \n") else: print("No es kinesico \n") print("Visual") if (visual == 1): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") elif (visual == 2): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=2Iy92z6WOqI \n") elif (visual == 3): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=2Iy92z6WOqI \n") print("https://www.youtube.com/watch?v=1ktyVZthSX4 \n") elif (visual == 4): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=2Iy92z6WOqI \n") print("https://www.youtube.com/watch?v=1ktyVZthSX4 \n") print("https://www.youtube.com/watch?v=CSlkZpoy5s8 \n") elif (visual == 5): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=2Iy92z6WOqI \n") print("https://www.youtube.com/watch?v=1ktyVZthSX4 \n") print("https://www.youtube.com/watch?v=CSlkZpoy5s8 \n") print("https://www.youtube.com/watch?v=aGJ00fU5Cik \n") elif (visual == 6): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=2Iy92z6WOqI \n") print("https://www.youtube.com/watch?v=1ktyVZthSX4 \n") print("https://www.youtube.com/watch?v=CSlkZpoy5s8 \n") print("https://www.youtube.com/watch?v=aGJ00fU5Cik \n") print("https://www.youtube.com/watch?v=szmjdS1Whz0 \n") elif (kine == 7): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=CSlkZpoy5s8 \n") print("https://www.youtube.com/watch?v=1ktyVZthSX4 \n") print("https://www.youtube.com/watch?v=CSlkZpoy5s8 \n") print("https://www.youtube.com/watch?v=aGJ00fU5Cik \n") print("https://www.youtube.com/watch?v=szmjdS1Whz0 \n") print("https://www.youtube.com/watch?v=uLulA91jt_A \n") elif (visual == 8): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=2Iy92z6WOqI \n") print("https://www.youtube.com/watch?v=1ktyVZthSX4 \n") print("https://www.youtube.com/watch?v=CSlkZpoy5s8 \n") print("https://www.youtube.com/watch?v=aGJ00fU5Cik \n") print("https://www.youtube.com/watch?v=szmjdS1Whz0 \n") print("https://www.youtube.com/watch?v=uLulA91jt_A \n") print("https://www.youtube.com/watch?v=Cv3T6QTnofs \n") elif (visual == 9): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=2Iy92z6WOqI \n") print("https://www.youtube.com/watch?v=1ktyVZthSX4 \n") print("https://www.youtube.com/watch?v=CSlkZpoy5s8 \n") print("https://www.youtube.com/watch?v=aGJ00fU5Cik \n") print("https://www.youtube.com/watch?v=szmjdS1Whz0 \n") print("https://www.youtube.com/watch?v=uLulA91jt_A \n") print("https://www.youtube.com/watch?v=Cv3T6QTnofs \n") print("https://www.youtube.com/watch?v=LVHo5xvsvO0 \n") elif (visual == 10): print("https://www.youtube.com/watch?v=5-8xAn9RxyU \n") print("https://www.youtube.com/watch?v=2Iy92z6WOqI \n") print("https://www.youtube.com/watch?v=1ktyVZthSX4 \n") print("https://www.youtube.com/watch?v=CSlkZpoy5s8 \n") print("https://www.youtube.com/watch?v=aGJ00fU5Cik \n") print("https://www.youtube.com/watch?v=szmjdS1Whz0 \n") print("https://www.youtube.com/watch?v=uLulA91jt_A \n") print("https://www.youtube.com/watch?v=Cv3T6QTnofs \n") print("https://www.youtube.com/watch?v=LVHo5xvsvO0 \n") print("https://www.youtube.com/watch?v=BWK6NLFQYzA \n") else: print("No es visual") print("Auditivo") if (audi == 1): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") elif (audi == 2): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") elif (audi == 3): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") print("https://www.youtube.com/watch?v=p_-TitDXrmY \n") elif (audi == 4): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") print("https://www.youtube.com/watch?v=p_-TitDXrmY \n") print("https://www.youtube.com/watch?v=rXF5yQ7HYVQ \n") elif (audi == 5): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") print("https://www.youtube.com/watch?v=p_-TitDXrmY \n") print("https://www.youtube.com/watch?v=rXF5yQ7HYVQ \n") print("https://www.youtube.com/watch?v=R0XQ8AbtZbo \n") elif (audi == 6): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") print("https://www.youtube.com/watch?v=p_-TitDXrmY \n") print("https://www.youtube.com/watch?v=rXF5yQ7HYVQ \n") print("https://www.youtube.com/watch?v=R0XQ8AbtZbo \n") print("https://www.youtube.com/watch?v=zB62w5cRpUQ \n") elif (audi == 7): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") print("https://www.youtube.com/watch?v=p_-TitDXrmY \n") print("https://www.youtube.com/watch?v=rXF5yQ7HYVQ \n") print("https://www.youtube.com/watch?v=R0XQ8AbtZbo \n") print("https://www.youtube.com/watch?v=zB62w5cRpUQ \n") print("https://www.youtube.com/watch?v=_ciH9pOnJYs \n") elif (audi == 8): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") print("https://www.youtube.com/watch?v=p_-TitDXrmY \n") print("https://www.youtube.com/watch?v=rXF5yQ7HYVQ \n") print("https://www.youtube.com/watch?v=R0XQ8AbtZbo \n") print("https://www.youtube.com/watch?v=zB62w5cRpUQ \n") print("https://www.youtube.com/watch?v=_ciH9pOnJYs \n") print("https://www.youtube.com/watch?v=1p4TecYqtwI \n") elif (audi == 9): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") print("https://www.youtube.com/watch?v=p_-TitDXrmY \n") print("https://www.youtube.com/watch?v=rXF5yQ7HYVQ \n") print("https://www.youtube.com/watch?v=R0XQ8AbtZbo \n") print("https://www.youtube.com/watch?v=zB62w5cRpUQ \n") print("https://www.youtube.com/watch?v=_ciH9pOnJYs \n") print("https://www.youtube.com/watch?v=1p4TecYqtwI \n") print("https://www.youtube.com/watch?v=OetrABNO3T4 \n") elif (audi == 10): print("https://www.youtube.com/watch?v=OBD9io9Z02A \n") print("https://www.youtube.com/watch?v=3S4lsk6gqeY \n") print("https://www.youtube.com/watch?v=p_-TitDXrmY \n") print("https://www.youtube.com/watch?v=rXF5yQ7HYVQ \n") print("https://www.youtube.com/watch?v=R0XQ8AbtZbo \n") print("https://www.youtube.com/watch?v=zB62w5cRpUQ \n") print("https://www.youtube.com/watch?v=_ciH9pOnJYs \n") print("https://www.youtube.com/watch?v=1p4TecYqtwI \n") print("https://www.youtube.com/watch?v=OetrABNO3T4 \n") print("https://www.youtube.com/watch?v=YiRst8TZgEE \n") else: print("No es auditivo") print("\t\t Evaluacion \n") print("\t\t https://www.matesfacil.com/interactivos/primaria/sumas-restas-primaria-ejercicios-interactivos-autocorreccion-online-test-examen-llevada-huecos-TIC.html")
# Cracking The Coding Interview # Recursion and Dynamic Programming # 8.7: Permutations without Dups ##### First Solution ##### def perm1(listo): if len(listo) == 0: # base case, empty list return [] elif len(listo) == 1: # another simple case, 1 item to permute return listo else: tempo = [] # now we need to disect our string, take the first item for i in range(len(listo)): first = listo[i] # first item in string/list others = listo[:i] + listo[i+1:] # everything before and after i for item in perm1(others): # we need to break the others down tempo.append(first+item) return tempo ##### Second Solution ##### # same as above def perm2(listo): n = len(listo) result = [] if n == 0: result.append(listo) return result for i in range(n): before = listo[:i] after = listo[i+1:] partials = perm2(before+after) for p in partials: result.append(listo[i]+p) return result ##### Third Solution ##### # I troubleshooted this one for sometime, # removing the append(" ") breaks it. /shruggie def perm3(listo): permutations = [] if len(listo) == 0: permutations.append(" ") return permutations first = listo[0] #print("DEBUG: first =",first) rest = listo[1:] #print("DEBUG: rest =",rest) #print("DEBUG: Entering recursion") words = perm3(rest) #print("DEBUG: words =",words) for word in words: for index in range(len(word)): s = insertCharAt(word,first,index) permutations.append(s) #print("DEBUG: Exiting recursion") #print("DEBUG: Permutations =",permutations) return permutations def insertCharAt(word,char,pos): start = word[:pos] end = word[pos:] return start + char + end ##### Testing ##### listo = "abc" print(perm1(listo)) print(perm2(listo)) print() print(perm3(listo)) ##### Notes ##### # # listo = "abcde" # listo[:2] == ab (excluding the second item ie, 'c') # listo[2:] == cde (inclusive of our 2nd element 'c') # instead use listo[i+1:] (for an exclusion of our ith item)
from Tkinter import * class interfaz: def __init__(self,contenedor): self.e1 = Label(contenedor, text="Etiqueta 1",fg = "black", bg = "white") self.e1.place(x=10,y=30,width=120,height=25) ventana = Tk() miInterfaz= interfaz(ventana) ventana.mainloop()
#DAY 16: Exceptions - String to Integer #Read string S, if it has an integer value, print it, if else print 'Bad String'. Must use a error catching, cannot use if/else or loops. I did this in python because it is much easier than JavaScript import sys S = input().strip() try: N = int(S) print(N) except: print('Bad String')
import socket import subprocess from util import * # logger for FTP client program clientLogger = setup_logger() class FTPClient(): """ Implementation for FTP client. The command accepted are: get, put, ls and quit. FTP client has two sockets: control socket is used for control channel, data socket is used for data channel. Commands are sent to FTP server by control channel, data are sent to and received from FTP server by data channel. """ def __init__(self, serverName, serverPort): self.__serverName = serverName self.__serverPort = int(serverPort) self.__dataChannelPort = None self.__dataChannelSocket = None self.__controlChannelSocket = None def __sendControlData(self, commandStr, filenameStr): """ Send control request with data to FTP server. The control request format is: command(5 bytes) + clientDataChannelPort(5 bytes) + filenameLength(5 bytes) + filename(optional) :param commandStr: <string> Command send to FTP server. :param filenameStr: <string> The filename to upload or download from FTP server for ls command, the filename is an empty string. :returns <boolean>: return True if successfully send control data to FTP server, otherwise return False """ clientLogger.debug("Sending control data to FTP server...") # Prepend spaces to the command string # until the size is 5 bytes commandLen = len(commandStr) while commandLen < 5: commandStr = " " + commandStr commandLen = len(commandStr) clientLogger.debug("Command will send to server is \"%s\"", commandStr) # Prepend 0's to the data channel port # until the size is 5 bytes dataChannelPortStr = str(self.__dataChannelPort) clientLogger.debug("FTP client data channel port is: %s", dataChannelPortStr) while len(dataChannelPortStr) < 5: dataChannelPortStr = "0" + dataChannelPortStr # Prepend 0's to the filename size string # until the size is 5 bytes filenameLen = len(filenameStr) filenameLenStr = str(filenameLen) clientLogger.debug("Filename length is: %s", filenameLenStr) while len(filenameLenStr) < 5: filenameLenStr = "0" + filenameLenStr #assemble control data send to FTP server controlDataStr = "" if commandStr.strip() == "ls": controlDataStr = commandStr + dataChannelPortStr elif commandStr.strip() == "get" or commandStr.strip() == "put": controlDataStr = commandStr + dataChannelPortStr + filenameLenStr + filenameStr #send control data to FTP server dataToSend = controlDataStr.encode() sentDataLen = 0 clientLogger.debug("Total size of control data will send to FTP server is: %d", len(dataToSend)) while sentDataLen < len(dataToSend): clientLogger.debug("Sending control data to FTP server...") try: sentDataLen += self.__controlChannelSocket.send(dataToSend[sentDataLen:]) except Exception as e: clientLogger.error(e) return False clientLogger.debug("Size of data sent to FTP server: %d", sentDataLen) return True def __sendFileData(self, dataStr, serverSocket): """ Send file data to FTP server in a upload request. The file request format is: filesize(10 bytes) + filedata :param dataStr: <string> The file data send to FTP server. :returns <tuple>: return a tuple of (True, dataSizeSent) if successfully send file data to FTP server, otherwise return (False, dataSizeSend) """ clientLogger.debug("Sending file data to FTP server...") # Prepend 0's to the size string # until the size is 10 bytes dataLen = len(dataStr) dataLenStr = str(dataLen) clientLogger.debug("Size of data to send to FTP server is: %s", dataLenStr) while len(dataLenStr) < 10: dataLenStr = "0" + dataLenStr #assemble data to send to FTP server dataStr = dataLenStr + dataStr #send data to FTP server dataToSend = dataStr.encode() sentDataLen = 0 clientLogger.debug("Size of total data to send to FTP server: %d", len(dataToSend)) while sentDataLen < len(dataToSend): try: sentDataLen += serverSocket.send(dataToSend[sentDataLen:]) except Exception as e: clientLogger.error(e) return False, sentDataLen clientLogger.debug("Size of data sent to FTP server: %d", sentDataLen) return True, len(dataToSend) def __receiveControlData(self): """ Receive control response from FTP server. The control response format is: statusCode(3 bytes) + messageSize(5 bytes) + message :returns <tuple>: a tuple of response status code and server message. """ serverMsg = "" # The buffer containing the request status code from FTP server statusCodeStr = self.__recvAll(3, self.__controlChannelSocket) # Get the status statusCode = int(statusCodeStr) clientLogger.debug("The FTP server response status code is %d", statusCode) # The buffer containing the server response message size msgSizeStr = self.__recvAll(5, self.__controlChannelSocket) # Get the server response message size msgSize = int(msgSizeStr.strip()) clientLogger.debug("The FTP server response message size is %d", msgSize) # Get the server response message serverMsg = self.__recvAll(msgSize, self.__controlChannelSocket) return statusCode, serverMsg def __receiveFileData(self, serverSocket): """ Receive file data from FTP server in a download request. :returns <tuple>: A tuple contains the downloaded file data and download data size. """ receivedData = "" # The buffer containing the file size dataSize = self.__recvAll(10, serverSocket) # Get the file size dataSize = int(dataSize.strip()) clientLogger.debug("The file size is %d", dataSize) # Get the file data receivedData = self.__recvAll(dataSize, serverSocket) clientLogger.debug("All file data received.") return receivedData, dataSize def __recvAll(self, receiveByteLen, socket): """ Receive data from the given socket. :returns <string>: the decoded received data. """ # The buffer recvBuff = "" # The temporary buffer tmpBuff = "" # Keep receiving till all is received while len(recvBuff) < receiveByteLen: # Attempt to receive bytes tmpBuff = socket.recv(receiveByteLen).decode() # The other side has closed the socket if not tmpBuff: break # Add the received bytes to the buffer recvBuff = recvBuff + tmpBuff return recvBuff def __uploadFile(self, filename, serverSocket): """ Upload file to FTP server. :param filename: <string> the filename of the file to be uploaded to FTP server. :returns <boolean>: return True if successfully uploaded file to FTP server, otherwise return False """ try: print("\nUploading file \"" + filename + "\" to FTP server...") #open file, read the content of file and send to FTP server with open("./ClientFiles/upload/" + filename, 'r') as file: #read file data = file.read() #send file to FTP server isFileDataSent, dataSizeSent = self.__sendFileData(data, serverSocket) if isFileDataSent == True: print("\nSUCCESS: File {} uploaded. Sent {} bytes to FTP server total.".format(filename, dataSizeSent)) return True else: print("File data failed to upload to FTP server.") return False except Exception as e: clientLogger.error(e) return False def __downloadFile(self, filename, serverSocket): """ Download file from FTP server. :param filename: <string> the filename of the file to be downlowded from FTP server. :returns <boolean>: return True if successfully download file from FTP server, otherwise return False """ try: print("\nDownloading file \"" + filename + "\" from FTP server...") #receive file data from FTP server fileData, fileDataSize = self.__receiveFileData(serverSocket) #create a file and write the downloaded file data with open("./ClientFiles/download/" + filename, 'w') as file: file.write(fileData) print("\nSUCCESS: File {} downloaded. Received {} bytes total from FTP server. File stored at directory /ClientFiles/download.".format(filename, fileDataSize)) return True except Exception as e: clientLogger.error(e) return False def __listServerFiles(self, serverSocket): """ Print the list of files available on FTP server. :returns <boolean>: return True if successfully retrieved file list on FTP server, otherwise return False """ try: #retrieve file list on FTP server serverFileInfo, _ = self.__receiveFileData(serverSocket) print("\nSUCCESS: Files on FTP server are") print(serverFileInfo) return True except Exception as e: print(e) return False def __validateFilename(self, filename): """ Check if the given filename is existing. :param filename: <string> The filename to check. :returns <Boolean>: Return True if the file exists, otherwise return False. """ proc = subprocess.Popen(["ls ./ClientFiles/upload"], shell=True, stdout=subprocess.PIPE) fileListStr = proc.stdout.read().decode() fileList = fileListStr.split("\n") return True if filename in fileList else False def executeControlCommand(self, command): """ Execute the command from user input. :param command: <string> the user input command. :returns <boolean>: return True if FTP client need to be stopped, otherwise return False """ #flag indicate if the FTP client need to be quit willStopClient = False try: #get user input command operation = command[0].strip() clientLogger.debug("Received client command: %s", operation) if self.__controlChannelSocket == None and operation != "quit": self.__initControlSocket() if len(command) == 2: #get user input filename filename = command[1] #create data channel socket self.__initDataSocket() #execute get command and download file from FTP server if operation == "get": #send control data to control channel isControlDataSent = self.__sendControlData(operation, filename) if isControlDataSent == True: #get FTP server response statusCode, msg = self.__receiveControlData() if statusCode == 0: print("\nFTP server response: {}".format(msg)) # Accept server connections to data channel serverSocket = None serverAddr = None try: serverSocket,serverAddr = self.__dataChannelSocket.accept() clientLogger.debug("Accepted connection from server %s at port %d", serverAddr[0], serverAddr[1]) #download file from FTP server isDownloadSucceed = self.__downloadFile(filename, serverSocket) #if download success, get response message from FTP server if isDownloadSucceed == True: statusCode, msg = self.__receiveControlData() if statusCode == 0: print("\nFTP server response: {}".format(msg)) else: print("\nFTP server response: {}".format(msg)) serverSocket.close() except Exception as e: serverSocket.close() if self.__controlChannelSocket != None: self.__destroyControlSocket() if self.__dataChannelSocket != None: self.__destroyDataSocket() clientLogger.error(e) return else: print("\nFTP server response: {}".format(msg)) else: print("\nFailed to send control data of command {} to FTP server.".format(operation)) #execute put command and upload file to FTP server elif operation == "put": #check if the filename to upload is valid if self.__validateFilename(filename) == False: print("\nError: could not upload, file /ClientFiles/{} doesn't exist".format(filename)) if self.__controlChannelSocket != None: self.__destroyControlSocket() if self.__dataChannelSocket != None: self.__destroyDataSocket() return #send control data to control channel isControlDataSent = self.__sendControlData(operation, filename) if isControlDataSent == True: #get FTP server response statusCode, msg = self.__receiveControlData() if statusCode == 0: print("\nFTP server response: {}".format(msg)) # Accept server connections to data channel serverSocket = None serverAddr = None try: serverSocket,serverAddr = self.__dataChannelSocket.accept() clientLogger.debug("Accepted connection from server %s at port %d", serverAddr[0], serverAddr[1]) #upload file to FTP server isUploadSucceed = self.__uploadFile(filename, serverSocket) #if download success, get response message from FTP server if isUploadSucceed == True: statusCode, msg = self.__receiveControlData() if statusCode == 0: print("\nFTP server response: {}".format(msg)) else: print("\nFTP server response: {}".format(msg)) serverSocket.close() except Exception as e: serverSocket.close() if self.__controlChannelSocket != None: self.__destroyControlSocket() if self.__dataChannelSocket != None: self.__destroyDataSocket() clientLogger.error(e) return else: print("\nFTP server response: {}".format(msg)) else: print("\nFailed to send control data of command {} to FTP server.".format(operation)) #destroy data channel socket self.__destroyDataSocket() #execute ls command and get file list on FTP server else: if operation == "ls": #create data channel socket self.__initDataSocket() #send control data to control channel isControlDataSent = self.__sendControlData(operation, "") if isControlDataSent == True: #get FTP server response statusCode, msg = self.__receiveControlData() if statusCode == 0: print("\nFTP server response: {}".format(msg)) # Accept server connections to data channel serverSocket = None serverAddr = None try: serverSocket,serverAddr = self.__dataChannelSocket.accept() clientLogger.debug("Accepted connection from server %s at port %d", serverAddr[0], serverAddr[1]) #get file list from FTP server isListFileSucceed = self.__listServerFiles(serverSocket) #if download success, get response message from FTP server if isListFileSucceed == True: statusCode, msg = self.__receiveControlData() if statusCode == 0: print("FTP server response: {}".format(msg)) else: print("FTP server response: {}".format(msg)) serverSocket.close() except Exception as e: serverSocket.close() if self.__controlChannelSocket != None: self.__destroyControlSocket() if self.__dataChannelSocket != None: self.__destroyDataSocket() clientLogger.error(e) return else: print("\nFTP server response: {}".format(msg)) else: print("\nFailed to send control data of command {} to FTP server.".format(operation)) #destroy data channel socket self.__destroyDataSocket() #execute quit command and terminate the FTP client elif operation == "quit": self.stop() willStopClient = True if self.__controlChannelSocket != None: self.__destroyControlSocket() except Exception as e: clientLogger.error(e) if self.__controlChannelSocket != None: self.__destroyControlSocket() if self.__dataChannelSocket != None: self.__destroyDataSocket() return willStopClient return willStopClient def __createSocket(self): """ Creating a TCP socket. """ so = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return so def __initControlSocket(self): """ Create and initialize the client control channel socket. """ #create control channel socket self.__controlChannelSocket = self.__createSocket() #connect the control channel socket to FTP server self.__controlChannelSocket.connect((self.__serverName, self.__serverPort)) clientLogger.debug("Control socket created.") def __initDataSocket(self): """ Create and initialize the client data channel socket. """ #create data channel socket self.__dataChannelSocket = self.__createSocket() clientLogger.debug("Data channel socket created.") #bind the data channel socket to a ephemeral port self.__dataChannelSocket.bind(("localhost", 0)) #get the ephemeral port self.__dataChannelPort = self.__dataChannelSocket.getsockname()[1] clientLogger.debug("Data channel socket binded to port %d", self.__dataChannelPort) #data channel socket listen for connection self.__dataChannelSocket.listen(1) def __destroyControlSocket(self): """ Destroy the client control channel socket. """ self.__controlChannelSocket.close() self.__controlChannelSocket = None clientLogger.debug("Control channel socket destroyed.") def __destroyDataSocket(self): """ Destroy the client data channel socket. """ self.__dataChannelSocket.close() self.__dataChannelSocket = None clientLogger.debug("Data channel socket destroyed.") def stop(self): """ Stop the FTP client. """ if self.__controlChannelSocket != None: self.__destroyControlSocket() if self.__dataChannelSocket != None: self.__destroyDataSocket()
# Set up your imports here! # import ... from flask import Flask app = Flask(__name__) @app.route('/') # Fill this in! def index(): # Welcome Page # Create a generic welcome page. return "<h1>Welcome! Go to /puppy_latin/name to see your name puppy latin!</h1>" @app.route('/puppy_latin/<name>') # Fill this in! def puppylatin(name): # This function will take in the name passed # and then use "puppy-latin" to convert it! # HINT: Use indexing and concatenation of strings # For Example: "hello"+" world" --> "hello world" if name[-1] == 'y': latin = name[:-1] + 'iful' else: latin = name + 'y' return f'<h1>Hi {name.title()}! Your puppylatin name is {latin.title()}</h1>' if __name__ == '__main__': # Fill me in! app.run(debug=True)
class HashTableEntry: """ Hash Table entry, as a linked list node. """ def __init__(self, key, value): self.key = key self.value = value self.next = None def __str__(self): return f"({self.key}, {self.value})" class HashTable: """ A hash table that with `capacity` buckets that accepts string keys Implement this. """ def __init__(self, capacity): self.capacity = capacity self.storage = [None] * capacity self.key_count = 0 def fnv1(self, key): """ FNV-1 64-bit hash function Implement this, and/or DJB2. """ def djb2(self, key): """ DJB2 32-bit hash function Implement this, and/or FNV-1. """ hash = 5381 for x in key: hash = ((hash << 5) + hash) + ord(x) return hash & 0xFFFFFFFF def hash_index(self, key): """ Take an arbitrary key and return a valid integer index between within the storage capacity of the hash table. """ #return self.fnv1(key) % self.capacity return self.djb2(key) % self.capacity def put(self, key, value): """ Store the value with the given key. Hash collisions should be handled with Linked List Chaining. Implement this. Find the hash index Search the list for the key If it's there, replace the value If it's not, append a new record to the list """ load = self.key_count / self.capacity print('initial load', load) if load > 0.7: print(f'\nresized {load}\n') self.key_count = 0 self.resize(self.capacity * 2) print('=== no resize ===') index = self.hash_index(key) node = self.storage[index] if node is None: self.storage[index] = HashTableEntry(key, value) self.key_count += 1 return prev = node while node is not None: if node.key == key: node.value = value return prev = node node = node.next prev.next = HashTableEntry(key, value) self.key_count += 1 print('full load', load) def delete(self, key): """ Remove the value stored with the given key. Print a warning if the key is not found. Implement this. Find the hash index Search the list for the key If found, delete the node from the list, (return the node or value?) Else return None """ index = self.hash_index(key) node = self.storage[index] while node is not None and node.key != key: node = node.next if node is None: return None else: node.key = None def get(self, key): """ Retrieve the value stored with the given key. Returns None if the key is not found. Implement this. Find the hash index Search the list for the key If found, return the value Else return None """ index = self.hash_index(key) current = self.storage[index] while current is not None and current.key != key: current = current.next if current is None: return None else: return current.value def resize(self, new_capacity): """ Doubles the capacity of the hash table and rehash all key/value pairs. Implement this. """ storage = self.storage self.capacity = new_capacity new_storage = [None] * self.capacity self.storage = new_storage for node in storage: while node is not None: self.put(node.key, node.value) node = node.next if __name__ == "__main__": ht = HashTable(2) old_capacity = len(ht.storage) ht.put("line_1", "Tiny hash table") print('key 1', ht.key_count) ht.put("line_2", "Filled beyond capacity") print('key 2', ht.key_count) ht.put("line_3", "Linked list saves the day!") print('key 3', ht.key_count) print("") # Test storing beyond capacity print(ht.get("line_1")) print(ht.get("line_2")) print(ht.get("line_3")) # Test resizing new_capacity = len(ht.storage) print(f"\nResized from {old_capacity} to {new_capacity}.\n") # Test if data intact after resizing print(ht.get("line_1")) print(ht.get("line_2")) print(ht.get("line_3")) print("")
class rect: l=0 b=0 def __init__(self): self.l=25 self.b=50 def calc(self,a): r=self.l*self.b print(r) a=rect() b=rect() b.calc(a)
import itertools def load_input(fname="input.txt"): with open(fname) as f: return [int(d) for d in f.read().strip()] def pairwise(sequence, offset=1, circular=True): """ Iterator over offset pairs of elements from sequence >>> list(pairwise([1, 2, 3])) [(1, 2), (2, 3), (3, 1)] >>> list(pairwise([1, 2, 3], circular=False)) [(1, 2), (2, 3)] >>> list(pairwise([1, 2, 3]), offset=2) [(1, 3), (2, 1), (3, 2)] """ a, b = itertools.tee(sequence) if circular: b = itertools.cycle(b) list(itertools.islice(b, offset)) return zip(a, b) def captcha(sequence, offset=1): """ Sum of all digits that match the corresponding offset digit. Sequence is circular. >>> captcha([1, 1, 2, 2]) # 1st matches 2nd, 3rd matches 4th 3 >>> captcha([9, 1, 2, 1, 2, 1, 2, 9]) # last matches first 9 """ return sum(l for l, r in pairwise(sequence, offset=offset) if l == r) def part1(): ans = captcha(load_input()) assert ans == 1182 return ans def part2(): data = load_input() ans = captcha(data, offset=int(len(data)/2)) assert ans == 1152 return ans
from collections import Counter def load_points(): points = {} with open("input.txt") as f: for point_id, line in enumerate(f): points[point_id] = tuple(map(int, line.split(","))) return points def md(x1, y1, x2, y2): """ Manhattan distance between two points. """ return abs(x1 - x2) + abs(y1 - y2) def nearest(x0, y0, points): """ Return name of point in points closest to (x0, y0) """ distances = {name: md(x0, y0, x, y) for name, (x, y) in points.items()} minimum_distance = min(distances.items(), key=lambda x: x[1])[1] nearest_points = [name for name, distance in distances.items() if distance == minimum_distance] if len(nearest_points) == 1: return nearest_points[0] else: return False # Tie def grid_size(points): """ Return largest x and y in points {name: (x,y)} """ return (max(x for x, _ in points.values()), max(y for _, y in points.values())) def largest_region(grid, maxx, maxy): """ Return the name and size of the largest region in the grid that is not on its edge. """ infinite_regions = set([name for (x, y), name in grid.items() if x in {0, maxx} or y in {0, maxy}]) return next((region, size) for region, size in Counter(grid.values()).most_common() if region not in infinite_regions) def nearest_points_grid(points, maxx, maxy): """ Construct grid {(x, y): nearest point} giving name of point nearest to location (x, y). """ grid = {} for x in range(maxx + 1): for y in range(maxy + 1): nearest_point = nearest(x, y, points) if nearest_point: grid[(x, y)] = nearest_point return grid def within_distance_grid(points, maxx, maxy, N=10000): """ Construct grid {(x, y): boolean flag} where flag is True if the sum of the Manhattan distances from (x, y) to all points is < N. """ grid = {} for x in range(maxx + 1): for y in range(maxy + 1): if sum(md(x, y, xp, yp) for (xp, yp) in points.values()) < N: grid[(x, y)] = True else: grid[(x, y)] = False return grid def part1(): points = load_points() maxx, maxy = grid_size(points) grid = nearest_points_grid(points, maxx, maxy) return largest_region(grid, maxx, maxy) def part2(): points = load_points() maxx, maxy = grid_size(points) grid = within_distance_grid(points, maxx, maxy) return sum(grid.values())
a = 5; b=13; sum=a+ \ b print(sum) ##sum raw_input("\n enter key to continue") print("ritesh")
#!/usr/bin/python import random class Generator(): def __init__(self, base, length, amount, encode, decode): '''Base to generate in, the length of the hashes, amount of hashes to generate, conversion function''' self.base = base self.length = length self.amount = amount self.encode = encode self.decode = decode self.i = 0 self.lowerBound = 0 self.upperBound = pow(self.base, self.length) def getRandomNumber(self): return random.randint(self.lowerBound, self.upperBound) def getShortHash(self): n = self.getRandomNumber() enc = self.encode(n) return self.pad(enc) def pad(self, n): if len(n) < self.length: x = self.length - len(n) return ('0' * x) + n else: return n def __iter__(self): return self def next(self): if self.i >= self.amount: raise StopIteration else: self.i += 1 return self.getShortHash()
""" 1.Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. - проверить ввод, если длинна !=3 то повторить ввод - если длинна == 3 - то взять первый символ, сложить его со вторым и с третьим - взять все символы и перемножить """ import sys def num_info(): while True: num = int(input('Введите трехзначное число: ')) if len(str(num)) == 3: a = num % 10 num = num // 10 b = num % 10 num = num // 10 c = num % 10 result = c + b + a, c * b * a return result sys.exit() else: print('вы ввели не трех значное число') if __name__ == '__main__': print(num_info())
import random print ("Welcome to the guessing game!") computerNumber = random.randint(1,20) enteredNumber=0 totalGuesses=0 while enteredNumber != computerNumber: print("Enter a number between 1 and 20: ", sep='') totalGuesses=totalGuesses+1 enteredNumber=int(input()) if enteredNumber > computerNumber: print ("Number is too high") else: print ("Number is too low") print ('Congratulations, you guessed correctly in', str(totalGuesses), 'tries')
# Create a function that takes 2 positive integers in form of a string as an input, and outputs the sum (also as a string) # sum_str("4", "5") # should output "9" # sum_str("34", "5") # should output "39" # If either input is an empty string, consider it as zero. # my solution def sum_str(a, b): if a == "": a = 0 if b == "": b = 0 x = int(a) + int(b) return str(x) # best practiced solution from vote # def sum_str(a, b): # return str(int(a or 0) + int(b or 0))
def derive(coefficient, exponent): return str(coefficient * exponent) + f"x^{exponent - 1}" #best practiced solution by vote # def derive(coefficient, exponent): # return f'{coefficient * exponent}x^{exponent - 1}' #damn why didn't I just do it like that, not this time. but next time I will be sure to remember it.
num=int(input("enter the number")) factorial=1 if num<1: print("No factorial is exist") elif num==0: print("factorial of 0 is 1") elif num >1: for i in range(1,num+1): factorial=factorial*i break print(factorial,"is the factorial of num")
kilometer=float(input("how many kilometer:")) facter=0.62137 mile=kilometer*facter print("{}kilometer is equal to {} mile".format(kilometer,mile))
#inputs #Amusment park height = input("How tall are you? " ) height = int(height) if height >= 160: print("You are tall enough to ride this ride.") else: print("Get out of here halfling.") number = input("Enter to see if your number is even or odd. ") number = int(number) if number % 2 == 0: print("Your number is even") else: print("Your number is odd") current_number = 1 while current_number <= 5: print(current_number) current_number += 1 #Using a flag flag = True while flag == True: message = input("I will repeat what you say. Input quit to stop. ") if message == 'quit': flag = False else: print(message) #Using a break to end a loop prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.)\n" while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 16 19:22:35 2019 @author: qinyachen """ from Deck import deck from player import Player import random import time class Game: def __init__(self,players): ''' The playerlist contains all players in the game. eg.[player1,palyer2...] playerpoints contains all players points in the game. eg.[10,2.....] playerAnums contains how many a each player has. eg.[0,0,1,...] playeractions conatins the action order of players. rewards is the money all player(include dealer) has. moneybet contains the money each player bet in a round. eg.[10,5,20....] ''' self.playerlist = [] for player in enumerate(players): self.playerlist.append(Player(player[0],player[1])) self.dealer = Player(6,0) self.dealerpoints = 0 self.playerpoints = [] self.playerAnums = [] self.actions = [0,1,2,3,4,5,6] self.table = deck() #the cards use for this game self.table.shuffle() #shuffle the card self.bust = 0 #number of bust in one game round self.rewards = [50,50,50,50,50,50,50] self.moneybet = [0,0,0,0,0,0,0,0] def play(self): ''' the process of the whole game ''' while(self.table.ifenough()): self.reset() self.run_one_time() print("game end") print("the final money is") print(self.rewards) def reset(self): ''' clear the playerpoints and playerAnums reset the cards in player's hand and assign them new cards for a next round ''' print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++") print("round start") self.playerpoints = [] self.playerAnums = [] self.bust = 0 for player in self.playerlist: player.reset_() player.getcard(self.table) player.getcard(self.table) self.playerpoints.append(player.getpoints()[0]) self.playerAnums.append(player.getpoints()[1]) self.dealer.reset_() self.dealer.getcard(self.table) self.dealerpoints = self.dealer.getpoints()[0] print("now the points of all after all deals" ) print(self.playerpoints) print("now the num of A in all players " ) print(self.playerAnums) print("the dealer points after first is " + str(self.dealerpoints)) self.dealer.getcard(self.table) self.dealerpoints = self.dealer.getpoints()[0] print("the money of all person") print(self.rewards) def run_one_time(self,): ''' The function define each round of the game. Determin who win in this round and give winner money. ''' for action in self.actions: #dealers turn, the last one act during play if(action == 6): #if points in dealer's hand less than 17, it must take next card while(self.dealerpoints < 17): self.dealer.getcard(self.table) self.dealerpoints = self.dealer.getpoints()[0] #if dealer bust, everyone not bust win the money if(self.dealerpoints > 21): self.bust += 1 print("dealer bust!") for i in range(6): self.rewards[i] += self.moneybet[i] self.rewards[action] -= self.moneybet[i] #if dealer not bust, the larger one compare with dealer win the money else: for points in enumerate(self.playerpoints): if(points[1] > self.dealerpoints and points[1] <=21): self.rewards[points[0]]+=self.moneybet[points[0]] self.rewards[action] -= self.moneybet[points[0]] elif(points[1] < self.dealerpoints and points[1] <=21): self.rewards[action]+=self.moneybet[points[0]] self.rewards[points[0]]-=self.moneybet[points[0]] #human turn elif(self.playerlist[action].type == 1): self.humanrun(action) #AI turn else: self.AI_run(action) print("===================================================") print("the result is for this round is ") print(self.playerpoints) print("the result of dealer for this round is ") print(self.dealerpoints) print("the money is for this round is ") print(self.rewards) print("round end") print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++") time.sleep(10) def humanrun(self,action): ''' input: the order number of action(0-5) let the player use command to decide if hit or not(y-hit, other-stand) ''' print("===================YOUR TURN================================") print("now the points of all after all deals" ) print(self.playerpoints) print("now the num of A in all players " ) print(self.playerAnums) print("now is player "+str(action+1)+"'s turn") print("now the points of you is" ) print(self.playerpoints[action]) print("now the A num of you is" ) print(self.playerAnums[action]) print("====================================================") print("now the money of all is" ) print(self.rewards) print("===================================================") bet = int(input("the money you want to bet:")) self.moneybet[action] = bet print("y is hit and n is not") while(input()=="y" and self.playerpoints[action] < 21): self.playerlist[action].getcard(self.table) self.playerpoints[action]=self.playerlist[action].getpoints()[0] print("now the points of you is" ) print(self.playerpoints[action]) if(self.playerpoints[action] >= 21): break if(self.playerpoints[action] > 21): print("player "+str(action+1)+ " bust!") self.bust += 1 self.rewards[action] = self.rewards[action] - bet self.rewards[6] += bet else: self.rewards[action] += 0 print("=============YOUR TURN END======================================") def AI_run(self,action): ''' input: the order number of action(0-5) let the AI use rand_pick function decide if hit or not(1-hit, 0-stand) ''' bet = int(self.rewards[action]/3) if(bet==0): bet = 1; self.moneybet[action] = bet seq = [1,0] ifnext = self.rand_pick(seq,[(21 - self.playerpoints[action])/10,1-(21 - self.playerpoints[action])/10]) while(ifnext == 1 and self.playerpoints[action] < 21): self.playerlist[action].getcard(self.table) self.playerpoints[action]=self.playerlist[action].getpoints()[0] ifnext = self.rand_pick(seq,[(21 - self.playerpoints[action])/10,1-(21 - self.playerpoints[action])/10]) if(self.playerpoints[action] > 21): print("player "+str(action+1)+ " bust!") self.bust += 1 self.rewards[action] = self.rewards[action] - bet self.rewards[6] += bet else: self.rewards[action]+=0 def rand_pick(self,seq,probabilities): ''' given an array and probability, return a number in array gnerate with probability input: eg.([0,1,2],[0.1,0.4,0.5]) output: random number in [0,1,2] with different probability eg.2 ''' x = random.uniform(0 ,1) cumprob = 0.0 for item , item_pro in zip(seq , probabilities): cumprob += item_pro if x < cumprob: break return item
import matplotlib.pyplot as plt import pandas as pd df=pd.read_excel("") fig=plt.figure() #Plots in matplotlib reside within a figure object, use plt.figure to create new figure #Create one or more subplots using add_subplot, because you can't create blank figure ax = fig.add_subplot(1,1,1) #Variable ax.hist(df['Credit_history'],bins = 4) # Here you can play with number of bins Labels and Tit plt.title('Loan Amount') plt.xlabel('loan_amount') plt.ylabel('Credit_history') plt.show()
#list a = [1,2,3,4,5] a.append(100) a.remove(4) #print (a) #tuple a = (1,2,3,4) #print (a) #dict #{key:value} a= { 1:True, 2:False } #print (a) #str s1 = '\'string\'' s2 = "\"string\"" #print s1 a = 3 + 4 and 10 - 4 and "1" #print a, type(a) if 5 > 4: print 'Case 1' else: print 'Case 2' for a in range(10): if a == 3: continue print a,",", type(a)
word = str(input()) number = str(input()) n = (int(number)) c = int(number[len(number) - 1]) d = int(number[len(number) - 2]) if word == 'утюг': if n == 1 or c == 1 and d != 1: print(n, "утюг") elif 2 <= n <= 4 or 2 <= c <= 4 and d != 1: print(n, "утюга") else: print(n, "утюгов") if word == 'ложка': if n == 1 or c == 1 and d != 1: print(n, "ложка") elif 2 <= n <= 4 or 2 <= c <= 4 and d != 1: print(n, "ложки") else: print(n, "ложек")
from binarySearchTree import BST from binarySearchTree import Node class AugmentedBST(BST): def __init__(self): """Initialize a node_class, used in the current implementation of insert""" self.node_class = AugmentedNode def insert_node(self, key): """ Insert node to the tree with value *key* Increment num_sub_nodes on every node passed Check to ensure key is unique Return the inserted node Returns None if key cannot be inserted """ if not isinstance(key, (int, float, long)): print "Cannot insert", key return None if not self.root: self.root = self.node_class(key) return self.root prev_node = None curr_node = self.root incremented_nodes = [] while curr_node: prev_node = curr_node incremented_nodes.append(prev_node) if key == curr_node.key: return None if key > curr_node.key: curr_node = curr_node.right else: curr_node = curr_node.left for node in incremented_nodes: node.increment_sub_tree() inserting = self.node_class(key) if key > prev_node.key: prev_node.right = inserting else: prev_node.left = inserting return inserting def rotate_right(self, key): """ Rotate right at the node found by key. Checks for NULL node or left child Modify subtree counts appropriately Reattaches rotated piece back into tree. """ node, parent = self._find_node_and_parent(key) if not node or not node.left: # Inoperable rotation return B = node.left node.left = B.right if B.left: node.decrement_sub_tree(B.left.num_sub_nodes) # Remove count for node not on subtree node.decrement_sub_tree() # Account for B B.right = node if node.right: B.increment_sub_tree(node.right.num_sub_nodes) B.increment_sub_tree() # Account for node itself if not parent: # Rotating root self.root = B else: if B.key > parent.key: # right child of parent parent.right = B else: parent.left = B def rotate_root_right(self): """ Rotate the root to the right. Doesn't spend time to find node. Modify subtree counts appropriately """ node = self.root if not node or not node.left: return B = node.left node.left = B.right if B.left: node.decrement_sub_tree(B.left.num_sub_nodes) node.decrement_sub_tree() # Account for B B.right = node if node.right: B.increment_sub_tree(node.right.num_sub_nodes) B.increment_sub_tree() # Account for node self.root = B def rotate_left(self, key): """ Rotate left at the node found by key. Checks for NULL node or right child Modify subtree counts appropriately Reattaches rotated piece back into tree. """ node, parent = self._find_node_and_parent(key) if not node or not node.right: return A = node.right node.right = A.left if A.right: node.decrement_sub_tree(A.right.num_sub_nodes) node.decrement_sub_tree() # Account for A A.left = node if node.left: A.increment_sub_tree(node.left.num_sub_nodes) A.increment_sub_tree() # Account for the node itself if not parent: # rotating root self.root = A else: if A.key > parent.key: # right child of parent parent.right = A else: parent.left = A def rotate_root_left(self): """ Rotate the root to the left. Doesn't spend time to find node. Modify subtree counts appropriately """ node = self.root if not node or not node.right: return A = node.right node.right = A.left if A.right: node.decrement_sub_tree(A.right.num_sub_nodes) node.decrement_sub_tree() # Account for A A.left = node if node.left: A.increment_sub_tree(node.left.num_sub_nodes) A.increment_sub_tree() # Account for node self.root = A def _decrement_subtree_counts_to_node(self, last_decremented_node): curr_node = self.root last_decremented_key = last_decremented_node.key last_decremented_node.decrement_sub_tree() while curr_node.key != last_decremented_key: curr_node.decrement_sub_tree() if curr_node.key > last_decremented_key: curr_node = curr_node.left else: curr_node = curr_node.right def _delete_node_without_both_children(self, node, parent): """Delete function without both children under the assumption the parent exists""" if not node.left: if parent.key > node.key: parent.left = node.right else: parent.right = node.right else: if parent.key > node.key: parent.left = node.left else: parent.right = node.left self._decrement_subtree_counts_to_node(parent) return class AugmentedNode(Node): """ Representation of a node on a tree containing a value and left/right pointers to start, as well as the number of nodes on a subtree with the root at that node """ def __init__(self, value): """ Initialize an empty node with *value* and left/right pointers set to None. *self.num_sub_nodes* used for various algorithms. """ self.key = value self.num_sub_nodes = 1 def increment_sub_tree(self,val=1): """Increment the number of sub nodes by *val*""" self.num_sub_nodes += val def decrement_sub_tree(self, val=1): """Decrement the number of sub nodes by *val*""" self.num_sub_nodes -= val def test_subtree_counts(node): if not node: return True if not node.right and not node.left: return node.num_sub_nodes == 1 if not node.right: return node.num_sub_nodes == node.left.num_sub_nodes+1 and \ test_subtree_counts(node.left) if not node.left: return node.num_sub_nodes == node.right.num_sub_nodes+1 and \ test_subtree_counts(node.right) return node.num_sub_nodes == node.left.num_sub_nodes + node.right.num_sub_nodes + 1 and \ test_subtree_counts(node.left) and test_subtree_counts(node.right) def main(): T = AugmentedBST() T.insert_node(5) T.insert_node(6) T.insert_node(3) T.insert_node(7) T.insert_node(1) for i in range(11): T.insert_node(i) T.insert_node(4.5) T.print_tree() print T.inorder_traversal_r() print T.preorder_traversal_r() print T.postorder_traversal_r() print "Subtree counts working...", test_subtree_counts(T.root) T.rotate_right(5) print "Subtree counts working...", test_subtree_counts(T.root) T.rotate_left(1) print "Subtree counts working...", test_subtree_counts(T.root) T.print_tree() T.rotate_root_left() print "Subtree counts working...", test_subtree_counts(T.root) T.print_tree() T.print_tree() T.insert_node(8.3) T.print_tree() T.delete_node(10) T.print_tree() T.delete_node(8) T.print_tree() #print "Subtree counts working...", test_subtree_counts(T.root) #print T.find_node(6).num_sub_nodes if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Basic unit testing of API @author: NikolaLohinski (https://github.com/NikolaLohinski) @date: 02/02/09 """ def test_get_empty_inventions(client): """After basic creation of DB test if get inventions is empty list""" request = client.get('api/v0/inventions') assert request.status_code == 200 body = request.json # gives you a list assert body['success'] assert isinstance(body['result']['inventions'], list) assert len(body['result']['inventions']) == 0 def test_re_init_db(client): """Test if re init of DB yields 17 records from inventions.json file""" request = client.put('api/v0/inventions/init') assert request.status_code == 200 body = request.json assert body['success'] assert isinstance(body['result']['inventions'], list) assert len(body['result']['inventions']) == 17 def test_add_invention(client): """Test adding an invention to DB""" invention = { 'name': 'test invention', 'date': 1564 } request = client.post('api/v0/inventions', json=invention) assert request.status_code == 200 body = request.json assert body['success'] record = body['result']['invention'] assert all(record[key] == value for key, value in invention.items()) # Test if everything was added request = client.get('api/v0/inventions') body = request.json assert body['result']['inventions'][0] == record def test_delete_invention(client): """Test deleting an invention from DB""" invention = { 'name': 'new invention', 'date': 1798 } request = client.post('api/v0/inventions', json=invention) assert request.status_code == 200 body = request.json assert body['success'] _id = body['result']['invention']['_id'] request = client.delete('api/v0/inventions/%s' % _id) assert request.status_code == 200 record = request.json['result']['invention'] request = client.get('api/v0/inventions') body = request.json assert record not in body['result']['inventions']
from heapq import heappush, heappop from itertools import count class PriorityQueue: REMOVED = '<removed-task>' def __init__(self): self.elements = [] self.entry_finder = {} self.counter = count() def add_task(self, task, priority=0): """Add a new task or update the priority of an existing task""" if task in self.entry_finder: self.remove_task(task) tiebreaker = next(self.counter) entry = [priority, tiebreaker, task] self.entry_finder[task] = entry heappush(self.elements, entry) def remove_task(self, task): """Mark an existing task as REMOVED. Raise KeyError if not found.""" entry = self.entry_finder.pop(task) entry[-1] = self.REMOVED def pop_task(self): """Remove and return the lowest priority task. Raise KeyError if empty.""" while self.elements: priority, tiebreaker, task = heappop(self.elements) if task is not self.REMOVED: del self.entry_finder[task] return task raise KeyError('pop from an empty priority queue') def get_task_priority(self, task): """Returns the priority of a given task""" return self.entry_finder[task][0] def is_empty(self): return len(self.elements) == 0 def __iter__(self): for key in self.entry_finder: yield key
import random class Dice: def roll(self): first = random.randint(1,6) second = random.randint(1,6) return first, second for i in range(3): print(random.random()) for i in range(3): print(random.randint(10,20)) members = ['Carvin', 'Joseph', 'Kyle'] leader = random.choice(members) print(leader) dice = Dice() print(dice.roll())
#Program 4-17 #This Program averages test scores. #It askes the user for the number of students #and the number of test scores per students. #Get the number of students. num_students = int(input('How many students do you have?')) #Get the number of test scores per student. num_test_scores = int(input('How many test scores per student?')) #Determine each studen's average test score. for student in range(num_students): #Initialize an accumulator for test score loop total = 0.0 #Get a student's test scores. print('Student number', student + 1) print('-----------------') for test_num in range(num_test_scores): print('Test number', test_num + 1, end='') score = float(input(': ')) #Add the scores to the accumulator. total += score #Calculate the average test score for this student. average = total / num_test_scores #Display the average. print('The average for student number', student + 1, \ 'is:', average) print()
#This program will split a total bill from a restaurant or whatever establishment and guarantee an even split #import math to use Ceil method (which will round up) import math def split_check(total, number_of_people): #divide the total amongst people #use the ceiling to allow rounding #check if the person is giving incorrect information if number_of_people <= 1: #raise exception and let the user know raise ValueError("Looks like you are paying for everything") return math.ceil(total / number_of_people) #exception handling try: total_due = float(input("What is your total? ")) number_of_people = int(input("How many are in your group? ")) amount_due = split_check(total_due, number_of_people) except ValueError as err: print("Oh no! That's not a valid value. Try again...") print("({})".format(err)) else: print("Each Person owes ${}".format(amount_due)) print("#############################") #Testing amount_due = split_check(180,4) #display results print(amount_due) #Test2: amount_due = split_check(84.97, 5) #display result with the format print("Each Person owes ${}".format(amount_due)) print("#############################") #Testing with input: #Need to cast the variables as floats or ints for function call to work total_due = float(input("What is your total? ")) number_of_people = int(input("How many are in your group? ")) amount_due = split_check(total_due, number_of_people) print("Each Person owes ${}".format(amount_due))
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> #Floating-point Program example 2-21 >>> monthly_pay = 5000.00 >>> annual_pay = monthly_pay * 12 >>> print('Your annual pay is $',format(annual_pay, ',.2f')) Your annual pay is $ 60,000.00 >>> monthly_pay = 1410.00 >>> annual_pay = monthly_pay * 12 >>> print('Your annual pay is $ ',format(annual pay, ',.2f')) SyntaxError: invalid syntax >>> print('Your annual pay is $ ',format(annual_pay, ',.2f')) Your annual pay is $ 16,920.00 >>> monthly_pay = 720.00 >>> annual_pay = monthly_pay * 12 >>> print('Your annual pay is $',format(annual_pay, ',.2f')) Your annual pay is $ 8,640.00 >>>
class Node(object): """ Node contains two objects - a left and a right child, both may be a Node or both None, latter representing a leaf """ def __init__(self, left=None, right=None): super(Node, self).__init__() self.left = left self.right = right def __str__(self): """ Default inorder print """ if self.left is None and self.right is None: return "( )" else: return "( " + str(self.left) + " " + str(self.right) + " )" def __eq__(self, other): if self.left is None and self.right is None: return other.left is None and other.right is None elif other.left is None and other.right is None: return False else: return self.left == other.left and self.right == other.right def mirrorTree(node): temp = Node() if node.left is not None: temp.right = mirrorTree(node.left) if node.right is not None: temp.left = mirrorTree(node.right) return temp pass def allTrees(n): trees =[] if n == 0 : temp = Node() return [temp] else: for l in range(0,n): r = n-1-l ltrees = allTrees(l) rtrees = allTrees(r) trees += [Node(newl,newr) for newl in ltrees for newr in rtrees] return trees pass def allSymTrees(n): sym = [] if(n == 0) : return [Node()] if(n%2 == 0): return sym total = allTrees((n-1)//2) sym = [Node(tree,mirrorTree(tree)) for tree in total] return sym pass if __name__ == '__main__': for x in allSymTrees(int(input())): print(x) node = Node(Node(Node(), Node()), Node()) print(node)
line = "" for i in range(1, 10): line += "*" * i line += "\n" print(line) line = "" i = 0 while i < 11: line += "*" * i line += "\n" i += 1 print(line)
from collections import defaultdict def PatternCount(genome: str, pattern: str): """ Return count of occurrences of `pattern` in `genome` """ count = 0 k = len(pattern) for x in range(0, len(genome) - k + 1): if genome[x:x+k] == pattern: count += 1 return count def FrequentPatterns(genome: str, k: int): """ Return most frequent kmers of length `k` in `genome` """ frequent_patterns = defaultdict(int) for x in range(0, len(genome) - k + 1): frequent_patterns[genome[x:x+k]] += 1 max_count = max(frequent_patterns.values()) most_frequent = {k:v for k,v in frequent_patterns.items() if v == max_count} return " ".join([m for m in most_frequent])
import random import copy def crea_puzzle(): puzzle = [[0, 2, 3], [1, 4, 6], [7, 5, 8]] random.shuffle(puzzle[0]) random.shuffle(puzzle[1]) random.shuffle(puzzle[2]) random.shuffle(puzzle[random.randint(0, 2)]) return puzzle def movimientos(puzzle, predecesor): hijos = [] if 0 in puzzle[0]: i = 0 j = puzzle[0].index(0) elif 0 in puzzle[1]: i = 1 j = puzzle[1].index(0) else: i = 2 j = puzzle[2].index(0) hijo1 = copy.deepcopy(puzzle) hijo2 = copy.deepcopy(puzzle) hijo3 = copy.deepcopy(puzzle) hijo4 = copy.deepcopy(puzzle) if j + 1 < len(hijo1[0]): y = hijo1[i][j] hijo1[i][j] = hijo1[i][j+1] hijo1[i][j+1] = y if j - 1 >= 0: y = hijo2[i][j] hijo2[i][j] = hijo2[i][j-1] hijo2[i][j-1] = y if i + 1 < len(hijo3): y = hijo3[i][j] hijo3[i][j] = hijo3[i+1][j] hijo3[i+1][j] = y if i - 1 >= 0: y = hijo4[i][j] hijo4[i][j] = hijo4[i-1][j] hijo4[i-1][j] = y if hijo1 != puzzle: hijos.append(hijo1) if hijo2 != puzzle: hijos.append(hijo2) if hijo3 != puzzle: hijos.append(hijo3) if hijo4 != puzzle: hijos.append(hijo4) return hijos def Bfs(puzzle, solucion): nivel = 0 arbol = {nivel: puzzle} hijos = movimientos(puzzle, "null") nivel += 1 arbol[nivel] = hijos while nivel < 500: nivel = nivel + 1 for i in hijos: hijos2 = movimientos(i, "null") if solucion in hijos: return hijos, True if nivel not in arbol: arbol[nivel] = hijos2 else: arbol[nivel].append(hijos2) hijos[:] = [] for j in hijos2: hijos.append(j) hijos2[:] = [] return arbol, False def Dfs(puzzle, solucion): nivel = 0 arbol = {nivel: puzzle} hijos = movimientos(puzzle, "null") nivel += 1 arbol[nivel] = hijos explorado = list() stack = [copy.deepcopy(puzzle)] while nivel < 1000: nodo_actual = stack.pop() nivel = nivel + 1 for tmp in movimientos(puzzle, "null"): stack.append(tmp) explorado.append([nodo_actual]) if solucion in nodo_actual: return arbol, True hijos = copy.deepcopy(movimientos(nodo_actual, "null")) for hijo in hijos: if hijo not in explorado: stack.append(hijo) explorado.append([hijo]) if nivel not in arbol: arbol[nivel] = hijo else: arbol[nivel].append(hijo) nodo_actual = [] return arbol, False def aStar(puzzle, solucion): nivel = 0 arbol = {nivel: puzzle} hijos = movimientos(puzzle, "null") nivel += 1 explorado = list() stack = copy.deepcopy([puzzle]) hInicial = h(puzzle, solucion) while nivel < 10000: nodo_actual = stack.pop() nivel = nivel + 1 for tmp in movimientos(puzzle, "null"): stack.append(tmp) explorado.append([nodo_actual]) if solucion in nodo_actual: return arbol, True hijos = copy.deepcopy(movimientos(nodo_actual, "null")) for hijo in hijos: hActual = h(hijo, solucion) if hActual == 0: if nivel not in arbol: arbol[nivel] = hijo else: arbol[nivel].append(hijo) return arbol, True elif hActual < hInicial: hInicial = hActual stack.append(hijo) explorado.append([hijo]) if nivel not in arbol: arbol[nivel] = hijo else: arbol[nivel].append(hijo) break nodo_actual = [] return arbol, False def hillClimbing(puzzle, solucion): stack = copy.deepcopy([puzzle]) nivel = 0 arbol = {nivel: puzzle} while nivel < 1000: if len(stack) <= 0: return arbol, False state = stack.pop() nivel += 1 if state == solucion: return arbol, True h_val = h(state, solucion) next_state = False hijos = movimientos(state, "null") for hijo in hijos: h_val_sig = h(hijo, solucion) # El algoritmo continua solo si se tiene una h(x) igual o menor con una h(x)_siguiente menor o igual # de otra menera el algoritmo se detiene. if h_val_sig <= h_val and not hijo in arbol.values(): next_state = copy.deepcopy(hijo) h_val = h_val_sig stack.append(next_state) if nivel not in arbol: arbol[nivel] = hijo else: arbol[nivel].append(hijo) break return arbol, False def h(puzzle, solucion): temp = 0 for i in range(0, 3): for j in range(0, 3): if puzzle[i][j] != solucion[i][j] and solucion[i][j] != '0': temp += 1 return temp cant = 0 solucion = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] while True: op = int(input( "Seleccione el modelo\n\n\t1) Dfs\n\t2) A* Search\n\t3) Bfs\n\t4) Hill Climbing\n\t0) Salir\n\n\nOpcion: ")) if op == 1 or op == 3: print("Solucion: ", solucion) for j in range(0, 10): for i in range(0, 10): puzzle = crea_puzzle() if op == 1: res, flag = Dfs(puzzle, solucion) elif op == 3: res, flag = Bfs(puzzle, solucion) if flag: cant = cant + 1 print("Puzzle: ", res) print("Vuelta: ", j+1, " Cantidad: ", cant) print("-"*60) promedio = cant / 10 print("Promedio: ", promedio) elif op == 2 or op == 4: print("Solucion: ", solucion) for j in range(0, 10): puzzle = crea_puzzle() if op == 2: res, flag = aStar(puzzle, solucion) if op == 4: res, flag = hillClimbing(puzzle, solucion) if flag: cant = cant + 1 print("Puzzle: ") for i in res: print(res[i]) print("Vuelta: ", j+1, " Cantidad: ", cant) print("-"*60) promedio = cant / 10 print("Promedio: ", promedio) elif op == "0": break else: print("Caracter incorrecto")
""" Created on Wed Sep 7 22:25:16 2016 @author: James """ import math # We need to import the math module for use in this function def polysum(n, s): """ input : n,s - positive integers where 'n' is the number of sides and 's' is the length of each side. Returns the sum of the perimeter squared and the area. """ perimeter = n * s # This variable is the total length of the boundary of the polygon. area = (0.25 * n * (s ** 2)) / math.tan(math.pi/n) # This variable is the total area of the polygon. This iswhy we needed # to import the math module! return round((perimeter ** 2) + area, 4) # Here we do our final calculation and return the value, rounding # it to 4 decimal places as required.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 11 17:15:52 2019 @author: flatironschool """ # import csv text_file = open('top-500-songs.txt', 'r') # read each line of the text file # here is where you can print out the lines to your terminal and get an idea #for how you might think about re-formatting the data lines = text_file.readlines() songs = [] #for each line in the list of lines for line in lines: #remove the \n treat before and after as seperate strings song = line.strip('\n') #remove the \t from the front and back as seperate strings songs.append(song.split('\t')) songs_as_dicts = [] for song in songs: #create dict keys and assign them the empty song_as_dict dictionary song_as_dict = {} song_as_dict['rank'] = song[0] song_as_dict['name'] = song[1] song_as_dict['artist'] = song[2] song_as_dict['year'] = song[3] songs_as_dicts.append(song_as_dict) print(songs_as_dicts[0])
class HashTable: size = 0 items = [] def __init__(self, size): self.size = size def hash(self, key, size = None): """ - count string, divide length of string by m and return the remainder """ size = size if size else self.size index = len(key) % size return index def add(self, key, value): hashed_index = self.hash(key) if self.items[hashed_index] == None: self.items[hashed_index] = [] self.items[hashed_index].append(value) pass def exists(self, key): hashed_index = self.hash(key) if len(self.items) > hashed_index and self.items[hashed_index] != None : return True return False def get(self, key): hashed_index = self.hash(key) if len(self.items) > hashed_index: return self.items[hashed_index] return False def remove(self, key): hashed_index = self.hash(key) self.items.pop(hashed_index) pass
import random win = 0 lose = 0 for x in range(0, 1000): flip = random.randint(1, 100) if flip > 49: win += 1 else: lose += 1 print("Wins is: " + str(win)) print("Losses is: " + str(lose)) print("net gain/loss is: $" + str((win - lose) * 100))
# Santa needs help figuring out which strings in his text file are naughty or nice. # A nice string is one with all of the following properties: # It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou. # It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd). # It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements. # For example: # ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...), and none of the disallowed substrings. # aaa is nice because it has at least three vowels and a double letter, even though the letters used by different rules overlap. # jchzalrnumimnmhp is naughty because it has no double letter. # haegwjzuvuyypxyu is naughty because it contains the string xy. # dvszwmarrgswjxmb is naughty because it contains only one vowel. # How many strings are nice? #Answer: 238 nice=0 word="" with open("05 - nice naughty.txt") as txt: for line in txt: temp=list(line) vowels=0 repetition=False contain=False for position, i in enumerate(temp): if i=="a" or i=="e" or i=="i" or i=="o" or i=="u": vowels+=1 if word == i: repetition=True if word+i == "ab" or word+i == "cd" or word+i == "pq" or word+i == "xy": contain=True word = i if vowels>=3 and repetition and not contain: nice+=1 print(nice)
import string import hashlib translator = str.maketrans('','', string.punctuation) with open('titanic_srt.txt', 'r') as file: # read each line for line in file: #read each word which is split by a space for word in line.split(): # turn each word into lowercase lower = word.lower() # remove all punctuation lower_no_punc = lower.translate(translator) # wrap in flag encased = 'tjctf{' + lower_no_punc + '}' no_punc_encoded = hashlib.md5(encased.encode()) hashed = no_punc_encoded.hexdigest() # print(hashed) if hashed == '9326ea0931baf5786cde7f280f965ebb': print('[*] Hash found!') print(encased) print(hashed) break else: continue
import random Set_number = random.randint(0,100) print(Set_number) N = 1 try: Guess_number = int(input("输入猜测的数:")) except NameError and ValueError: print("输入内容须为整数!") Guess_number = int(input("重新输入猜测的数:")) N = N + 1 while(Guess_number < Set_number or Guess_number > Set_number): N = N + 1 if Guess_number > Set_number: print("对不起,太大了") elif Guess_number < Set_number: print("对不起,太小了") try: Guess_number = int(input("重新输入猜测的数:")) except NameError and ValueError: print("输入内容须为整数!") Guess_number = int(input("重新输入猜测的数:")) N = N + 1 print("预测{}次,你猜中了".format(N))
import numpy as np import pandas as pd import matplotlib.pylab as plt import time as tm """ This code was written as part of a larger project to develope a model that accurately describes the biological interractions between a pest insect and its habitat, namely the eastern spruce budworm and the spruce forests it inhabits. The model is developed in the written paper, and here the system of equations is solved and displayed graphically. The solution is calculated and displayed using the below define Runge-Kutta 4 numerical method and matplotlib library. """ def rk4(dt, t, field, y_0): """ :param dt: float - the timestep :param t: array - the time mesh :param field: method - the vector field y' = f(t, y) :param y_0: array - contains initial conditions :return: ndarray - solution """ # Initialize solution matrix. Each row is the solution to the system # for a given time step. Each column is the full solution for a single # equation. y = np.asarray(len(t) * [y_0]) for i in np.arange(len(t) - 1): k1 = dt * field(t[i], y[i]) k2 = dt * field(t[i] + 0.5 * dt, y[i] + 0.5 * k1) k3 = dt * field(t[i] + 0.5 * dt, y[i] + 0.5 * k2) k4 = dt * field(t[i] + dt, y[i] + k3) y[i + 1] = y[i] + (k1 + 2 * k2 + 2 * k3 + k4) / 6 return y if __name__ == '__main__': def system(t, vect): b, s, e = vect return np.array([(r_b * b * (1 - (b * (pow(T, 2) + pow(e, 2))) / (K * s * pow(e, 2))) - (beta * pow(b, 2)) / (pow((alpha * s), 2) + pow(b, 2))), r_s * s * (1 - (s * K_e) / (e * K_s)), r_e * e * (1 - e / K_e) - (P * b * pow(e, 2)) / (s * (pow(T, 2) + pow(e, 2)))]) # set parameter values from Ludwig paper r_b = 1.52 r_s = 0.095 r_e = 0.92 alpha = 1.11 beta = 43200 K = 355 K_s = 25440 K_e = 1 P = 0.00195 T = 0.1 t_0 = 0. t_n = 50. Dt = .1 steps = int(np.floor((t_n - t_0) / Dt)) time = np.arange(t_0, t_n, Dt) # Initialize solution vector and initial conditions x_0 = [1e-16, .075 * K_s, 1.] # Solve the system of equations start = tm.time() x = rk4(Dt, time, system, x_0) print("runtime was", tm.time() - start, "seconds") # Create Pandas DataFrame df = pd.DataFrame(x, index=time, columns=['B', 'S', 'E']) fig, ax1 = plt.subplots(figsize=(10, 6)) fig.subplots_adjust(right=0.75) fig.suptitle('Forest Health and Population Dynamics') color = 'red' ax1.set_xlabel('Years') ax1.set_ylabel('Budworm Population Density', color=color) ax1.plot(time, df.loc[:,'B'], color=color) ax1.tick_params(axis='y', labelcolor=color) color = 'green' ax2 = ax1.twinx() ax2.set_ylabel('Foliage Density', color=color) ax2.plot(time, df.loc[:,'S'], color=color) ax2.tick_params(axis='y', labelcolor=color) color = 'blue' ax3 = ax1.twinx() ax3.spines["right"].set_position(("axes", 1.2)) ax3.set_ylabel('Foliage Health', color=color) ax3.plot(time, df.loc[:, 'E'], color=color) ax3.tick_params(axis='y', labelcolor=color) plt.show()
# CTI-110 # P3HW1 - Age Classifier # 6/19/18 # Connor Naylor #Request age choice="y" while choice=="y": age=float(input("How old are you? ")) #Calculate age classification if age < 0: print("Invalid Number") elif 0<= age <= 1: print("You are an infant.") elif 1 < age < 13: print("You are a child.") elif 13 <= age < 20: print("You are a teenager.") else: print("You are an adult.") choice=input("Would you like to run the program again? Y or N ") print ("Goodbye") #End program
#Write a subroutine that outputs the following properties of a circle from the the diameter and arc angle. D = int(input("What is the diameter? ")) AA =int(input("What is the arc angle? ")) #Subroutine to find the area and circumference of the circle def Properties(X): return (X * 3.14) #Main Programme R = D / 2 A = round(Properties(R ** 2),3) C = round(Properties(D),3) AL = round((C * AA) / 360,3) print("The radius is", R) print("The area is", A) print("The circumference is", C) print("The arc length is", AL)
import random def swap(board, r1, c1, r2, c2): t = board[r1][c1] board[r1][c1] = board[r2][c2] board[r2][c2] = t def vLineAt(board, r, c): location = board[r][c] if r-2 >= 0 and location == board[r-1][c] and location == board[r-2][c]: return True if r-1 >= 0 and r+1<len(board) and location == board[r-1][c] and location == board[r+1][c]: return True if r+2<len(board) and location == board[r+1][c] and location == board[r+2][c]: return True return False def hLineAt(board, r, c): location = board[r][c] if c-2 >= 0 and location == board[r][c-1] and location == board[r][c-2]: return True if c-1 >= 0 and c+1<len(board[r]) and location == board[r][c-1] and location == board[r][c+1]: return True if c+2<len(board[r]) and location == board[r][c+1] and location == board[r][c+2]: return True return False def createBoard(numberOfRows,numberOfColumns,numberOfUniquePieces): board=[] for r in range(numberOfRows): board.append([]) for c in range(numberOfColumns): board[r].append(random.randint(0,numberOfUniquePieces)) return board tabela=createBoard(5,5,5) for elenenti in tabela: for element in elenenti: print(element) print("\n") def clearSymbols(board,symbol): for r in range(len(board)): for c in range (len(board[0])): if board[r][c]==symbol: board[r][c]=-1 def hint(board): r1=0 c1=0 r2=1 c2=0 for r in range(len(board)-1): for c in range(len(board[0])): swap(board, r1, c1, r2, c2) if vLineAt(board,r1,c1)==True or hLineAt(board,r1,c1)==True or vLineAt(board,r1,c2)==True or hLineAt(board,r2,c2)==True: swap(board, r1, c1, r2, c2) return r1,c1,r2,c2 swap(board, r1, c1, r2, c2) c1=c1+1 c2=c2+1 r1=r1+1 r2=r2+1 r1=0 c1=0 r2=0 c2=1 for r in range(len(board)): for c in range(len(board[0])-1): swap(board, r1, c1, r2, c2) if vLineAt(boardr,r1,c1) or hLineAt(board,r1,c1) or vLineAt(board,r2,c2)==True or hLineAt(board,r2,c2)==True: swap(board, r1, c1, r2, c2) return r1,c1,r2,c2 swap(board, r1, c1, r2, c2) c1=c+1 c2=c+1 r1=r+1 r2=r+1 return -1,-1,-1,-1
import os import time infoFile="/home/pi/firebase/userInfo.txt" while True: print('I am gonna reset all your device info. Are you sure?(y/n)') print('or you can press (ctr+c) to exit') ans = input() if(ans == 'y'): print('removing all your device info.....') a = open(infoFile,"r+") a.truncate(0) a.close() time.sleep(2) staff = input("please type your staff's name:") customer = input("please type user's name:") fp = open(infoFile,"a") fp.write(staff + ' ' + customer) fp.close() print('your device info has been updated successfully!') print() print() elif(ans == 'n'): print('okey bye~~') else: print('okey bye~~')
#!/usr/bin/python import sys def add_ranking(): test_filename = sys.argv[1] ranking_filename = sys.argv[2] test_with_ranking_filename = test_filename + ".final_ranking_" + ranking_filename[2:].split("_")[0] print(test_filename) print(ranking_filename) print(test_with_ranking_filename) with open(test_filename) as test_file, open(ranking_filename) as ranking_file, open(test_with_ranking_filename, "w") as test_with_ranking_file: test_lines = test_file.readlines() ranking_lines = ranking_file.readlines() rank_by_line = {} for line in ranking_lines: split = line.split(" ") rank_by_line[split[2].split("=")[1]] = split[3] for i, line in enumerate(test_lines): new_line = rank_by_line[str(i)] + line[2:] test_with_ranking_file.write(new_line) def main(): print("Started adding ranking...") add_ranking() if __name__== "__main__": main()
print("----\n") f = float(input("digite a temperatura em fahrenheit")) c = (f - 32) * 5 / 9 print("a temperatura é de ", c, "graus celcius") print("----\n")
# Ejercicio que define si un estudiante esta aprobado o no #autor: Rose def determinaraprobado(promedio): if promedio >=11: resultado = "aprobado" else: resultado ="desaprobado" return resultado promedio = int(input("promedio valor : ")) print(determinaraprobado(promedio))