text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- """ Created on Thu Aug 31 14:17:37 2017 @author: 00mymy """ import math, random from collections import Counter from linear_algebra import distance, vector_subtract, scalar_multiply def sum_of_squares(v): return sum(v_i**2 for v_i in v) def difference_quotient(f, x, h): return (f(x+h)-f(x)) / h def square(x): return x*x def derivative(x): return 2*x def partial_difference_quotient(f, v, i, h): w = [v_j + (h if j==i else 0) for j, v_j in enumerate(v)] return (f(w)-f(v))/h def estimate_gradient(f, v, h=0.00001): return [partial_difference_quotient(f,v,i,h) for i, _ in enumerate(v)] def step(v, direction, step_size): return [v_i + step_size*direction_i for v_i, direction_i in zip(v, direction)] def sum_of_squares_gradient(v): return [2*v_i for v_i in v] def squared_distance(v, w): """(v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2""" return sum_of_squares(vector_subtract(v, w)) def safe(f): """return a new function that's the same as f, except that it outputs infinity whenever f produces an error""" def safe_f(*args, **kwargs): try: return f(*args, **kwargs) except: return float('inf') # this means "infinity" in Python return safe_f def minimize_batch(target_fn, gradient_fn, theta_0, tolerance=0.000001): """use gradient descent to find theta that minimizes target function""" step_sizes = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001] theta = theta_0 # set theta to initial value target_fn = safe(target_fn) # safe version of target_fn value = target_fn(theta) # value we're minimizing while True: gradient = gradient_fn(theta) next_thetas = [step(theta, gradient, -step_size) for step_size in step_sizes] # choose the one that minimizes the error function next_theta = min(next_thetas, key=target_fn) next_value = target_fn(next_theta) # stop if we're "converging" if abs(value - next_value) < tolerance: return theta else: theta, value = next_theta, next_value def negate(f): """return a function that for any input x returns -f(x)""" return lambda *args, **kwargs: -f(*args, **kwargs) def negate_all(f): """the same when f returns a list of numbers""" return lambda *args, **kwargs: [-y for y in f(*args, **kwargs)] def in_random_order(data): """generator that returns the elements of data in random order""" indexes = [i for i, _ in enumerate(data)] # create a list of indexes random.shuffle(indexes) # shuffle them for i in indexes: # return the data in that order yield data[i] def minimize_stochastic(target_fn, gradient_fn, x, y, theta_0, alpha_0=0.01): data = zip(x, y) theta = theta_0 # initial guess alpha = alpha_0 # initial step size min_theta, min_value = None, float("inf") # the minimum so far iterations_with_no_improvement = 0 # if we ever go 100 iterations with no improvement, stop while iterations_with_no_improvement < 100: value = sum( target_fn(x_i, y_i, theta) for x_i, y_i in data ) if value < min_value: # if we've found a new minimum, remember it # and go back to the original step size min_theta, min_value = theta, value iterations_with_no_improvement = 0 alpha = alpha_0 else: # otherwise we're not improving, so try shrinking the step size iterations_with_no_improvement += 1 alpha *= 0.9 # and take a gradient step for each of the data points for x_i, y_i in in_random_order(data): gradient_i = gradient_fn(x_i, y_i, theta) theta = vector_subtract(theta, scalar_multiply(alpha, gradient_i)) return min_theta def maximize_stochastic(target_fn, gradient_fn, x, y, theta_0, alpha_0=0.01): return minimize_stochastic(negate(target_fn), negate_all(gradient_fn), x, y, theta_0, alpha_0) x = [x/10 for x in range(-100,100)] y = [x**2 - 5*x +6 for x in x] t_fn = lambda x,y,t : (y-(x**2 - 5*x +t))**2 g_fn = lambda x,y,t : 2*(y-(x**2 - 5*x +t)) minimize_stochastic(t_fn, g_fn, x, y, random.random()) ''' #find a local minimum of the function f(x)=x^4−3x^3+2, with derivative f'(x)=4x3−9x2. cur_x = -1 # The algorithm starts at x=6 gamma = 0.01 # step size multiplier precision = 0.00001 previous_step_size = cur_x def df(x): return 4 * x**3 - 9 * x**2 while previous_step_size > precision: prev_x = cur_x cur_x += -gamma * df(prev_x) previous_step_size = abs(cur_x - prev_x) print("The local minimum occurs at %f" % cur_x) ''' ''' derivative_estimate = lambda x: difference_quotient(square, x, h=0.00001) import matplotlib.pyplot as plt x = range(-10, 10) plt.title('Actual Derivative vs. Enstimates') plt.plot(x, list(map(derivative, x)), 'rx', label='Actual') plt.plot(x, list(map(derivative_estimate, x)), 'b+', label='Estimate') plt.legend(loc=9) plt.show() ''' ''' import random v = [random.randint(-10,10) for i in range(3)] tolerance = 0.0000001 while True: gradient = sum_of_squares_gradient(v) next_v = step(v, gradient, -0.01) if distance(next_v, v) < tolerance: break v = next_v print(v) ''' ''' print("using minimize_batch") v = [random.randint(-10,10) for i in range(3)] v = minimize_batch(sum_of_squares, sum_of_squares_gradient, v) print("minimum v", v) print("minimum value", sum_of_squares(v)) '''
def is_palindrome(n): stringnum=str(n) i=0 while i<len(stringnum): if stringnum[i]!=stringnum[len(stringnum)-1-i]: return False i=i+1 return True output = filter(is_palindrome, range(1, 1000)) print(list(output))
L1=[('Lili',75),('Adam',92),('Bart',66),('Lisa',68)] def name(x): i=0 L2=[] while i<len(x): L2.append(L1[i][0]) i=i+1 return L2 output=sorted(L1,key=name) print(output)
from dumbo_syntaxique import Node from dumbo_lexical import variables """ Analyseur semantique """ def getVariable(node): """ :param node: un noeud :return: va chercher la valeur de la variable dans le dictionnaire variable """ if node.p_type == "variable": try: return variables[node.eval()][1] except KeyError as identifier: print("ERROR: variable not defined") exit() else: return node.eval() def evalProgram(node): """ Fonction d'evaluation d'un programme ou d'une expression list :param node: Le noeud a evaluer :return: le resultat de l'evalution du noeud """ l = "" for child in node.children: new_l = child.eval() l += new_l return l def evalAssign(node): """ Fonction d'evaluation d'une assignation :param node: Le noeud a evaluer :return: le resultat de l'evalution du noeud """ # on ajoute la valeur a la variable dans le dictionnaire des variables variables[node.children[0].eval()][1] = node.children[1].eval() return "" def evalFor(node): """ Fonction d'evaluation d'une boucle for :param node: Le noeud a evaluer :return: le resultat de l'evalution du noeud """ l = "" list_value = getVariable(node.children[1]) var_name = node.children[0].eval() var_value = None # si la variable existe deja dans le dictionnaire, on retient sa valeur pour la remettre a la fin if var_name in variables: var_value = variables[var_name][1] for item in list_value: # on actualise la valeur de la variable et on rappelle le sous-arbre variables[var_name][1] = item l += node.children[2].eval() if var_value is None: # la variable etait une variable provisoire, donc on la supprime du dictionnaire variables.pop(var_name) else: # la variable existait deja, donc on lui redonne sa valeur initiale variables[var_name][1] = var_value return l def eval_integer_expression(node): """ Fonction d'evaluation d'une integer expression :param node: Le noeud a evaluer :return: le resultat de l'evalution du noeud """ op = node.p_type a = getVariable(node.children[0]) b = getVariable(node.children[1]) if op == "+": return a + b elif op == "-": return a-b elif op == "*": return a*b elif op == "/": return a/b def eval_boolean_expression(node): """ Fonction d'evaluation d'une boolean expression :param node: Le noeud a evaluer :return: le resultat de l'evalution du noeud """ op = node.p_type.value a = node.children[0].eval() b = node.children[1].eval() if op == "and": return a and b elif op == "or": return a or b def eval_comparator_expression(node): """ Fonction d'evaluation d'une comparator expression :param node: Le noeud a evaluer :return: le resultat de l'evalution du noeud """ op = node.p_type a = node.children[0].eval() b = node.children[1].eval() if op == "<": return a < b elif op == ">": return a > b elif op == "=": return a == b elif op == "!=": return a != b def buildTree(tree): """ Construis l'arbre semantique :param tree: l'arbre syntaxique :return: l'abre semantique """ if tree is None: return None elif tree.p_type == "programme": if len(tree.children) == 1: # le fils est un texte ou un dumboBloc return buildTree(tree.children[0]) elif len(tree.children) == 2: return Node("program", [buildTree(tree.children[0]), buildTree(tree.children[1])], function=evalProgram) elif tree.p_type == "text": # program -> text return Node("text", value=tree.value) elif tree.p_type == "dumbo_bloc": # program -> dumboBlock if len(tree.children) > 0: return buildTree(tree.children[1]) else: return Node("dumbo_bloc") elif tree.p_type == "expression_list": # dumboBloc -> expression list if len(tree.children) == 2: # une seul expression return buildTree(tree.children[0]) elif len(tree.children) == 3: return Node("expression_list", [buildTree(tree.children[0]), buildTree(tree.children[2])], function=evalProgram) elif tree.p_type == "expression": # expressionList -> expression if len(tree.children) == 2: # c'est un print return Node("print", [buildTree(tree.children[1])], function=lambda node: str(getVariable(node.children[0]))) elif len(tree.children) == 3: # c'est une assignation key = buildTree(tree.children[0]) value = buildTree(tree.children[2]) if value.p_type in ['+', '-', '*', '/']: variables[key.value] = ["integer", None] else: variables[key.value] = [value.p_type, None] return Node("assignation", [key, value], function=evalAssign) elif len(tree.children) == 5: # c'est un if return Node("if", [buildTree(tree.children[1]), buildTree(tree.children[3])], function=lambda node: (node.children[1].eval() if node.children[0].eval() else "")) elif len(tree.children) == 7: # c'est un for liste = buildTree(tree.children[3]) if (liste.p_type == "variable" and variables[liste.value][0] == "string_list") or liste.p_type == "string_list": return Node("for", [buildTree(tree.children[1]), liste, buildTree(tree.children[5])], function=evalFor) else: print( "ERREUR SEMANTIQUE: Le type attendu n'est pas correct") return None elif tree.p_type == "string_list": # expression -> string_list return buildTree(tree.children[1]) elif tree.p_type == "string_expression": if len(tree.children) == 1: return buildTree(tree.children[0]) elif len(tree.children) == 3: return Node("concatenation", [buildTree(tree.children[0]), buildTree(tree.children[2])], function=lambda node: getVariable(node.children[0]) + getVariable(node.children[1])) elif tree.p_type == "integer_expression": if len(tree.children) == 1: # juste un entier return buildTree(tree.children[0]) elif len(tree.children) == 3: # une operation return Node(tree.children[1].value, [buildTree(tree.children[0]), buildTree(tree.children[2])], function=eval_integer_expression) elif tree.p_type == "string_list_interior": if len(tree.children) == 1: # un string r = Node("string_list", [buildTree( tree.children[0])], function=lambda node: [node.children[0].eval()]) return r elif len(tree.children) == 3: # liste de string c1 = buildTree(tree.children[0]) c2 = buildTree(tree.children[2]) r2 = Node("string_list", children=[c1, c2], function=lambda node: [ node.children[0].eval()]+node.children[1].eval()) return r2 elif tree.p_type == "boolean_expression": if len(tree.children) == 1: return buildTree(tree.children[0]) elif len(tree.children) == 3: return Node(tree.children[1], [buildTree(tree.children[0]), buildTree(tree.children[2])], function=eval_boolean_expression) elif tree.p_type == "comparator_expression": return Node(tree.children[1].value, [buildTree(tree.children[0]), buildTree(tree.children[2])], function=eval_comparator_expression) elif tree.p_type == "variable": return Node("variable", value=tree.value) elif tree.p_type == "bool": return Node("boolean", value=tree.value) elif tree.p_type == "string": r3 = Node("string", value=tree.value) return r3 elif tree.p_type == "integer": return Node("integer", value=tree.value) else: print("ERREUR: type inconnu ", tree.p_type)
import statistics import string # create matrix for animals #Sharks, rays, amphibians #sharks #rays #amphibians #function determines the lowest element in the matrix def minVal(animal_matrix): minVal = 999 #start minimum with first element for row in range(len(animal_matrix)): for col in range(len(animal_matrix)): if animal_matrix[row][col] != None: if (animal_matrix[row][col] < minVal): minVal = animal_matrix[row][col] return minVal #function that returns leaves for shortest distances def leavesReturn(matrix,short_dist): related_leaves = list() all_leaves = list() breakFlag = False for row in range(len(matrix)): for col in range(len(matrix)): if matrix[row][col] == short_dist: # print(matrix[row][col]) related_leaves.append(row) related_leaves.append(col) all_leaves.append(related_leaves[:]) all_leaves = all_leaves.copy() #make a copy of the list to unlink reference #related_leaves.clear()#clear the list breakFlag = True break if breakFlag == True: break # return all_leaves return related_leaves #find average for each cell def cellAverage(matrix, leaf_group, other_cell): if leaf_group[0] != other_cell and leaf_group[1] != other_cell: # print("Val at that cell", matrix[leaf_group[group][0]][other_cell]) # # print("M0:", matrix[leaf_group[0]][other_cell], "M0:", matrix[other_cell][leaf_group[0]],"\n") # print("M1:", matrix[leaf_group[1]][other_cell], "M1:", matrix[other_cell][leaf_group[1]],"\n") Sum = noneTo0(matrix[leaf_group[0]][other_cell]) + noneTo0(matrix[other_cell][leaf_group[0]])+ \ noneTo0(matrix[leaf_group[1]][other_cell]) + noneTo0(matrix[other_cell][leaf_group[1]]) Sum /= 2 return Sum else: return None def noneTo0(value): if value == None: value = 0 return value else: return value #update the new matrix by putting None where ever needed def updateRow(matrix, leaf_group): row_list = list() #check the leaf_group and the next cells next to it and update new matrix #need to truncate matrix but only do the first row for averages for row in range(len(matrix)): # traverse through the rows get the averages avg = cellAverage(matrix, leaf_group, row) #append to a row list row_list.append(avg) #move all the None type to the left row_list.sort(key=lambda k: k!=None) return row_list # place the new row value where the old one was def makeMatrix(matrix,leaf_group,new_row,row_location): #first delete a row and column from the old matrix new_matrix = delRowCol(matrix,leaf_group) #replace the old row with the new one del new_row[row_location] new_matrix[row_location] = new_row #reupdate the matrix to with None values new_matrix = updateMatrix(new_matrix) return new_matrix # return the matrix with the delete row x col def delRowCol(matrix, leaf_group): #delete the row and column with the highest index value delRow=leaf_group[0] if leaf_group[0]>leaf_group[1] else leaf_group[1] delCol=delRow for row in matrix: #delete the column from that row del row[delCol] del matrix[delRow] #update the matrix and put None where ever neccesary matrix = updateMatrix(matrix) return matrix # return matrix where the same row|col are None # ex. [A][A] == 1 def updateMatrix(matrix): for row in range(len(matrix)): for col in range(len(matrix)): if row == col: matrix[row][col] = None # print(matrix) return matrix # return the row location where to insert the new row def whichRow(leaf_group): row_loc=leaf_group[0] if leaf_group[0]<leaf_group[1] else leaf_group return row_loc # Update dictionary with a key and values for each taxa or leaf def updateDict(dictionary, shortest_dist, leaf_list): tmp_list = [] #check to see if there is the same key in the dictionary if shortest_dist in dictionary: #if there is the same key then we make a nested list tmp_list.append(dictionary.get(shortest_dist)) tmp_list.append(leaf_list) dictionary[shortest_dist] = tmp_list else: #add a new leaf list to the dictionary dictionary[shortest_dist] = leaf_list return dictionary # enumuerate all the values in rows of the matrix to become distinctive letters # and return a list that has those letters to represent different species def letToNum(matrix): letter_list = list() for num_letter in zip(range(len(matrix)), string.ascii_uppercase): letter_list.append(num_letter[1]) return letter_list # check for which rows or specie can become combined as one cluster # return the new list def updateSpeciesList(species_list, matrix, shortest_dist): #create an empty list that will store two elements for clusters cluster = list() isBreak = False # look for the first shorteset distance in the matrix for row in range(len(matrix)): for col in range(len(matrix)): if matrix[row][col] == shortest_dist: #add the row and colum to the list cluster.append(species_list[row]) cluster.append(species_list[col]) #delete the row values in the species list species_list.pop(col) species_list.pop(row) isBreak = True break if isBreak == True: break species_list.insert(row,cluster) return species_list def main(): # matrix = [[None, 9, 2, 4, 9, 10], # [None, None, 9, 6, 2, 10], # [None, None, None, 5, 9, 10], # [None, None, None, None, 6, 10], # [None, None, None, None, None, 10], # [None, None, None, None, None, None]] matrix = [[None, 1, 2, 4, 4, 4, 4], [None, None, 1, 3, 3, 3, 3], [None, None, None, 2, 2, 2, 2], [None, None, None, None, 0, 2, 2], [None, None, None, None, None, 2, 2], [None, None, None, None, None, None, 0], [None, None, None, None, None, None, None]] keepGoing = True leaf_list = [] species_list = [] species_list = letToNum(matrix) while(keepGoing == True): #Step 1. Find the min value. But first check if the shortest_dist = minVal(matrix) #Step 2. find the row x col that has that min value from the matrix leaf_list = leavesReturn(matrix, shortest_dist) #Step 3. Cluster species that have a short distance between them species_list = updateSpeciesList(species_list, matrix, shortest_dist) #Step 4. Calculate the average distance from the row x col (cluser value) # Return the new row to be inserted new_row = updateRow(matrix,leaf_list) #Step 5. determine the locaton of where to place the new row row_loc = whichRow(leaf_list) #Step 6. Put the new row into the matrix and update the old matrix matrix = makeMatrix(matrix,leaf_list,new_row, row_loc) #Step 7. Check if when we only have 2 clusters in the matrix keepGoing = False if len(matrix) <= 2 and len(matrix[0]) <= 2 else True print(species_list) if __name__ == "__main__": main()
#!/usr/bin/env python3 from math import sqrt def get_botright_edges(location): """ Simply returns i as the bottom right value where the location is and a list of squares numbers from 1 to i with a step of 2 """ i = 1 res = [1] while (i * i) < location: i += 2 res.append(i*i) return i, res assert max(get_botright_edges(13)[1]) == 25 def solve(location): """ Since bottom right edges are squares numbers, I find the edges of the square where the location is and then can easily find how many steps from the start. """ if location == 1: return 0 size, edges = get_botright_edges(location) e = [edges[-2] + size - 1, edges[-1] - 2 * size + 2, edges[-1] - size + 1, edges[-1]] center = - (size // 2) for i in range(0, 4): if location <= e[i]: center += e[i] break return (size // 2) + abs(location - center) assert solve(1) == 0 assert solve(12) == 3 assert solve(23) == 2 assert solve(1024) == 31 if __name__ == "__main__": print(solve(277678))
#Hi! Thanks for viewing my code. I hope my coments are clear enough to understand... #Reset ans to 0 for some reason ans = 0 #We introduce the calculator and give information def info(): print "Welcome to my simple calculator!" print "Type 'fin' for your first or second number if you want to stop." print "This calculator does not support decimals, so just use whole numbers. Also, numbers that would end up being a fraction or decimal will appear as 0." print "Use 'ans' for your first or second number to substitute that number as your last answer." print " " #Get started with the numbers num(ans) def num(ans): #Ask and get first number num1 = raw_input("First number: ") #Check if their answer was "fin" and if it is, end the program if num1 == "fin": num2 = "fin" stop() #Check if they say "ans" and if they do set their number as their last answer if num1 == "ans": num1 = ans #Change the text with a number to an acutal number else: num1 = int(num1) #Choose function fun = raw_input("What function? ") #Ask and get first number + fin + ans + fix num num2 = raw_input("Second number: ") if num2 == "fin": stop() if num2 == "ans": num2 = ans else: num2 = int(num2) #Find what function they said and exucate that function with their number if fun == "+" or fun == "plus" or fun == "add": ans = num1 + num2 elif fun == "-" or fun == "minus" or fun == "subtract": ans = num1 - num2 elif fun == "*" or fun == "times" or fun == "multiply": ans = num1 * num2 elif fun == "/" or fun == "divide": ans = num1 / num2 #If something bad happens this will put the user back to the number selection else: print "ERROR" print " " print " " num(ans) #Print the answer and restart print ans print " " print " " num(ans) #If the person said "fin" earlier then we end it here def stop(): print " " print "Thanks for using my calculator!" raw_input(" ") #Finally, we call the information. info()
students=[ {"name": "Sanskriti", "clique": "Nerd"}, {"name": "Samyak", "clique": "Coder"}, {"name": "Preetansh", "clique": "Idiot"} ] #def f(person): # return person["clique"] students.sort(key=lambda person: person["clique"]) print(students)
#Alan ve Hacim Hesaplayıcı - Area and Volume Calculator pi=3.141592 dil=input("Türkçe İçin 1- For English 2") if dil=="1": print("Çeviriciye Hoşgeldin") while(True): print("-"*30) secimilk = input("Alan için 1 Hacim için 2 yi tuşlayınız") if secimilk=="1": secimiki = input("Kare için--------> k\nDikdörtgen için--> dd\nDaire için--------> d\nÜçgen için-------> ü") if secimiki =="k": karekenar=float(input("kenar uzunluğunu girin")) karealan=karekenar*karekenar print("karenin alanı:",karealan) elif secimiki=="dd": dikdörtgenukenar=float(input("bir kenar uzunluğu giriniz")) dikdörtgenkkenar=float(input("ilk yazdığınız kenara dik olan kenarın uzunluğunu giriniz")) dikdörtgenalan=dikdörtgenukenar*dikdörtgenkkenar print("dikdörtgenin alanı:",dikdörtgenalan) elif secimiki=="d": yarıcap=float(input("yarıçapı giriniz")) dairealan=pi*yarıcap*yarıcap print("dairenin alanı:",dairealan) elif secimilk== "2": secimuc= input("Küp için --------->1\nDikdörtgenler Prizması için-->2\nSilindir için----->3\nKoni------->4 için\nKüre için------->5") if secimuc=="1": kupkenar=float(input("bir kenar uzunluğunu giriniz")) kupalan=kupkenar**3 print("Küpün Alanı:",kupalan) elif secimuc=="2": dikdörtgenkenarilk= float(input("Kenarlardan birini girin")) dikdörtgenkenariki= float(input("ilk kenara dik olan kenarlardan birini girin")) dikdörtgenkenaruc= float(input("diğer iki kenara dik olan kenarı girin")) dikdörtgenhacim= dikdörtgenkenarilk*dikdörtgenkenariki*dikdörtgenkenaruc print("dikdörtgenin hacmi:",dikdörtgenhacim) elif secimuc=="3": silindiryarıcap=float(input("silindirin yarıçapını girin")) silindiralan=silindiryarıcap*silindiryarıcap*pi silindiryukseklik=float(input("silindirin yuksekliğini girin")) silindirhacim=silindiralan*silindiryukseklik print("silindirin hacmi:",silindirhacim) elif secimuc=="4": koniyarıcap=float(input("koninin yarıçapını girin")) konialan=koniyarıcap*koniyarıcap*pi koniyukseklik=float(input("koninin yüksekliğini girin")) konihacim=konialan*koniyukseklik/3 print("koninin hacmi:",konihacim) elif secimuc=="5": kureyarıcap=float(input("kürenin yarıçapını girin")) kurehacim=4/3*pi*kureyarıcap**3 print("kurenin hacmi:",kurehacim) elif dil=="2": print("Welcome the Converter") while(True): print("-"*30) secimilk = input("Calculate Area-> 1\nCalculate Volume-> 2 ") if secimilk=="1": secimiki = input("Calculate the Square--------> 1\nCalculate the Rectangle--> 2\nCalculate the Circle--------> 3") if secimiki =="1": karekenar=float(input("Enter the Edge Lenght")) karealan=karekenar*karekenar print("Square Area:",karealan) elif secimiki=="2": dikdörtgenukenar=float(input("Enter a Edge Lenght")) dikdörtgenkkenar=float(input("Enter the Lenght of the Edge Perpendicular to the Edge You Entered First")) dikdörtgenalan=dikdörtgenukenar*dikdörtgenkkenar print("Rectangle Area:",dikdörtgenalan) elif secimiki=="3": yarıcap=float(input("Enter the Radius")) dairealan=pi*yarıcap*yarıcap print("Circle Area:",dairealan) elif secimilk== "2": secimuc= input("Calculate the Cube --------->1\nCalculate the Rectangles Prism-->2\nCalculate the Cylinder----->3\nCalculate the Cone------->4 \nCalculate the Sphere------->5") if secimuc=="1": kupkenar=float(input("Enter the Edge Lenght")) kupalan=kupkenar**3 print("Volume of Cube:",kupalan) elif secimuc=="2": dikdörtgenkenarilk= float(input("Enter a Edge Lenght")) dikdörtgenkenariki= float(input("Enter the Lenght of the Edge Perpendicular to the Edge You Entered First")) dikdörtgenkenaruc= float(input("Enter the Side That is Perpendicular to the Other Two Sides")) dikdörtgenhacim= dikdörtgenkenarilk*dikdörtgenkenariki*dikdörtgenkenaruc print("Volume of Rectangles Prism:",dikdörtgenhacim) elif secimuc=="3": silindiryarıcap=float(input("Enter the Radius of Cylinder")) silindiralan=silindiryarıcap*silindiryarıcap*pi silindiryukseklik=float(input("Enter the Height Cylinder")) silindirhacim=silindiralan*silindiryukseklik print("Volume of Cylinder:",silindirhacim) elif secimuc=="4": koniyarıcap=float(input("Enter the Radius of Cone")) konialan=koniyarıcap*koniyarıcap*pi koniyukseklik=float(input("Enter the Height of Cone")) konihacim=konialan*koniyukseklik/3 print("Volume of Cone:",konihacim) elif secimuc=="5": kureyarıcap=float(input("Enter the Radius of Sphere")) kurehacim=4/3*pi*kureyarıcap**3 print("Volume of Sphere:",kurehacim)
import matplotlib.pyplot as plt import networkx as nx # Define a function wich computes the Closeness Centrality: def closeness(graph): return nx.closeness_centrality(graph) # Define a function wich plots the Closeness Centrality: def plot_closeness(graph): closenessDict = closeness(graph) keyList = [] closenessList = [] for keys in closenessDict.keys(): keyList.append(keys) closenessList.append(closenessDict[keys]) y = closenessList print('Closeness Centrlality histogram:') plt.ylabel('Frequency for each CC value') plt.hist(y) plt.show() # Define a function wich computes the Betweeness Centrality: def betweeness(graph): return nx.betweenness_centrality(graph) # Define a function wich plots the Betweeness Centrality: def plot_betweeness(graph): betweennessDict = betweeness(graph) keyList = [] betweennessList = [] for keys in betweennessDict.keys(): keyList.append(int(keys)) betweennessList.append(betweennessDict[keys]) y = betweennessList print(' Betweeness Centrality histogram:') plt.ylabel('Frequency for each BC value') plt.hist(y) plt.show() # Define a function wich computes the Degree Centrality: def degree(graph): return nx.degree_centrality(graph) # Define a function wich plots the Degree Centrality: def plot_degree(graph): degreeDict = degree(graph) keyList = [] degreeList = [] for keys in degreeDict.keys(): keyList.append(int(keys)) degreeList.append(degreeDict[keys]) y = degreeList print(' Degree Centrality histogram:') plt.ylabel('Frequency for each DC value') plt.hist(y) plt.show()
# Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() fruits = ["Апельсин", "Мандарин", "Нектарин", "Томат"] i = 0 while len(fruits) > i: print("{}.{:>12}".format(i+1, fruits[i])) i += 1 # Задача-2: # Даны два произвольные списка. # Удалите из первого списка элементы, присутствующие во втором списке. firstList = [1, 2 ,3, 4, 5,"собака", "кошка", "ягуар"] secondList = [5, 6, 2, 3, 3.4, "кошка"] for currentElement in firstList: if currentElement in secondList: firstList.pop(currentElement) print("Первый список: ", firstList) print("Второй список: ", secondList) print("Первый список с удалением из него элементов второго списка: ",firstList) # Задача-3: # Дан произвольный список из целых чисел. # Получите НОВЫЙ список из элементов исходного, выполнив следующие условия: # если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два. numbersList = [345, 213, 123, 690, 6843, 4542, 878, 54545, 623, 1231234] newList = [] for element in numbersList: if element % 2 == 0: newList.append(element/4) else: newList.append(element * 2) print("После изменения согласно условиям задания, новый список выглядит следующим образом: ", newList)
''' * * * * * * * * * * * * * * * when n=5 ''' n=int(input('Enter the value of n\n')) for i in range(n,0,-1): for sp in range(0,n-i+1): print(" ",end="") for j in range(0,i): print("*",end=" ") print()
x,y=0,0 increment=10 n=int(input('Enter the number\n')) evenCount=0 oddCount=0 noOfIterations=0 # for i in range(1,n+1): # if i%4==0: # y=y-increment # elif i testvalue=0 for i in range(1,n+1): noOfIterations+=1 if noOfIterations%2==0: evenCount+=1 if evenCount%2==0: y=y-increment else: y=y+increment else: oddCount+=1 if oddCount%2==0: x=x-increment else: x=x+increment increment+=10 if noOfIterations%5==0: noOfIterations=0 oddCount,evenCount=evenCount,oddCount print('Step {}'.format(i)) print('x , y = ({},{})'.format(x, y)) print('x , y = ({},{})'.format(x,y))
''' Given a String of date of format YYYYMMDD, our task is to compute the life path number. Life Path Number is the number obtained by summation of individual digits of each element repeatedly till single digit, of datestring. Used in Numerology Predictions. Examples: Input : test_str = “19970314” Output : 7 Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 3 = 3 [ month ] ; 1 + 4 = 5 [ day ]. 5 + 3 + 8 = 16 ; 1 + 6 = 7. ''' def sumOfDigits(num): sum=0 while(num>0): d=num%10 sum=sum+d num//=10 return sum def lifePath(string): year=int(string[0:4]) month=int(string[4:6]) day=int(string[-2:]) sumOfAll=0 #print(year,month,day) #singleYear=singleMonth=singleDay=0 print('loop in') while(year>10): year=sumOfDigits(year) print('Year is ',year) print('loop 1 out') while (month > 10): month = sumOfDigits(month) print('month is ',month) print('loop 2 out') print(day) while (day > 10): day = sumOfDigits(day) print('Day is ',day) print('loop 3 out') sumOfAll=year+month+day while (sumOfAll > 10): sumOfAll = sumOfDigits(sumOfAll) print('sum is ',sumOfAll) return sumOfAll test_str=input('Enter the String in the format YYYYMMDD\n') print(lifePath(test_str))
''' Given a list, the task is to write a Python program to mark the duplicate occurrence of elements with progressive occurrence number. Input : test_list = [‘gfg’, ‘is’, ‘best’, ‘gfg’, ‘best’, ‘for’, ‘all’, ‘gfg’] Output : [‘gfg1’, ‘is’, ‘best1’, ‘gfg2’, ‘best2’, ‘for’, ‘all’, ‘gfg3’] Explanation : gfg’s all occurrence are marked as it have multiple repetitions(3). Input : test_list = [‘gfg’, ‘is’, ‘best’, ‘best’, ‘for’, ‘all’] Output : [‘gfg’, ‘is’, ‘best1’, ‘best2’, ‘for’, ‘all’] Explanation : best’s all occurrence are marked as it have multiple repetitions(2). ''' def fre(word,list): count=0 for i in list: if i.rstrip('0123456789') == word: count+=1 return count test_list=[] for i in range(0,int(input('Enter the value of n\n'))): if i==0: print('Enter the elements') test_list.append(input()) hashList=[] for i in test_list: f=fre(i,hashList) f+=1 if f>1: hashList.append(i+str(f)) elif f==1 and fre(i,test_list)>1: hashList.append(i + str(f)) else: hashList.append(i) print(hashList)
''' Python program to print all pronic numbers between 1 and 100 The pronic number is a product of two consecutive integers of the form: n(n+1). For example: 6 = 2(2+1)= n(n+1), 72 =8(8+1) = n(n+1) ''' def isPronic(num): import math #num = int(input('Enter the number\n')) n = int(math.sqrt(num)) if n * (n + 1) == num: return True #print('Yes') return False for i in range(1,1001): if isPronic(i): print(i)
def fre(ch,word): count =0 for i in word: if i==ch: count+=1 return count def max(ls): maximum=ls[0] for i in range(1,len(ls)): if maximum<ls[i]: maximum=ls[i] return maximum print(fre('l','lala')) print(max([1,2,3,5,21,1,1,2])) print(fre('',''))
#!/usr/bin/python import sys class Solution: """ @param: nums: an array of Integer @param: target: target = nums[index1] + nums[index2] @return: [index1 + 1, index2 + 1] (index1 < index2) """ def twoSum(self, nums, target): # write your code here i = 0 j = len(nums) - 1 while i < j: if nums[i]+nums[j] > target: j -= 1 elif nums[i]+nums[j] < target: i += 1 else: return [i+1, j+1] return [] def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTilt(self, root): """ :type root: TreeNode :rtype: int """ self.result = 0 self.dfs(root) return self.result def dfs(self, node): if not node: return 0 left = self.dfs(node.left) right = self.dfs(node.right) self.result += abs(right - left) return left + right + node.val def main(): aa = Solution() print aa.findTilt() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def findRadius(self, houses, heaters): """ :type houses: List[int] :type heaters: List[int] :rtype: int """ houses.sort() heaters.sort() heaters = [float('-inf')] + heaters + [float('inf')] ans, i = 0, 0 for house in houses: while house > heaters[i+1]: i += 1 dis = min(house-heaters[i], heaters[i+1]-house) ans = max(dis, ans) return ans def main(): aa = Solution() print aa.findRadius() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param: head: The head of linked list. @return: You should return the head of the sorted linked list, using constant space complexity. """ def sortList(self, head): # write your code here if head is None or head.next is None: return head slow = head fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next mid = slow.next slow.next = None list1 = self.sortList(mid) list2 = self.sortList(head) return self.merge(list1, list2) def merge(self, l1, l2): if not l1: return l2 if not l2: return l1 head = None if l1.val < l2.val: head = l1 l1 = l1.next else: head = l2 l2 = l2.next p = head while l1 and l2: if l1.val < l2.val: p.next = l1 l1 = l1.next else: p.next = l2 l2 = l2.next p = p.next if l1: p.next = l1 if l2: p.next = l2 return head def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param hashTable: A list of The first node of linked list @return: A list of The first node of linked list which have twice size """ def rehashing(self, hashTable): # write your code here new_len = len(hashTable)*2 new_hash = [None for _ in range(new_len)] for item in hashTable: p = item while p: pos = p.val % new_len if new_hash[pos]: cur = new_hash[pos] while cur.next: cur = cur.next cur.next = ListNode(p.val) else: new_hash[pos] = ListNode(p.val) p = p.next return new_hash def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys import heapq class MaxStack(object): def __init__(self): """ Space O N initialize your data structure here. """ self.stack = [] def push(self, x): """ O 1 :type x: int :rtype: void """ m = max(self.stack[-1][1] if self.stack else -float('inf'), x) self.stack.append((x, m)) def pop(self): """ O 1 :rtype: int """ return self.stack.pop()[0] def top(self): """ O 1 :rtype: int """ return self.stack[-1][0] def peekMax(self): """ O 1 :rtype: int """ return self.stack[-1][1] def popMax(self): """ O N :rtype: int """ tmp = [] m = self.stack[-1][1] while self.stack[-1][0] != m: tmp.append(self.pop()) self.pop() map(self.push, reversed(tmp)) return m # Your MaxStack object will be instantiated and called as such: # obj = MaxStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.peekMax() # param_5 = obj.popMax() class MaxStack1(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.maxHeap = [] self.toPop_heap = {} # to keep track of things to remove from the heap self.toPop_stack = set() # to keep track of things to remove from the stack def push(self, x): """ :type x: int :rtype: void """ heapq.heappush(self.maxHeap, (-x, -len(self.stack))) self.stack.append(x) def pop(self): """ :rtype: int """ self.top() x = self.stack.pop() key = (-x, -len(self.stack)) self.toPop_heap[key] = self.toPop_heap.get(key, 0) + 1 return x def top(self): """ :rtype: int """ while self.stack and len(self.stack) - 1 in self.toPop_stack: x = self.stack.pop() self.toPop_stack.remove(len(self.stack)) return self.stack[-1] def peekMax(self): """ :rtype: int """ while self.maxHeap and self.toPop_heap.get(self.maxHeap[0], 0): x = heapq.heappop(self.maxHeap) self.toPop_heap[x] -= 1 return -self.maxHeap[0][0] def popMax(self): """ :rtype: int """ self.peekMax() x, idx = heapq.heappop(self.maxHeap) x, idx = -x, -idx self.toPop_stack.add(idx) return x class MaxStack2(list): def push(self, x): m = max(x, self[-1][1] if self else None) self.append((x, m)) def pop(self): return list.pop(self)[0] def top(self): return self[-1][0] def peekMax(self): return self[-1][1] def popMax(self): m = self[-1][1] b = [] while self[-1][0] != m: b.append(self.pop()) self.pop() map(self.push, reversed(b)) return m def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution: """ @param: matrix: A list of lists of integers @param: target: An integer you want to search in matrix @return: An integer indicate the total occurrence of target in the given matrix """ def searchMatrix(self, matrix, target): # write your code here if not matrix or not matrix[0]: return 0 y = 0 x = len(matrix[0])-1 count = 0 while x >= 0 and y < len(matrix): if matrix[y][x] == target: count += 1 y += 1 x -= 1 elif matrix[y][x] < target: y += 1 else: x -= 1 return count def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution: """ @param: n: An integer @return: the nth prime number as description. """ def nthUglyNumber(self, n): # write your code here ugly = [1] i2, i3, i5 = 0, 0, 0 while n > 1: u2, u3, u5 = ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5 u = min(u2, u3, u5) if u == u2: i2 += 1 if u == u3: i3 += 1 if u == u5: i5 += 1 ugly.append(u) n -= 1 return ugly[-1] def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def nextGreaterElements(self, nums): """ :type nums: List[int] :rtype: List[int] """ result = [-1] * len(nums) stack = [] for i in range(len(nums)) * 2: while stack and nums[i] > nums[stack[-1]]: result[stack.pop()] = nums[i] stack.append(i) return result def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def frequencySort(self, s): """ :type s: str :rtype: str """ result = "" d = dict() for c in s: d[c] = d.get(c, 0) + 1 a = [[] for _ in range(len(s) + 1)] for k in d.keys(): a[d[k]].append(k) for i in range(len(a) - 1, -1, -1): for c in a[i]: result += i * c return result class Solution1(object): def frequencySort(self, s): """ :type s: str :rtype: str """ result = "" d = {} for i in s: d[i] = d.get(i, 0) + 1 a = [[] for _ in range(len(s)+1)] for k in d: a[d[k]].append(k) for i in range(len(a)-1, -1, -1): result += ''.join([i*n for n in a[i]]) return result def main(): aa = Solution() print aa.frequencySort() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def checkRecord(self, s): """ :type s: str :rtype: bool """ a = 0 l = 0 c = 0 for i in s: if i == 'A': a += 1 c = 0 elif i == 'L': l += 1 c += 1 if c > 2: return False else: c = 0 if a <= 1: return True return False def main(): aa = Solution() print aa.checkRecord() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution: # @param {int} n an integer # @param {int[][]} edges a list of undirected edges # @return {boolean} true if it's a valid tree, or false def validTree(self, n, edges): if len(edges) != n - 1: return False neighbors = {i: [] for i in range(n)} for v, w in edges: neighbors[v] += w, neighbors[w] += v, stack = [0] while stack: print stack stack += neighbors.pop(stack.pop(), []) return not neighbors class Solution1(object): def validTree(self, n, edges): """ (BFS) :type n: int :type edges: List[List[int]] :rtype: bool """ d = {i: set() for i in range(n)} for v, w in edges: d[v].add(w) d[w].add(v) root = [d.keys()[0]] visited = set() while root: node = root.pop(0) if node in visited: return False else: visited.add(node) for k in d[node]: root.append(k) d[k].remove(node) del d[node] return not d def main(): aa = Solution() print aa.validTree(5, [[0,1],[0,2],[1,3],[3,2]]) # print aa.validTree(4, [['a', 'b'], ['a', 'c'], ['b', 'd']]) return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution: """ @param: reader: An instance of ArrayReader. @param: target: An integer @return: An integer which is the first index of target. """ def searchBigSortedArray(self, reader, target): # write your code here index = 0 while reader.get(index) < target: index = index * 2 + 1 first = 0 last = index while first + 1 < last: m = (first+last)/2 if reader.get(m) < target: first = m elif reader.get(m) > target: last = m else: last = m if reader.get(first) == target: return first if reader.get(last) == target: return last return -1 def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if inorder: idx = inorder.index(postorder.pop()) node = TreeNode(inorder[idx]) node.right = self.buildTree(inorder[idx+1:], postorder) node.left = self.buildTree(inorder[:idx], postorder) return node def main(): aa = Solution() print aa.buildTree() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def isStrobogrammatic(self, num): """ :type num: str :rtype: bool """ d = {'6': '9', '9': '6', '1': '1', '8': '8', '0': '0'} if set(num) - set(d.keys()): return False new = [] for n in num: new.append(d[n]) return num == ''.join(new[::-1]) def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys import random class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type numsSize: int """ self.nums = nums def pick(self, target): """ :type target: int :rtype: int """ n = 0 result = -1 for i in range(len(self.nums)): if self.nums[i] == target: r = random.randint(0, n) n += 1 if r == 0: result = i return result # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.pick(target) def main(): aa = Solution() print aa.pick() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDiffInBST(self, root): """ :type root: TreeNode :rtype: int """ self.result = float('inf') self.inorder = [] self.dfs(root) if len(self.inorder) == 1: return 0 for i in range(1, len(self.inorder)): self.result = min(self.inorder[i] - self.inorder[i - 1], self.result) return self.result def dfs(self, node): if not node: return self.dfs(node.left) self.inorder.append(node.val) self.dfs(node.right) def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys """ Definition of TreeNode: class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None """ class Solution: """ @param: root: the root of binary tree @return: the root of the maximum average of subtree """ def findSubtree2(self, root): self.average = 0 self.node = None self.dfs(root) return self.node def dfs(self, node): if node is None: return 0, 0 left_sum, left_size = self.dfs(node.left) right_sum, right_size = self.dfs(node.right) sum = left_sum + right_sum + node.val size = left_size + right_size + 1 if self.node is None or sum * 1.0 / size > self.average: self.node = node self.average = sum * 1.0 / size return sum, size def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findMode(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] self.d = {} self.dfs(root) m = max(self.d.values()) return [i for i, v in self.d.items() if v == m] def dfs(self, node): if not node: return self.d[node.val] = self.d.get(node.val, 0) + 1 self.dfs(node.left) self.dfs(node.right) return def main(): aa = Solution() print aa.findMode() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution: """ @param: source: source string to be scanned. @param: target: target string containing the sequence of characters to match @return: a index to the first occurrence of target in source, or -1 if target is not part of source. """ def strStr(self, source, target): if source is None or target is None: return -1 for i in range(len(source)-len(target)+1): if source[i: i+len(target)] == target: return i return -1 # write your code here def main(): aa = Solution() print aa.strStr("","") print aa.strStr(" ", " ") print aa.strStr("asdfasdf", "eee") print aa.strStr("asdfsadgfasdf", "dg") print aa.strStr("addssee", "s") print aa.strStr("abcdabcdefg", "bcd") return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def upsideDownBinaryTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ curr = root pre = None nex = None tmp = None while curr: nex = curr.left curr.left = tmp tmp = curr.right curr.right = pre pre = curr curr = nex return pre def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ def post_order(node): if node is None: return '$' l = post_order(node.left) r = post_order(node.right) return l + r + str(node.val) + '^' return post_order(t) in post_order(s) def main(): aa = Solution() print aa.isSubtree() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ self.l = L self.r = R return self.trim(root) def trim(self, node): if not node: return if node.val > self.r: return self.trim(node.left) elif node.val < self.l: return self.trim(node.right) else: node.left = self.trim(node.left) node.right = self.trim(node.right) return node def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution: """ @param: s: A string @return: Whether the string is a valid palindrome """ def isPalindrome(self, s): # write your code here i = 0 j = len(s)-1 while i<j: if not s[i].isalnum(): i += 1 continue if not s[j].isalnum(): j -= 1 continue if s[i].lower() == s[j].lower(): i += 1 j -= 1 else: return False return True def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def floodFill(self, image, sr, sc, newColor): """ :type image: List[List[int]] :type sr: int :type sc: int :type newColor: int :rtype: List[List[int]] """ # BFS if image[sr][sc] == newColor: return image dx = (0, 1, 0, -1) dy = (1, 0, -1, 0) q = [(sr, sc)] o = image[sr][sc] while q: x, y = q.pop() image[x][y] = newColor for i in range(4): nx = x + dx[i] ny = y + dy[i] if nx < 0 or ny < 0 or nx >= len(image) or ny >= len(image[0]): continue if image[nx][ny] == o: q.append((nx, ny)) return image def floodFill1(self, image, sr, sc, newColor): """ :type image: List[List[int]] :type sr: int :type sc: int :type newColor: int :rtype: List[List[int]] """ # Recursive DFS if image[sr][sc] == newColor: return image o = image[sr][sc] self.nc = newColor self.dfs(image, sr, sc, o) return image def dfs(self, image, i, j, o): if i < 0 or j < 0 or i >= len(image) or j >= len(image[0]): return if image[i][j] == o: image[i][j] = self.nc self.dfs(image, i - 1, j, o) self.dfs(image, i, j - 1, o) self.dfs(image, i + 1, j, o) self.dfs(image, i, j + 1, o) def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ self.visited = set() result = 0 for n in range(len(M)): if n not in self.visited: self.dfs(M, n) result += 1 return result def dfs(self, M, node): for idx, v in enumerate(M[node]): if v and idx not in self.visited: self.visited.add(idx) self.dfs(M, idx) def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def convertBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ self.vals = [] self.s = 0 self.dfs1(root) self.dfs2(root) return root def dfs1(self, node): if node: self.dfs1(node.left) self.vals.append(node.val) self.dfs1(node.right) def dfs2(self, node): if node: self.dfs2(node.right) self.s += self.vals.pop() node.val = self.s self.dfs2(node.left) # traverse 1: inorder -> list from small to big # traverse 2: reverse inorder , gen the new tree def main(): aa = Solution() print aa.convertBST() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or not matrix[0]: return False j = -1 for r in matrix: while j + len(r) and r[j] > target: j -= 1 if r[j] == target: return True return False def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def pivotIndex(self, nums): """ :type nums: List[int] :rtype: int """ s = sum(nums) leftsum = 0 for i, n in enumerate(nums): if leftsum == (s - leftsum - n): return i leftsum += n return -1 def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) l = nums[0] f = nums[n - 1] li = -2 fi = -1 for i in range(len(nums)): l = max(nums[i], l) f = min(nums[n - i - 1], f) if l > nums[i]: li = i if f < nums[n - i - 1]: fi = n - i - 1 return li - fi + 1 def main(): aa = Solution() print aa.findUnsortedSubarray() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ if set([a, b]) == set([2147483647, -2147483648]): return -1 if a < 0 or b < 0: if a < 0: b, a = abs(a), b if b < 0: b = abs(b) return self.minus(a, b) elif a < 0 and b < 0: return self.allMinus(abs(a), abs(b)) else: return self.add(a, b) def add(self, a, b): while b != 0: c = a & b a = a ^ b b = c << 1 return a def minus(self, a, b): while b != 0: c = (~a) & b a = a ^ b b = c << 1 return a def allMinus(self, a, b): return ~(self.add(a, b)) def main(): aa = Solution() print aa.getSum(1, 2) return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Recursive dfs class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.result = [] self.dfs(nums, []) return self.result def dfs(self, nums, ss): if len(ss) == len(nums): self.result.append(ss[:]) return for n in set(nums) - set(ss): ss.append(n) self.dfs(nums, ss) ss.pop() # Iterate dfs class Solution2(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] stack = [[i] for i in nums] while stack: last = stack.pop() if len(last) == len(nums): result.append(last) continue for n in nums: if n not in last: candidate = last + [n] if len(candidate) == len(nums): result.append(candidate) else: stack.append(candidate) return result def main(): aa = Solution() print aa.permute() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution(object): def findDuplicate(self, paths): """ :type paths: List[str] :rtype: List[List[str]] """ d = {} for p in paths: path = p.split(" ")[0] files = p.split(" ")[1:] for f in files: con = f[f.index("(") + 1:f.rindex(")")] name = f[:f.index("(")] d[con] = d.get(con, []) + [os.path.join(path, name)] return [i for i in d.values() if len(i) != 1] def main(): aa = Solution() print aa.findDuplicate() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ s = f = head while f and f.next: f = f.next.next s = s.next n = None while s: t = s.next s.next = n n = s s = t while head and n: if n.val != head.val: return False n = n.next head = head.next return True def main(): aa = Solution() print aa.isPalindrome() return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution: """ @param: nums: A list of integers. @return: A list of permutations. """ def permute(self, nums): # write your code here self.result = [] self.dfs(nums, []) return self.result def dfs(self, nums, ss): if len(ss) == len(nums): self.result.append(ss[:]) return for n in set(nums)-set(ss): ss.append(n) self.dfs(nums, ss) ss.pop() class Solution2(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [[]] result = [] stack = [[i] for i in nums] while stack: last = stack.pop() if len(last) == len(nums): result.append(last) continue for n in nums: if n not in last: stack.append(last + [n]) return result def main(): aa = Solution() print aa.permute([1,2,3]) aa = Solution2() print aa.permute([1, 2, 3]) return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import sys class Solution: """ @param: s: a string @param: dict: a set of n substrings @return: the minimum length """ def minLength(self, s, dict): # write your code here if not s: return 0 result = len(s) h = {s} q = [s] while q: cur = q.pop(0) for k in dict: idx = cur.find(k) while idx != -1: new_s = cur[:idx] + cur[idx+len(k):] if new_s not in h: result = min(result, len(new_s)) h.add(new_s) q.append(new_s) idx = cur.find(k, idx+1) return result def main(): aa = Solution() return 0 if __name__ == "__main__": sys.exit(main())
import math def longest_side(a, b): """ Founction to find the length of the longest side of a right triangle. :arg a : Side a of the triangle :arg b: Side b of the triangle :return Length of the longest side c as float """ return math.sqrt(a*a + b*b) if _name_ == '_main_': print(longest_side._doc_) print(longest_side(4,5))
''' Created on 10 mar. 2021 @author: Ivi ''' num1 = int(input("Dame el numero entero inicial:")) num2 = int(input("Dime cuantos valores quieres:")) i = 0 lista = [] if num2 >= 0: while num2 > i: lista.append(num1) num1=num1+1 i=i+1 if lista.__len__()>0: print(lista) else: print("La cantidad de valores no puede ser negativa!")
# Rock, Paper, Scissors game. # Import modules import sys import random import time # Scores wins = 0 loses = 0 ties = 0 # Strikes strikes = 0 balls = 0 fouls = 0 # Agreements yes = ('y', 'yes') no = ('n', 'no') # Are we # playing? def Play(): global wins global loses global ties # What are our options? options = ('rock', 'paper', 'scissors') playing = 'y' while playing in yes: # Users and their choices human = input('Choose between \'rock\', \'paper\' or \'scissors\': ').lower() computer = random.choice(options) # Wrong choice? while human not in options: print('\nYo! That\'s not a word I asked for.') Strike() human = input('Choose between \'rock\', \'paper\' or \'scissors\': ').lower() # Say 'ROCK, PAPER SCISSORS!' for n in options: print('\n', n.upper(), '!', sep='') time.sleep(.3) # Print users choices print('\nYou picked:', human.upper()) print('Computer picked:', computer.upper()) # Testing results: # Same choice? if human == computer: print('\nIt is a tie!') ties += 1 # Human loses? elif (human == options[0] and computer == options[1]) or (human == options[1] and computer == options[2]) or ( human == options[2] and computer == options[0]): print('\nYou lose!') loses += 1 # Human wins?! elif (human == options[0] and computer == options[2]) or (human == options[1] and computer == options[0]) or ( human == options[2] and computer == options[1]): print('\nYou win!') wins += 1 # Prints Total Results print('\nTotal wins:', wins) print('Total loses:', loses) print('Total ties:', ties, '\n') PlayAgain() # Whas is PlayAgain()? def PlayAgain(): global yes global no # Play again? playing = input('Would you like to play again?(y/n): ') # YAY! :D while playing in yes: print() Play() # NAY! :( if playing in no: print('\nThanks for playing!') sys.exit() # Lol, WAT? else: Strike() # What is Strike()? def Strike(): global strikes # This is a strike strikes += 1 while strikes <= 3: # Indeed it is... print('\nThat\'s strike', strikes, '\n') # Strike 3! if strikes == 3: print(strikes, 'strikes! YOU\'RE OUT!') sys.exit() PlayAgain() print() # Can we FINALLY play? Play()
__author__ = 'danbox' from time import time import math import random ''' FORMATTING CONVENTION The convention for formatting a list of points in this program is to use a list of lists of pairs of floating-point values. The first element in each pair is the x coordinate of a point and the second is its y coordinate. There must be at least two points in a list. Example: [[3.2,5,8],[4.7,1.2]] ''' ''' Read a set of points from a file. Prconditions: The file consists of two floating-point values per line, where the first gives the x coordinate of a point and the second gives its y coordinate. Postconditions: the returned list is a list of the points, adhering to the formatting convention (above) ''' def readPts(filename): return [] ''' Merge of mergesort, for sorted lists of points. Preconditions: S1 and S2 are two lists of lists of size two, adhering to the formatting convention (above). In addition, coord is either 0 or 1. If it is 0, then the two lists must be sorted by x coordinate and if it is 1, they must be sorted by y coordinate. Postconditions: The returned list is the union of the two lists. If coord == 0, it is sorted by x coordinate and if coord == 1, it is sorted by y coordinate. ''' def mergePts(S1, S2, coord): return [] ''' Mergesort for a list of points. preconditions: S is a set of points adhering to the formatting convention (above), and coord is 0 or 1 postconditions: if coord == 0, the returned list is the elements of S sorted by x coordinate, and if coord == 1, the returned list is the elements of S sorted by y coordinate. ''' def msPts(S, coord): return [] ''' preconditions: S is a set of points in two-space. The two returned values are the square of the distance between the closest pair of points, and a list of two points adhering to the formatting convention (above), giving the closest pair. This is needed in the closest-pair algorithm for the base case where the number of points is two or three. (Using this as the base case prevents us from having to consider what answer to return if there is only one point in the list). ''' def brute(S): best = distsq(S[0], S[1]) bestPair = [S[0], S[1]] for i in range(len(S)): for j in range(i+1, len(S)): candidate = distsq(S[i], S[j]) if candidate < best: best = candidate bestPair = [S[i], S[j]] return best, bestPair ''' Find the closest pair in S Precondition: S conforms to the formatting convention, and no two points have the same x coordinate Postcondition: A tuple has been returned whose first element is the distance squared, and whose second element is a list of two points. This should generate two sorted lists and call closestAux ''' def closest(S): return 0.0, [[0.0,0.0], [0.0,0.0]] ''' preconditions: X and Y are the same set of points in two-space, no two of which share the same x coordinate. X is sorted by X coordinate Y is sorted by Y coordinate postconditions: the returned tuple are the square of the distance of the closest pair and a list of size two giving the closest pair ''' def closestAux(X, Y): return 0.0, [[0.0,0.0],[0.0,0.0]] ''' Find the square of the distance between two points. Preconditions: p1 and p2 are lists of size two floating-point values, where the first element in each list is the x coordinate and the second is the y coordinate. Postcondition: the square of the distance between the two points has been returned ''' def distsq(p1, p2): return 0.0 '''One way to test out the correctness and efficiency of your code is to uncomment some of the following: ''' ''' ************************************* ''' ''' S = readPts('points.txt')''' ''' size = int(input("Enter number of points: ")) print size S = [[random.random(), random.random()] for i in range(size)] start=time(); Soln = closest(S) end = time(); print '\n Solution for closest: ', Soln print '\n Elapsed for closest: ', end - start start = time() Soln = brute(S) end = time() print '\nSolution for brute-force: ', Soln print '\n Elapsed for brute-force: ', end - start '''
#QUESTION-1 try: a=3 if a<4: a=a/(a-3) print(a) except ZeroDivisionError: print("no. !/0") #QUESTION-2 try: l=[1,2,3] print(l[3]) except IndexError: print("list out of index.") #QUESTION-3 #Output will be {An exception} as "hi there" will not be found. #QUESTION-4 #smjh nhi aaya #QUESTION-5 #IMPORT ERROR try: import date except ImportError: print("import error") #INDEX ERROR try: l=[1,2,3] print(l[3]) except IndexError: print("Index error") #VALUE ERROR try: n=input("enter the integer:- ") n=int(n) except ValueError: print("value error") else: print("value is inserted.")
#QUESTION-1 list1=[int(input("Enter the number:- ")) for i in range(10)] for i in list1: print(i) #QUESTION-2 while(True): print("infinite loop") #QUESTION-3 number=int(input("Enter the number of elements:- ")) list2=[int(input("Enter number:- ")) for i in range(number)] list3=[i**2 for i in list2] print(list3) #QUESTION-4 list4=[1,'jon',11.45235,'snow',87,24,24.324] slist=[] flist=[] ilist=[] for i in list4: if(type(i)==float): flist.append(i) elif(type(i)==int): ilist.append(i) elif(type(i)==str): slist.append(i) print(slist) print(flist) print(ilist) #QUESTION-5 list5=[int(i) for i in range(1,101)] list6=[] for i in list5: for j in range(2,i): if(i%j==0): break else: if(i!=1): list6.append(i) print("all prime numbers:- ",list6) #QUESTION-6 for i in range(4): for j in range(i+1): print("*",end='') print() #QUESTION-7 list7=[int(input("Enter the no.:- ")) for i in range(int(input("Enter the no. of elements:- ")))] number=int(input("Enter the no. for search and delete:- ")) for i in list7: if(number in list7): list7.remove(number) print("no. deleted") print("last list",list7) break else: print("no. not available")
def DDAL(x1, y1, x2, y2, color1, color2): dx = abs(x2 - x1) dy = abs(y2 - y1) steps = 0 if (dx) > (dy): steps = (dx) else: steps = (dy) xInc = float(dx / steps) yInc = float(dy / steps) xInc = round(xInc,1) yInc = round(yInc,1) for i in range(0, int(steps + 1)): plt.plot(round(x1),round(y1), color2) x1 += xInc y1 += yInc resultado.set("Resultado:"+str(x1)) resultado.set(str(y1)) #print(x1) #print(y1) plt.show()
import random from itertools import combinations question_format = """ - {id}) {question}""" def random_get_answer(answers, memory=None): if memory is None: memory = [] while True: answer = random.choice(answers) if answer not in memory: memory.append(answer) return answer def generate_combinations(dimensions): """ Generate a list of two element items which each is a tuple of (dimenstion_name, answer) e.g: [[('Adaptive', 'I am a curious person'), ('Integrity', 'I am fair')], ...] :return: """ questions = [] memory = [] for comb in combinations(range(len(dimensions)), 2): first_dimension_index, second_dimension_index = comb first_d = dimensions[first_dimension_index] second_d = dimensions[second_dimension_index] for i in range(2): a_1 = random_get_answer(first_d['answers'], memory) a_2 = random_get_answer(second_d['answers'], memory) questions.append([(first_d['name'], a_1), (second_d['name'], a_2)]) random.shuffle(questions) return questions
def class animal(self, ) print ("Hello world") a = 22 while a != 23: a = int(input("Enter integer:")) print(a) print(type(a)) else: print(f"You got it, the number is {a}") print("End")
def ordinalFunc(x): if not isinstance(x, int): return "Input must be integer" x_string = str(x) last_digit = x_string[-1] last_2_digits = x_string[-2:] last_digit = int(last_digit) last_2_digits = int(last_2_digits) if last_2_digits in range(11,16): return "%sth" % x else: if last_digit == 1: return "%sst" % x if last_digit == 2: return "%snd" % x if last_digit == 3: return "%srd" % x if last_digit == 4 or last_digit == 0: return "%sth" % x
#Task1 #def CounttoN(num): num = abs(num) #num will be assigned the absoulute value of it self #for i in range(1,num+1): # print i n = raw_input("enter an interger:\n") n = int(n) #alternative # i = 1 # while i <=num: # print i # list(): #while(): CounttoN(n) #factors returns a list of all intergers def Factors(num2): num2 = abs (num2) l = []#list() for i in range (1,num2+1): if num % i == 0: l.append (i) return l print Factors(n)
# File: src/python/basic_mathematical_operations.py # First, let's import the 'math' library import math # Declare some variables so we have data to play around with str1 = "I am string #1" str2 = "I am string #2" int1 = 12 int2 = 58 float1 = 100.2 float2 = 56.3 # Addition ================================================== add1 = int1 + int2 add2 = float1 + float2 add3 = int1 + int2 + float1 + float2 add4 = add1 + add2 print "ADDITION:" print int1, "+", int2, "=", add1 print float1, "+", float2, "=", add2 print "All numbers added together:", add3 print "Same Result:", add4 # Subtraction =============================================== sub1 = int1 - int2 sub2 = int2 - int1 sub3 = float1 - float2 sub4 = int1 - int2 - float1 - float2 print "\nSUBTRACTION:" print int1, "-", int2, "=", sub1 print int2, "-", int1, "=", sub2 print float1, "-", float2, "=", sub3 print "All subtracted:", sub4 # Multiplication ============================================ mul1 = int1 * int2 mul2 = float1 * float2 mul3 = int1 * int2 * float1 * float2 print "\nMULTIPLICATION:" print int1, "x", int2, "=", mul1 print float1, "x", float2, "=", mul2 print "All multiplied:", mul3 # Division ================================================== div1 = int1 / int2 #gotcha! div1f1 = float(int1) / int2 div1f2 = 1.0 * int1 / int2 div2 = float1 / float2 # Note on the gotcha: # A math operation between two integers will never produce a float unless # you cast one of the integers to a float before the operation. This can # be done either by multiplying by 1.0 or using the float() function to cast # as a float. print "\nDIVISION:" print int1, "/", int2, "=", div1, "- Watch out for this!" print float(int1), "/", int2, "=", div1f1, "- Correct!" print 1.0 * int1, "/", int2, "=", div1f2, "- Correct!" print float1, "/", float2, "=", div2, "- Both were floats, correct!" # Powers ==================================================== pow1 = int1 ** int2 pow2 = float1 ** float2 print "\nPOWERS:" print int1, "^", int2, "=", pow1 print float1, "^", float2, "=", pow2 # Sin, Cos, Tan ============================================= # math.pi is pi, stored as a constant in the math library sin1 = math.sin(math.pi) cos1 = math.cos(math.pi) tan1 = math.tan(math.pi) # there are similar functions for arcsin, arccos, and arctan, see the python # documentation for more details (http://docs.python.org/library/math.html) print "\nSIN, COS, TAN" print "Sin(pi) =", sin1, "- basically zero" print "Cos(pi) =", cos1 print "Tan(pi) =", tan1, "- basically zero" # Logs ======================================================= ex = math.exp(4) log1 = math.log(4) log2 = math.log(4, 10) log3 = math.log(4, 3) print "\nLOGARITHMS" print "e^4 =", ex print "log_e(4) =", log1 print "log_10(4) =", log2 print "log_3(4) = ", log3 # String Concatenation ======================================= con1 = str1 + str2 con2 = str1 * 4 print "\nSTRING CONCATENATION" print str1, "+", str2, "=", con1 print str1, "x 4 =", con2
# File: src/python/basic_control.py # Demonstrates the use of if/elif/else statements. # The following line is unrelated to control statements num = int(raw_input("Input Number:")) if num > 0: print num, "is positive" elif num < 0: print num, "is negative" else: print num, "is zero"
# File: src/python/physics_numerical_euler.py # Simulates an object being launched at a particular angle given an initial velocity using the forward Euler method. import math ANGLE = 30.0 #degrees V0 = 112.0 #initial velocity, m/s DT = 0.01 G = -9.8 #gravity, m/s H_DAMP = 0.0 #wind, m/s t = 0.0 #time (seconds) x = 0.0 #x-position (m) y = 0.0 #y-position (m) vx = V0 * math.sin(math.radians(ANGLE)) vy = V0 * math.sin(math.radians(ANGLE)) # Calculate the x and y components of velocity def vel(v_x, v_y, a_x, a_y, dt): v_x_new = v_x + (a_x * dt) v_y_new = v_y + (a_y * dt) return (v_x_new, v_y_new) # Calculate the x and y components of position def pos(pos_x, pos_y, v_x, v_y, dt): x_new = pos_x + (v_x * dt) y_new = pos_y + (v_y * dt) return (x_new, y_new) outfile = open("euler.txt", "w") while True: x, y = pos(x, y, vx, vy, DT) vx, vy = vel(vx, vy, H_DAMP, G, DT) t += DT if y <= 0: break outfile.write("%s %s %s %s %s\n" % (t, x, y, vx, vy)) outfile.close()
# File: src/python/basic_arrays_multinumpy.py # Demonstrates the use of the NumPy array library to make multidimentional arrays # Import the NumPy library import numpy # Declare a 2D array arr2D = numpy.array([ [00,01,02,03], [10,11,12,13], [20,21,22,23], [30,31,32,33] ]) # Access an element item = arr2D[1][1] print "Item (2,2):", item # Change an items value arr2D[1][1] = 14 item = arr2D[1][1] print "Item (2,2) is now:", item
# Copyright 2008-2020 pydicom authors. See LICENSE file for details. """Code for multi-value data elements values, or any list of items that must all be the same type. """ from typing import overload, Any, cast, TypeVar from collections.abc import Iterable, Callable, MutableSequence, Iterator from pydicom import config _T = TypeVar("_T") _ItemType = TypeVar("_ItemType") class MultiValue(MutableSequence[_ItemType]): """Class to hold any multi-valued DICOM value, or any list of items that are all of the same type. This class enforces that any items added to the list are of the correct type, by calling the constructor on any items that are added. Therefore, the constructor must behave nicely if passed an object that is already its type. The constructor should raise :class:`TypeError` if the item cannot be converted. Note, however, that DS and IS types can be a blank string ``''`` rather than an instance of their classes. """ def __init__( self, type_constructor: Callable[[_T], _ItemType], iterable: Iterable[_T], validation_mode: int | None = None, ) -> None: """Create a new :class:`MultiValue` from an iterable and ensure each item in the :class:`MultiValue` has the same type. Parameters ---------- type_constructor : callable A constructor for the required type for all items. Could be the class, or a factory function. Takes a single parameter and returns the input as the desired type (or raises an appropriate exception). iterable : iterable An iterable (e.g. :class:`list`, :class:`tuple`) of items to initialize the :class:`MultiValue` list. Each item in the iterable is passed to `type_constructor` and the returned value added to the :class:`MultiValue`. """ from pydicom.valuerep import DSfloat, DSdecimal, IS def DS_IS_constructor(x: _T) -> _ItemType: return ( # type: ignore[no-any-return] self.type_constructor( # type: ignore[has-type] x, validation_mode=validation_mode ) if x != "" else cast(_ItemType, x) ) if validation_mode is None: validation_mode = config.settings.reading_validation_mode self._list: list[_ItemType] = list() self.type_constructor = type_constructor if type_constructor in (DSfloat, IS, DSdecimal): type_constructor = DS_IS_constructor for x in iterable: self._list.append(type_constructor(x)) def append(self, val: _T) -> None: self._list.append(self.type_constructor(val)) def __delitem__(self, index: slice | int) -> None: del self._list[index] def extend(self, val: Iterable[_T]) -> None: """Extend the :class:`~pydicom.multival.MultiValue` using an iterable of objects. """ self._list.extend([self.type_constructor(x) for x in val]) def __iadd__( # type: ignore[override] self, other: Iterable[_T] ) -> MutableSequence[_ItemType]: """Implement MultiValue() += Iterable[Any].""" self._list += [self.type_constructor(x) for x in other] return self def __eq__(self, other: Any) -> Any: return self._list == other @overload def __getitem__(self, index: int) -> _ItemType: pass # pragma: no cover @overload def __getitem__(self, index: slice) -> MutableSequence[_ItemType]: pass # pragma: no cover def __getitem__(self, index: slice | int) -> MutableSequence[_ItemType] | _ItemType: return self._list[index] def insert(self, position: int, val: _T) -> None: self._list.insert(position, self.type_constructor(val)) def __iter__(self) -> Iterator[_ItemType]: yield from self._list def __len__(self) -> int: return len(self._list) def __ne__(self, other: Any) -> Any: return self._list != other @overload def __setitem__(self, idx: int, val: _T) -> None: pass # pragma: no cover @overload def __setitem__(self, idx: slice, val: Iterable[_T]) -> None: pass # pragma: no cover def __setitem__( # type: ignore[misc] self, idx: int | slice, val: _T | Iterable[_T] ) -> None: """Set an item of the list, making sure it is of the right VR type""" if isinstance(idx, slice): val = cast(Iterable[_T], val) out = [self.type_constructor(v) for v in val] self._list.__setitem__(idx, out) else: val = cast(_T, val) self._list.__setitem__(idx, self.type_constructor(val)) def sort(self, *args: Any, **kwargs: Any) -> None: self._list.sort(*args, **kwargs) def __str__(self) -> str: if not self: return "" lines = (f"{x!r}" if isinstance(x, str | bytes) else str(x) for x in self) return f"[{', '.join(lines)}]" __repr__ = __str__
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() + ".\n") #\n creates a new line. print("Thank you everyone! \nThat was a great magic show!") message = ("Those are the first 9 numbers!") numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numbers: print(number) print(message) #using a list function to generate a set of numbers numbers = list(range(1,11)) print(numbers) # for loop that saves each number in number variable and prints for number in numbers: print(number) even_numbers = list(range(2,11,2)) print(even_numbers) odd_numbers = list(range(1,101,2)) print(odd_numbers) for odd_number in odd_numbers: print(odd_number*odd_number)
#Programmed by Chris Olszewski #Imports import sys import time #Variables #a=2 #Methods def yes_no(prompt, complaint='Invalid Answer'): while True: ok = input(prompt) if ok in ('Y', 'y', 'yes', 'Yes'): return True if ok in ('N', 'n', 'no', 'No'): return False print(complaint) def mutliChoice(title, ans1, ans2, ans3, ans4, complaint='Invalid Answer'): while True: print(title) print(" 1: ",ans1) print(" 2: ",ans2) print(" 3: ",ans3) print(" 4: ",ans4) questionAnswer = input() if questionAnswer == '1': return 1 elif questionAnswer == '2': return 2 elif questionAnswer == '3': return 3 elif questionAnswer == '4': return 4 else: print(complaint) def checkPrime(n): start = time.time() for x in range(2, n//2 + 1): if n % x == 0: break else: print(n, ' [', (time.time() - start),']') def main(): userAnswer = mutliChoice("Welcome to primeGen v0.3", "Generate", "Settings", "Credits", "Exit") if userAnswer == 1: a = 2 forward = yes_no('Exit at any time with Ctrl+C\nAre you sure?[Y/N]') while forward: checkPrime(a) a = a + 1 pass elif userAnswer == 2: print("Feature Not Added") yes = yes_no('Return to Menu? [Y/N]') if yes == True: main() elif userAnswer == 3: print("Programmed by Chris Olszewski \n Written as my first Python program. \n GitHub: chris-olszewski") yes = yes_no('Return to Menu? [Y/N]') if yes == True: main() elif userAnswer == 4: sys.exit(0) #Code main()
n = int(input()) k = int(input()) total = 0 total += n for i in range(1,k+1): total += n*10**i print(total)
def runFunction(): v1 = input() v2 = input() v3 = input() v4 = input() v5 = input() v6 = input() wins = 0 if v1 == "W": wins+=1 if v2 == "W": wins+=1 if v3 == "W": wins+=1 if v4 == "W": wins+=1 if v5 == "W": wins+=1 if v6 == "W": wins+=1 if wins >=5: return (1) elif wins >= 3: return (2) elif wins >= 1: return (3) else: return (-1) print(runFunction())
temp = int(input()) p = 5 * temp - 400 print(p) if (p < 100): print(1) elif (p > 100): print(-1) else: print(0)
word = input() Success = True for i in range(len(word)): if word[i] == "I" or word[i] == "O" or word[i] == "S" or word[i] == "H" or word[i] == "Z" or word[i] == "X" or word[i] == "N": Success = True else: print("NO") Success = False break if Success == True: print("YES")
import tkinter as tk print("Stage 5") ''' Base 2 to Base 10 1010 1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 0 * 2^0 = 1 * 8 + 0 * 4 + 1 * 2 + 0 * 1 = 10 ''' #This gets printed in terminal when program is opened #This function makes program process the entered value #*args function: when function is called, *args allows any number of parameters to pass through it by ignoring any value typed in the box #"process"will show up in terminal when code is ran to show that code is being excecuted #NOTE:A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called. def process(*args): #ent_value is the entry widget (tk.Entry widget), .get acts on ent_value and gets the value val = ent_value.get() #Check to ensure string of 1's and 0's check = check01(val) if (check == True): #removes left most 0 val gets passed to "def remove0 function" val = remove0(val) #converts from base 2 to base 10 result = base2to10(val) #updates display with conversion lab_results.config(text = str(val) + " --> " + str(result)) else: lab_results.config(text = "INVALID") ent_value.delete(0,tk.END) def base2to10(str): n = 0 total = 0 for i in range(len(str) - 1, -1, -1): total = total + int(str[i]) * 2**n n = n + 1 return total #function for removing left most 0's def remove0(str): '''012345 -- this is the index number of the string (6 index values total in this example) 000101 -- this is the inputted string/value, the "for i in range" will identify the first "1" and return/enter once identified in this case, it will take the last three digits''' #examines each index of the number inputted in the string and determines when the first 1 appears. If no 1's are found it has to be a zero. for i in range(0, len(str),1): #if str at index "i" is equivalent to a "1" (if there is a number "1" in the string...) if (str[i] == "1"): return str[i:]#returns index "i" to the length of the string (returns whatever number where after the first "1") #if you make it past this loop: return str #Function for checking if value is 1's and 0's only def check01(str): #Counts number of 0's in the str. (string) num_0 = str.count("0") num_1 = str.count("1")#counts number of 1's in string #if ammount of 1's and 0's is the same as the length of the string (entered value) if num_0 + num_1 == len(str): return True return False #root creates wndow in which prgram is in root = tk.Tk() #Construct the widgets lab_instructions = tk.Label(root, text = "Enter Binary") '''first widget: label widget, goes into tk module and uses constructor module that will build a label''' '''The first parameter is where it will be placed, in this case it is placed in the root window''' '''after first parameter (root), named parameters can be used to create the text of the label(in this case we use text)''' ent_value = tk.Entry(root) '''second widget: entry widget, goes into tk module and creates entry box''' '''Only attached to root window, does not need any name parameters''' lab_results = tk.Label(root, text = "--") '''third widget: label widget, creates another label''' '''Attached to root window, name parameter is used for results''' #Configure Widgets #Add the widgets to the window lab_instructions.pack() '''takes lab_instructions widget and packs it into root window, it knows to pack it into root window because it is specified as the parameter above. The must be done for ent_value and lab_results''' ent_value.pack() lab_results.pack() root.bind("<Return>",process) root.mainloop()
# модуль для работы с текстом def removeSymbols(string): # список символов к замене на пробел symbolsToReplaceWithSpace = ['\n', '\"', '/', '{', '}', '[', ']', '(', ')', '<', '>', '=', '.'] # заменяем в цикле символы на пробелы for symbol in symbolsToReplaceWithSpace: string = string.replace(symbol, ' ') # список спецсимволов к удалению symbolsToRemove = [',', '?', '!', ':'] # удаляем в цикле спецсимволы из списка for symbol in symbolsToRemove: string = string.replace(symbol, '') return string def wordAmountInFile(fileAsString, wordToCount): fileAsString = removeSymbols(fileAsString) # разбиваем строку на список подстрок words = fileAsString.split() # возвращаем количество вхождений искомого слова в список return words.count(wordToCount) # добавляем окончание к слову 'раз' в зависимости от числа вхождений def decorateAmount(wordAmount): if wordAmount > 4 and wordAmount < 21: wordAmount = str(wordAmount) wordAmount += ' раз' elif wordAmount % 10 > 1 and wordAmount % 10 < 5: wordAmount = str(wordAmount) wordAmount += ' раза' else: wordAmount = str(wordAmount) wordAmount += ' раз' return wordAmount
''' ------------------------------------------------------------------------------- Name: problem1.py Purpose: The purpose of this program is to make a conversion between the temperature in Fahrenheit to the temperature in Celsius, for my cousin visiting from the U.S Author: Surees.A Created: 07/12/2020 ------------------------------------------------------------------------------ ''' # introduce the program to the user print ("Welcome to the Fahrenheit to Celsius converter!") print("") # ask the user to input the temperature in celsius celsius_temperature = int(input("What is the temperature in Celsius? ")) # use the proper formula to convert the temperature in celsius to fahrenheit fahrenheit_temperature = (9/5*celsius_temperature)+ 32 print("") # Output the proper conversion onto the screen print ("The temperature you inputted, " + str(celsius_temperature) + "° Celsius is equal to " + str(fahrenheit_temperature) + "° Fahrenheit")
class Human(): def __init__(self): self.attack = 0 def play(self,node): print("Human turn!") while 1: print("Avaliable move: \n") for col,row in enumerate(node.frontier): if row!=None: print(str(row)+" "+str(col)+'\n') action = [int(x) for x in input("Your turn: ").split()] if node.frontier[action[1]]!=action[0]: print("Move is invalid!") continue break node.update_frontier(action[0],action[1]) return (action[0],action[1]) def win(self): print("Game over: Human win!")
import sqlite3 class menuPrincipal: barra = lambda self,n=40,caraca='*':print(caraca*n) def menu(self): self.barra() print("$ 1 -> Logar como Administrador") print("$ 2 -> Logar como Secretario") print("$ 3 -> Logar como Presidente") print("$ 4 -> Logar como Mesario") print("$ 99 -> Sair do sistema") self.barra() def loginSecretario(self,nomeSecretario, senhaSecretario): conex = sqlite3.connect('logins2.db') cursor = conex.cursor() self.nome = nomeSecretario self.senha = senhaSecretario cursor.execute(f''' SELECT * FROM tbl_secretario ''') for i in cursor.fetchall(): if (i[0]==self.nome and i[1]==self.senha) : print(f'Olá {self.nome}') return True def loginPresidente(self, nome,senha): conex = sqlite3.connect('loginUsers.db') cursor = conex.cursor() self.nomeP=nome self.senhaP=senha cursor.execute(''' SELECT * FROM tbl_pessoa ''') for i in cursor.fetchall(): if (i[0].lower()=='presidente' and i[1]==self.nomeP and i[2]==self.senhaP): print(f'Ola {self.nomeP}') return True conex.commit() def loginMesario(self,nome,senha): conex = sqlite3.connect('loginUsers.db') cursor = conex.cursor() self.nomeM=nome self.senhaM=senha cursor.execute(''' SELECT * FROM tbl_pessoa ''') for i in cursor.fetchall(): if (i[0].lower()=='mesario' and i[1]==self.nomeM and i[2]==self.senhaM): print(f'Ola {self.nomeM}') return True conex.commit() class administrador: conex = sqlite3.connect('logins2.db') cursor = conex.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS tbl_secretario( nomeUsuario text not null, password text not null ); ''') def __init__(self, MASTER_PASSWORD, nomeAdm): self.MASTER_PASSWORD = MASTER_PASSWORD self.nomeAdm = nomeAdm barra = lambda self, n=40, caractere='*':print(caractere*n) def menu(self): self.barra() print("$ 1 -> Cadastrar o secretario ") print("$ 2 -> listar secretarios cadastrados") print("$ 3 -> Recuperar senha do secretario") print("$ 5 -> Voltar para o menu principal") self.barra() def mostraSecretarios(self): self.cursor.execute(''' SELECT * FROM tbl_secretario ''') for i in self.cursor.fetchall(): self.barra() print (f'Nome: {i[0]} \nSenha: {i[1]} ') input("press enter to continue...") def inserirSecretario(self,nomeUsuario, password): self.nomeUsuario = nomeUsuario self.password = password self.cursor.execute(f''' INSERT INTO tbl_secretario VALUES ('{self.nomeUsuario}','{self.password}') ''') self.conex.commit() def recuperaSenha(self, nomeUsuario): self.nomeUsuario = nomeUsuario self.cursor.execute(f''' select * from tbl_secretario where nomeUsuario = '{self.nomeUsuario}' ''') if self.cursor.rowcount == 0 : print('nenhum usuario com essas especificações') else: for nomeUsuario in self.cursor.fetchall(): print(f'A senha para {nomeUsuario[0]} é {nomeUsuario[1]}') input("pressione qualquer tecla para continuar ...") class secretario: conex = sqlite3.connect('loginUsers.db') cursor = conex.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS tbl_pessoa( service text not null, nomeUsuario text not null, password text not null ); ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS tbl_candidato2( idCandidato int not null primary key unique, nomeCandidato text not null, funcaoCandidatura text not null ); ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS tbl_eleitor( idEleitor int not null primary key unique, nomeEleitor text not null, idVoto int not null ); ''') # def __init__(self,senhaSecretario, nomeSecretario): # self.senhaSecretario = senhaSecretario # self.nomeSecretario = nomeSecretario barra = lambda self, n=40, caractere='*':print(caractere*n) def menu(self): self.barra() print("$ 1 -> Cadastrar Presidente ou Mesario") print("$ 2 -> Cadastrar Candidato") print("$ 3 -> Mostar mesarios e presidentes do TRE") print("$ 4 -> Mostar Candidatos") print("$ 5 -> Voltar ao menu principal") self.barra() def inserirPessoa(self,service, nomeUsuario, password): self.service = service self.nomeUsuario = nomeUsuario self.password = password self.cursor.execute(f''' INSERT INTO tbl_pessoa VALUES ('{self.service}','{self.nomeUsuario}','{self.password}') ''') self.conex.commit() def inserirCandiato(self, idCandidato, nomeCandidato,funcaoCandidatura ): self.idCandidato = idCandidato self.nomeCandidato = nomeCandidato self.funcao = funcaoCandidatura self.cursor.execute(f''' INSERT INTO tbl_candidato2 VALUES ('{self.idCandidato}','{self.nomeCandidato}','{self.funcao}') ''') self.conex.commit() def mostrarMesariosPresidentes(self): self.cursor.execute(''' SELECT * FROM tbl_pessoa ''') for i in self.cursor.fetchall(): self.barra() print (f'Serviço: {i[0]} \nNome: {i[1]} \nSenha: {i[2]} ') input("press enter to continue...") self.conex.commit() def mostrarCandidatos(self): self.cursor.execute(''' SELECT * FROM tbl_candidato2 ''') for i in self.cursor.fetchall(): self.barra() print (f'Código para voto: {i[0]} \nNome: {i[1]}\nFunção: {i[2]} ') input("press enter to continue...") class presidente: conex = sqlite3.connect('loginUsers.db') cursor = conex.cursor() def __init__(self,nome,senha): self.senhaP=senha self.nomeP=nome barra = lambda self, n=40, caractere='*':print(caractere*n) def menu(self): self.barra() print("$ 1 -> Iniciar Votação e limpar votos") print("$ 2 -> Mostrar Eleitores") print("$ 3 -> Fechar a votação e computar votos") print("$ 5 -> Voltar para o menu principal") self.barra() def inicioVotacao(self): self.cursor.execute(''' delete from tbl_eleitor ''') if self.cursor.rowcount==0: print("não foi possivel limpar a votação") else: print("dados excluidos e votação iniciada") self.conex.commit() def computarVotos(self): votos=[] candidatos=[] n=[] self.cursor.execute(''' SELECT idVoto from tbl_eleitor ''') for i in self.cursor.fetchall(): votos.append(i[0]) self.cursor.execute(''' SELECT idCandidato from tbl_candidato2 ''') for i in self.cursor.fetchall(): candidatos.append(i[0]) for i in range(votos.__len__()): n.append(list(filter(lambda x: x==candidatos[i] , votos))) if n[i]==[]: print(f'O candidato {candidatos[i]} não recebeu nenhum voto') else: print(f'o candidato {candidatos[i]} recebeu {n[i].__len__()} votos') self.conex.commit() def mostarEleitores(self): self.cursor.execute(''' SELECT * FROM tbl_eleitor ''') for i in self.cursor.fetchall(): self.barra() self.cursor.execute(f''' SELECT * FROM tbl_candidato2 where idCandidato = {i[2]} ''') for j in self.cursor.fetchall(): print (f'CPF: {i[0]} \nNome: {i[1]} \nVotou em: {j[1]} para {j[2]} ') input("press enter to continue...") self.conex.commit() class mesario: conex = sqlite3.connect('loginUsers.db') cursor = conex.cursor() def __init__(self,nome,senha): self.nome=nome self.senha=senha barra = lambda self, n=40, caractere='*':print(caractere*n) def menu(self): self.barra() print("$ 1 -> Liberar votação para eleitores") print("$ 2 -> Voltar ao menu principal") self.barra() def inserirEleitor(self, cpf, nomeEleitor, votoEleitor): self.cpf = cpf self.nomeEleitor = nomeEleitor self.votoEleitor = votoEleitor self.cursor.execute(f''' INSERT INTO tbl_eleitor VALUES ('{self.cpf}','{self.nomeEleitor}','{self.votoEleitor}') ''') self.conex.commit()
from math import * class Circle: #@staticmethod def __init__(self): #dict=[] #for i in range(1,21): # dict.append(i) #print dict #self.radius=radius pass def rec(self): y = [] while True: l = (raw_input("enter the number")) if '@' in l: x = l.split('@')[0] y.append(x) else: print "we need an email address" str = raw_input("Do you want to enter another string") if str == "yes": continue else: break print y def main(): l = Circle() #j=NewYorker() l.rec() #j.printNationality() if __name__=="__main__": main()
#Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input # and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence class A: def array(self): print "hi" b = (raw_input("Enter the bin numbers:")) for i in b.split(','): #print i f= int(i, 2) print type(f) if f%5==0: print i #print (b) #print (format(raw_input("Enter the nimber:\n"), b) def main(): L= A() L.array() if __name__== "__main__": main()
# 2. Write a program which can compute the factorial of a given numbers. #The results should be printed in a comma-separated sequence on a single line. def fact(n): if n==0: return False elif n==1: return 1 else: prod = 1 for i in range(n): prod=prod*n n=n-1 return prod a=int(raw_input(("enter the number"))) fact(a)
class Circle: def rec(self,n): print "hi" print "wassup" y=[1,3,2,6,4,9,7] y1=sorted(y) print y1 for i in y1: #print i if i==n: print y1.index(i) # using the element to find the index else: print "element not found" break def main(): l = Circle() # j=NewYorker() n = int(raw_input("enter the number:\n")) l.rec(n) if __name__=="__main__": main()
#Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. class A: def q10(self): b= raw_input("enter the string") c=[] d=[] for i in b.split(' '): print i if i in c: continue else: c.append(i) #print c while c: minimum = c[0] # arbitrary number in list for x in c: if x < minimum: minimum = x d.append(minimum) c.remove(minimum) print ' '.join(d) def main(): a= A() a.q10() if __name__=="__main__": main()
#creating a bell-curve graph with mobile data print("Hello!\nThis is a bell-curve graph which shows the average rating for amazon mobile brands.") #importing the right libraries import csv import pandas as pd import plotly.figure_factory as ff #reading the csv file df=pd.read_csv("mobileData.csv") #creating a distribution plot graph (bell-curve) fig=ff.create_distplot([df["Average Rating"].tolist()], ["Average Rating"]) #calling the function fig.show()
"""This is test file1 for list. """ cars = ['ww', 'subaru', 'honda', 'toyota'] print('last car brand is % s.' % cars[-1].title()) # title() function is to capitalize the first char of string print(cars[-1].title()) # Use for loop to traverse the list elements. # Exercise 3-1 for car in cars: print(car) # Exercise 3-3 for car in cars: print('I enjoy my car', car+'!') # delete one element from list print('the length is: ', cars.__len__()) del cars[-1] print(cars) cars.pop(2) print(cars) # Exercise 3-4 ~ 3-7 people = ['p1', 'p2', 'p3', 'p4'] for p in people: print(p + ', Please have a party with us!') print('p2 is unavailable.') people[1]='p2m' for p in people: print(p + ', Please have a party with us!') print('We will have bigger party!') people.insert(0,'p1new') people.insert(3, 'p3new') people.append('plast') print(people) people.__delitem__(0) print(people) for p in people: print(p + ', please enjoy party with us!') print('Only 2 tickets available!') while len(people) > 2: pend = people.pop() print(pend + ', sorry that you cannot join the party.') print(people) for pin in people: people.remove(pin) print(people) """究其原因,在删掉第一个值,也就是索引[0]后,索引为[1]的值索引变为了[0],然后第二次删除是从索引[1]开始删除的,所以漏掉了一个值。 如果要用remove函数删空整个List,正确的做法应该是 list = ['Google', 'Runoob', 'Taobao', 'Baidu'] for i in range(len(list)): list.remove(list[0]) print(list) ———————————————— """ """ import copy a = rang(30) b = copy.deepcopy(a) for i in a: if i % 4 != 0: b.remove(i) print(b) """ # # while len(people) > 0: # people.pop() print(people) print(people.__sizeof__()) print(len(people))
""" This is a text file for testing Git in Pycharm! This is a new line for 1st time edition. End of line """ """This is the 2nd time edition. New line appended for 2nd time.""" name = "morris" print('%s, Welcome to PyCharm' % name) """Exercise 2-3: Upper case the first char of the name string """ # Function Casecon() complete the uppercase convert for the first char of the string def Casecon(name): name = name.upper()[0] + name[1:] return name name = Casecon(name) print(name) print('This is Upper case of your name:%s' % name.upper()) print('This is another case of your name in Uppercase:%s' % name) """Some new comments""" # exercise 2-6 name_with_space = ' morris \t' name = name_with_space.strip() print(name, len(name)) num = 8 print('This is my favourite number: %d' % num ) # Add some more comment
#!/usr/bin/env python def isPrime(n): def modulus(n,x): if (n%x)==0: return False else: if x<(n/2): return modulus(n,x+1) else: return True if n==0 or n==1: return False elif n==2: return True else: return modulus(n,2)
''' 使用lambda 表达式为槽函数传递参数 lambda 表达式:匿名函数,也就是没有名字的函数 ''' # fun=lambda :print("hello world") # # fun() # # fun1=lambda x,y:print(x,y) # # fun1("a","b") from PyQt5.QtWidgets import * import sys class LambdaSlotArgs(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("使用lambda 表达式为槽函数传递参数") button1=QPushButton("按钮1") button2=QPushButton("按钮2") button1.clicked.connect(lambda :self.onButtonClicked(10,20)) button2.clicked.connect(lambda :self.onButtonClicked(40,-20)) layout=QHBoxLayout() layout.addWidget(button1) mainFrame=QWidget() mainFrame.setLayout(layout) layout.addWidget(button2) self.setCentralWidget(mainFrame) def onButtonClicked(self,m,n): print("m+n=",m+n) QMessageBox.information(self,"结果",str(m+n)) if __name__ == '__main__': app = QApplication(sys.argv) example = LambdaSlotArgs() example.show() sys.exit(app.exec_())
x = "Samyuktha" print(x) # Combine numbers and text s = "My lucky number is %d, what is yours?" % 7 print(s) # alternative method of combining numbers and text s = "My lucky number is " + str(7) + ", what is yours?" print(s) # print character by index print(x[0]) # print piece of string print(x[0:3]) v = "Today is " + str(2)+"/"+str(2)+"/"+str(2016) print(v)
class Heap: def __init__(self): self.storage = [] def insert(self, value): # insert at end of heap new_index = len(self.storage) self.storage.append(value) self._bubble_up(new_index) def delete(self): if len(self.storage) == 0: return None elif len(self.storage) == 1: temp = self.storage[0] self.storage = [] return temp # move last element to beginning of list last_index = len(self.storage) - 1 self.storage[0], self.storage[last_index] = self.storage[last_index], self.storage[0] # remove first element (now at end of list) temp = self.storage.pop(last_index) self._sift_down(0) return temp def get_max(self): return self.storage[0] def get_size(self): return len(self.storage) def _sift_down(self, index): found_spot = False while not found_spot: # compare with largest child child1_index = (index*2) + 1 child2_index = (index*2) + 2 if child1_index > len(self.storage) - 1: # no children exist largest_child_index = index # while it seems wierd to refer to self as own child, # at bottom of loop an equality triggers breaking the loop elif child2_index > len(self.storage) - 1: # only 1 child largest_child_index = child1_index elif self.storage[child1_index] > self.storage[child2_index]: #child1 > child2 largest_child_index = child1_index else: #child2 > child1 largest_child_index = child2_index # swap if smaller than largest child if self.storage[index] < self.storage[largest_child_index]: self.storage[index], self.storage[largest_child_index] = self.storage[largest_child_index], self.storage[index] index = largest_child_index # repeat comparisons until child is smaller else: found_spot = True def _bubble_up(self, index): found_spot = False while not found_spot: # compare with parent parent_index = (index - 1) // 2 if parent_index < 0: parent_index = 0 # swap if larger than parent if self.storage[index] > self.storage[parent_index]: self.storage[index], self.storage[parent_index] = self.storage[parent_index], self.storage[index] index = parent_index # continue compare/swap until parent is larger else: found_spot = True def heap_sort(arr): sorted_arr = [] heap = Heap() for x in arr: heap.insert(x) for i in range(len(arr)): sorted_arr.append(heap.delete()) return sorted_arr
#!/usr/bin/python __author__ = 'boltz_j' import sys from time import time class Game(): def __init__(self, size_of_deck): """ At the creation of the game, we init a lookup table (shuffle_table) to precalculate the distribution of card for a round :param size_of_deck: Number of cards in the deck (MUST BE POSITIVE) :return: """ self.deck = list(range(size_of_deck)) self.shuffle_table = list(range(size_of_deck)) table_deck = list() deck = list(range(size_of_deck)) # Compute the lookup table while deck: # Step 1 : Take the top card off the deck and set it on the table table_deck.append(deck.pop()) if deck: # Step 2 : Take the next card off the top of desk and put it on the bottom of the deck in your hand. deck.insert(0, deck.pop()) # Store the position of the card after one round as the lookup table for x in range(size_of_deck): self.shuffle_table[x] = table_deck[x] def compute(self): """ :return: Return the number of round to come back to the initial deck """ # Two decks to use alternatively decks = [list(self.deck), list(self.deck)] round = 0 # Shuffle card until going back to original deck while True: # Select decks deck = decks[(round + 1) % 2] new_deck = decks[round % 2] # Use the shuffle table to make the new deck for x in deck: new_deck[self.shuffle_table[x]] = deck[x] round += 1 if self.is_over(new_deck): break # Return the number of round to come back to the original order return round @staticmethod def is_over(deck): """ :return: Return true if the game deck is at initial status, False otherwise """ # First card value (We assumed that first card value is 0) expected_value = 0 # Iterate on card value for card in deck: if card == expected_value: # Increment expected value and continue expected_value += 1 else: # Deck is not as the initial status return False # Deck is at the initial status return True def main(argv): if not argv[0]: sys.exit(1) try: size_of_deck = int(argv[0]) except ValueError: print('Error:', argv[0], 'is not a valid input') sys.exit(1) # New Game game = Game(size_of_deck) # Get start time start_time = time() # Find the solution rounds = game.compute() # Print Result end_time = time() print(rounds, 'rounds (computed in ', end_time - start_time, ')') sys.exit(0) if __name__ == "__main__": main(sys.argv[1:])
class Solution: def isMatch2(self, text, pattern): if not pattern: return not text first_match = bool(text) and pattern[0] in {text[0], '.'} if len(pattern) >= 2 and pattern[1] == '*': return (self.isMatch(text, pattern[2:]) or first_match and self.isMatch(text[1:], pattern)) return first_match and self.isMatch(text[1:], pattern[1:]) def isMatch(self, s: str, p: str) -> bool: s_len = len(s) p_len = len(p) if s_len == 0: if p_len == 0: return True if p[p_len - 1] == "*" and p_len >= 2: return self.isMatch(s[0:s_len], p[0:p_len-2]) return False if not p_len: # p == 0 and s > 0 return False actual = s[s_len -1] exp = p[p_len - 1] # Match! if exp in [actual, "."]: return self.isMatch(s[0:s_len -1], p[0:p_len -1]) # No match if (p_len - 2 < 0): return False next_p = p[p_len - 2] if exp == "*": if next_p in [actual , "."]: return self.isMatch(s[0:s_len - 1], p[0:p_len]) return self.isMatch(s[0:s_len], p[0:p_len-2]) # No match at all return False s = Solution() assert s.isMatch("aaa","ab*a*c*a") == True assert s.isMatch("aaa", "aaaa") == False assert s.isMatch("aa", "a") == False assert s.isMatch("aa", "aa") == True assert s.isMatch("ab", ".*") == True assert s.isMatch("aab", "c*a*b") == True assert s.isMatch("mississippi", "mis*is*p*.") == False
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.root = None def get_max(self, node: TreeNode) -> TreeNode: if not node: return node if node.right: return self.get_max(node.right) return node def __remove(self, node, parent_node): if node.left and node.right: max_left_branch = self.get_max(node.left) self.remove(max_left_branch.val) node.val = max_left_branch.val return is_root = False if not parent_node: # root is_root = True is_right_child = False if not is_root and node.val > parent_node.val: is_right_child = True replacement_node = None # only left child if node.left and not node.right: replacement_node = node.left # only left child if not node.left and node.right: replacement_node = node.right if is_root: self.root = replacement_node return if is_right_child: parent_node.right = replacement_node return parent_node.left = replacement_node def remove(self, val): node = self.root parent_node = None while node: if val > node.val: parent_node = node node = node.right continue if val < node.val: parent_node = node node = node.left continue # val == node.val: self.__remove(node, parent_node) break def deleteNode(self, root: TreeNode, key: int) -> TreeNode: self.root = root self.remove(key) return self.root
class Solution: def reverse(self, x: int) -> int: is_negative = False if x < 0: is_negative = True x *= -1 x_str = str(x) x_list = list(x_str) x_list_reversed = x_list[::-1] print(x_list_reversed) x_string = ''.join([char for char in x_list_reversed ]) if is_negative: x_reversed = int(x_string) * -1 else: x_reversed = int(x_string) if x_reversed > (2**31 -1) or x_reversed < 2**31 * -1: return 0 return x_reversed
import tkinter as tk from tkinter import Label,messagebox,Button,Entry,TOP,BOTTOM import webbrowser root = tk.Tk() root.geometry("300x100") root.minsize(300,100) root.maxsize(300,100) root.title("Multiple open URL") labal1 = Label(text = "Enter New URL:") labal1.pack() E1 = Entry() E1.pack() def url(): webbrowser.Chrome("C:/Program Files/Google/Chrome/Application/chrome.exe").open_new(E1.get()) button1 = Button(text = "Open URL", command = url, fg = "green") button1.pack() root.mainloop()
#-*-coding:utf-8-*- # Author: GISyang_china # 抽象工厂 # 是抽象方法的一种泛化,抽象工厂是一组工厂方法,其中每个工厂方法负责产生不同种类的对象 # ''' 工厂模式使用场景: 追踪对象的创建时 将对象的创建和使用解耦时 优化应用的性能和资源占用时 ''' class Frog: def __init__(self, name): self.name = name def __str__(self): return self.name def interact_with(self, obstacle): print('{} the Forg encounters {} an {}'.format(self, obstacle, obstacle.action())) class Bug: def __str__(self): return 'a bug' def action(self): return 'eats it' class FrogWorld: def __init__(self, name): print(self) self.player_name = name def __str__(self): return '\n\n\t-----forgWorld-----' def make_character(self): return Frog(self.player_name) def make_obstacle(self): return Bug() class Wizard: def __init__(self, name): self.name = name def __str__(self): return self.name def interact_with(self, obstacle): print('{} the Wizard battles agains {} and {}!'.format( self, obstacle, obstacle.action())) class Ork: def __str__(self): return 'an evil ork' def action(self): return 'kills it!' class WizardWorld: def __init__(self, name): print(self) self.player_name = name def __str__(self): return '\n\n\t-----WizardWorld-----' def make_character(self): return Wizard(self.player_name) def make_obstacle(self): return Ork() class GameEnvironment: def __init__(self, factory): self.hero = factory.make_character() self.obstacle = factory.make_obstacle() def play(self): self.hero.interact_with(self.obstacle) def validate_age(name): try: age = input('Welcome{}.How old are you?'.format(name)) age = int(age) except ValueError as err: print("Age{} is invalid, please try again...".format(age)) return (False, age) return (True,age) def main(): name = input("hello.what`s your name?") vaild_input = False while not vaild_input: vaild_input, age = validate_age(name) game = FrogWorld if age < 18 else WizardWorld environment = GameEnvironment(game(name)) environment.play() if __name__ == '__main__': main()
''' # -*- coding: utf-8-*- esto se utiliza para validar carecteres especiales en espanol Palabras reservadas False, class, finally, is, return None, continue, for, lambda, try True, def, from, nonlocal, while and, del, global, not, with as, elif, if, or, yield assert, else, import, pass break, except, in, raise ''' ''' x = 'hola' + "hola" y = 'camilo' * 4 print(x) print(y) print(type(x)) print(type(y)) print("--------------------------") pi = 3.1416 multiplicar = int(input("Ingrese el valor a multiplicar :: ")) exponente = int(input("Ingrese el valor a elevar :: ")) resultado = pi * multiplicar ** exponente print("El resultado de los valores anteriores es", resultado) print("--------------------------") ''' print("-----------------------------------------------------") name = input("Ingresa tú nombre > ") print(type(name)) print("Hola, " + name + "!") print("-----------------------------------------------------")
''' Secuencia de caracteres se puede acceder por indice indices empiezan en cero 0 1 2 3 4 5 c a m i l o Metodos upper isupper lower islower find isdigit endswith startswith split join ''' name = 'Camilo' validar = name[0] longitud = len(name) ultimaLetra = name[len(name)-1] mayuscula = name.upper() minuscula = name.lower() encontrar = name.find('m') print(validar , longitud, ultimaLetra, mayuscula, minuscula, encontrar)