text
stringlengths
37
1.41M
# Write a Python program to create Fibonacci series upto n using Lambda. from functools import reduce def fibonacci(count): sequence = (0, 1) for _ in range(2, count): sequence += (reduce(lambda a, b: a + b, sequence[-2:]), ) return sequence print(fibonacci(7))
# Write a Python program to get a list, sorted in increasing order by the last # element in each tuple from a given list of non-empty tuples. # Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] # Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] def last(x): return x[-1] def out20(lis): return sorted(lis, key=last) print(out20([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))
# Write a Python program to iterate over dictionaries using for loops. def out35(dic): for key, value in dic.items(): print(f'{key}: {value}') out35({0: 10, 1: 20, 2: 30})
# Write a Python program to check whether a given string is number or not using Lambda. def f18(string): return string.isnumeric() print(f18("123")) print(f18("123abc")) print(f18('abc123')) print(f18("9812345678"))
# Write a Python program to sum all the items in a list from functools import reduce def out16(func, lis): return func + lis print(reduce(out16, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
# Write a Python script to add a key to a dictionary. # Sample Dictionary : {0: 10, 1: 20} # Expected Result : {0: 10, 1: 20, 2: 30} sample = {0: 10, 1: 20} def out28(key, value): sample[key] = value return sample print(out28(2, 30))
# Write a Python program to get a single string from two given strings, separated # by a space and swap the first two characters of each string. # Sample String : 'abc', 'xyz' # Expected Result : 'xyc abz' def out4(lis): first_two_letter1 = lis[0][:2] first_two_letter2 = lis[1][:2] char1 = first_two_letter2 + lis[0][-1] char2 = first_two_letter1 + lis[1][-1] return char1 + ' ' + char2 print(out4(['abc', 'xyz']))
import csv import plotly.figure_factory as ff import pandas as pd import statistics df = pd.read_csv("StudentsPerformance.csv") performance = df['reading score'].tolist() mean = statistics.mean(performance) median = statistics.median(performance) mode = statistics.mode(performance) std_deviation = statistics.stdev(performance) first_std_deviation_start, first_std_deviation_end = mean-std_deviation, mean+std_deviation second_std_deviation_start, second_std_deviation_end = mean-(2*std_deviation), mean+(2*std_deviation) third_std_deviation_start, third_std_deviation_end = mean-(3*std_deviation), mean+(3*std_deviation) thin_1_std_deviation = [result for result in performance if result > first_std_deviation_start and result < first_std_deviation_end] thin_2_std_deviation = [result for result in performance if result > second_std_deviation_start and result < second_std_deviation_end] thin_3_std_deviation = [result for result in performance if result > third_std_deviation_start and result < third_std_deviation_end] print("The mean of this data set is ",mean) print("The median of this data set is ",median) print("The mode of this data set is ",mode) print("The standard deviation of this data set is ",sd) print("The percent of data that lies within 1 standard deviation is ",len(thin_1_std_deviation)*100.0/len(performance)) print("The percent of data that lies within 2 standard deviations is ",len(thin_2_std_deviation)*100.0/len(performance)) print("The percent of data that lies within 3 standard deviations is ",len(thin_3_std_deviation)*100.0/len(performance))
import random """Functions""" #Creates up to 6 rooms def room_creation(): for amount in range(random.randint(1,6)): rooms.append(room()) n = 0 for some in rooms: rooms[n].treasure_chance() rooms[n].healing_chance() rooms[n].monster_chance() #Just to make sure room creation works """ print(rooms[n].treasure) print(rooms[n].healing) print(rooms[n].monster) """ n = n + 1 """Classes""" class Warrior(): #Warrior Class inventory = {} def __init__(self): self.name = None self.health = 25 self.mana = 0 self.strength = 15 self.vitality = 8 self.magic = 8 self.sense = 11 self.dexerity = 11 self.charisma = 12 self.barriers = 0 self.wealth = 0 self.vision = 0 self.scan = 0 def add_item(self, item): self.inventory.update({item: 1}) def show_stats(self): print('Name:', self.name) print('Health:', self.health) print('Mana:', self.mana) print('Strength:', self.strength) print('Vitality:', self.vitality) print('Magic:', self.magic) print('Sense:', self.sense) print('Dexerity:', self.dexerity) print('Barriers:', self.charisma) print('Name:', self.barriers) print("Wealth:", self.wealth) class room(): #Room Class def __init__(self): self.treasure = 0 self.healing = 0 self.monster = 0 def treasure_chance(self): tchance = random.randint(0,100) if tchance < 40: self.treasure = 1 else: self.treasure = 0 def healing_chance(self): hchance = random.randint(0,100) if hchance < 10: self.healing = 1 else: self.healing = 0 def monster_chance(self): mchance = random.randint(0,100) if mchance < 60: self.monster = 1 else: self.monster = 0 """Lists and Dictionaries""" #Creates temporary list of rooms rooms = []
""" Physics 18L - Experiment 4 - Day 2 Christian Lee Professor: N. Whitehorn TA: Teresa Le Lab Date: Thursday, Oct 24, 2019 UCLA Physics Department Required libraries: matplotlib, numpy, scipy Projectile motion in 2D """ #Settings for 2D Projectile Motion #Number of particles num_particles = 5 #Gravitational Acceleration (x, y) gravity = [0, -1] #Velocity dependant drag constant #Recommended less than 0.1. drag = 0 #Apply a central force? (True/False) #If true, set ball_collisions -> False central_force = False #Central force power. Choose n for F = 1/r^n. #Recommended less than 2. central_force_power = 0.1 #Mass of the balls. Recommended 0.05 ball_mass = 0.05 #Random mass. If true, the particles will have varrying masses based on a gaussian distribution about mass. #If false, all particles will have uniform mass. #Forces affect particles of different masses differently random_mass = False #Ball collisions. If true, balls will bounce off of each other. ball_collisions = True import ProjectileMotion
import random, sys def common_member_set(lista1, lista2): a_set = set(lista1) b_set = set(lista2) if (a_set & b_set): return sorted(list(a_set & b_set)) else: return [] def remove_list_duplicates(lista): cleanlist = [] [cleanlist.append(x) for x in lista if x not in cleanlist] return cleanlist def common_member(lista1, lista2): supportList1 = [] for el in lista1: if el in lista2: supportList1.append(el) supportList1 = remove_list_duplicates(supportList1) supportList1.sort() return supportList1 def random_list(): lista = [] for x in range(random.randint(1,30)): lista.append(random.randint(1,101)) return lista #a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 1] #b = [1, 2, 3, 89, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1] a = ["leo", "luca", "pippo", "tania", "topolino"] b = ["giorgio", "piero", "tania", "leo", "asymov", "pino", "umberto"] #for i in range(10000): # a = random_list() # b = random_list() # if common_member(a,b) != common_member_set(a,b): # print(common_member(a,b)) # print(common_member+set(a,b)) # else: # sys.stdout.write(".") print(a) print(b) print(common_member(a,b)) print(common_member_set(a,b)) #lista = [] #for x in range(random.randint(1,101)): # lista.append(random.randint(1,101))
def format(number): upper = number // (1<<64) lower = number % (1<<64) print(""+hex(upper)+","+hex(lower)+",") for q in range(-342,0): power5 = 5 ** -q z = 0 while( (1<<z) < power5) : z += 1 if(q >= -27): b = z + 127 c = 2 ** b // power5 + 1 format(c) else: b = 2 * z + 2 * 64 c = 2 ** b // power5 + 1 # truncate while(c >= (1<<128)): c //= 2 format(c) for q in range(0,308+1): power5 = 5 ** q # move the most significant bit in position while(power5 < (1<<127)): power5 *= 2 # *truncate* while(power5 >= (1<<128)): power5 //= 2 format(power5)
#импорт pygame и random import pygame as pg import random as rnd #Кадры в секунду FPS = 60 #Цвета WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 225, 0) BLUE = (0, 0, 225) BLACK = (0,0,0) #идентификация окна программы pg.init() screen = pg.display.set_mode((140, 140)) clock = pg.time.Clock() #Класс, определяющий саму кость class Dice: #функция init, идентификация def __init__(self, x_circle, y_circle, dice, size_circle): self.x_circle = x_circle self.y_circle = y_circle self.size_circle = size_circle self.dice = dice #рисование фигур для кубика, квадрат и круг def draw_cube(self): pg.draw.rect(screen, WHITE ,(20, 20, 100, 100), 0, 15) def draw_circle(self): pg.draw.circle(screen, BLACK, (self.x_circle, self.y_circle), self.size_circle) #создание нового значения кубика def change(self, dice): self.dice = dice print(self.dice) #сторона 1 def side_2(self): self.draw_cube() pg.draw.circle(screen, BLACK, (45, 45), 10) pg.draw.circle(screen, BLACK, (95, 95), 10) #--------------------------------- def side_1(self): self.draw_cube() pg.draw.circle(screen, BLACK, (70, 70), 10) #--------------------------------- def side_3(self): self.draw_cube() self.side_2() pg.draw.circle(screen, BLACK, (70, 70), 10) #--------------------------------- def side_4(self): self.side_2() pg.draw.circle(screen, BLACK, (45,95), 10) pg.draw.circle(screen, BLACK, (95,45), 10) #--------------------------------- def side_5(self): self.side_4() pg.draw.circle(screen, BLACK, (70,70), 10) #--------------------------------- def side_6(self): self.side_4() pg.draw.circle(screen, BLACK, (45,70), 10) pg.draw.circle(screen, BLACK, (95,70), 10) #--------------------------------- # Начальная загрузка cube = Dice(320, 240, rnd.randint(1, 6), 10) cube.change(rnd.randint(1, 6)) # Бесконечный цикл while True: pg.time.delay(FPS) for i in pg.event.get(): if i.type == pg.QUIT: exit() if i.type == pg.MOUSEBUTTONDOWN: FPS = 60 for x in range(12): cube.change(rnd.randint(1, 6)) if cube.dice == 1: cube.side_1() elif cube.dice == 2: cube.side_2() elif cube.dice == 3: cube.side_3() elif cube.dice == 4: cube.side_4() elif cube.dice == 5: cube.side_5() elif cube.dice == 6: cube.side_6() pg.time.delay(FPS) FPS = FPS+5 pg.display.update()
from pyspark import SparkConf, SparkContext conf = SparkConf().setMaster("local").setAppName("Test") # setMaster(local) - we are doing tasks on a single machine sc = SparkContext(conf = conf) # read data from text file and split each line into words words = sc.textFile("../TXT/input_for_word_count.txt").flatMap(lambda line: line.split(" ")) # count the occurrence of each word wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda a,b:a +b) # save the counts to output list_of_words = ["education", "Canada", "University", "Dalhousie", "expensive", "good school", "good schools", "bad school", "faculty", "Computer Science", "graduate" ] wordsList = wordCounts.collect() f = open("../TXT/output.txt", "w") for word in list_of_words: flag = False for l in wordsList: if word == l[0]: print(str(l[0]), l[1]) f.write("%s %s\n" % (str(l[0]), l[1])) flag = True break if flag == False: print(word, 0) f.write("%s %s\n"% (word, 0)) print("")
# Module is create to take a 3 row matrix, and return a parametric curve for the shot # Row 0 should be x-positions, row 2 should be y-positions, row 3 should be approximate z-positions # The z-positions are expected to not be perfectly parabolic, but the x and y coords should be on some y=mx + b line import numpy as np import math import matplotlib.pyplot as plt test_matrix = np.array([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [1, 1, 1, 1, 1]], dtype=float) # Reduces 3-D shot to equivalent 2-D coords def flatten_shot(shot_matrix): squished = np.array([shot_matrix[0], shot_matrix[2]]) for i in range(len(shot_matrix[0])): squished[0, i] = math.sqrt(shot_matrix[0, i]**2 + shot_matrix[1, i]**2) return squished # Performs the polynomial fitting def fit_parabola(r_arr, z_arr): return np.polyfit(r_arr, z_arr, 2) # Given the 3 coefficients of a 2D parabola, proceeds to parameterize it # Takes coefficients in decreasing order of degrees def parameterize_2d_parabola(a, b, c): r = np.polynomial.polynomial.Polynomial([0, 1]) z = np.polynomial.polynomial.Polynomial([c, b, a]) return np.array([r, z]) def parameterize_2d_line(x_arr, y_arr): directing_vector = [(x_arr[1] - x_arr[0]), (y_arr[1] - y_arr[0])] x = np.polynomial.polynomial.Polynomial([x_arr[0], directing_vector[0]]) y = np.polynomial.polynomial.Polynomial([y_arr[0], directing_vector[1]]) return np.array([x, y]) def distance_between_points(p1, p2): x_diff = p1[0] - p2[0] y_diff = p1[1] - p2[1] dist = math.sqrt(x_diff**2 + y_diff**2) return dist # This implementation is absolutely fucked, since the x polynomial and y polynomial have a different variable # than the z polynomial. This class is meant to be a black box so that the user doesn't need to worry about fixing it # Note that t = sqrt(v^2 +(mv + b)^2) # raw matrix contains x-positions, y-positions, ball size rows # There should be a pdf/onenote somewhere explaining the math class ParametricParabola: def __init__(self, aligned_matrix): flat_shot = flatten_shot(aligned_matrix) parabola_coefficients = fit_parabola(flat_shot[0], flat_shot[1]) parabola_coefficients = list(map(lambda x : round(x, 5), parabola_coefficients)) parametric_parabola_2d = parameterize_2d_parabola(parabola_coefficients[0], parabola_coefficients[1], parabola_coefficients[2]) parametric_line_xy = parameterize_2d_line(aligned_matrix[0], aligned_matrix[1]) self.x_poly_base_t = parametric_line_xy[0] self.y_poly_base_t = parametric_line_xy[1] self.z_poly_base_r = parametric_parabola_2d[1] self.__zeroes_distance = None self.__xy_zeroes = None self.__parameter_range = None def evaluate_at(self, t): x = self.x_poly_base_t(t) y = self.y_poly_base_t(t) r = math.sqrt(x**2 + y**2) z = self.z_poly_base_r(r) return np.array([round(x, 3), round(y, 3), round(z, 3)]) def __get_all_potential_xy_zeroes(self): zeroes = self.z_poly_base_r.roots() self.__zeroes_distance = max(zeroes) - min(zeroes) potential_xy_zeroes = [] for zero in zeroes: temp_poly = self.x_poly_base_t**2 + self.y_poly_base_t**2 - zero**2 t_s = temp_poly.roots() for t in t_s: x = self.x_poly_base_t(t) y = self.y_poly_base_t(t) potential_xy_zeroes.append((x, y)) return potential_xy_zeroes # Can throw an exception def __narrow_down_by_direction(self): potential_zeroes = self.__get_all_potential_xy_zeroes() assert len(potential_zeroes) <= 4 if len(potential_zeroes) == 2: return potential_zeroes if len(potential_zeroes) < 2: raise Exception("The polynomial had less than 2 roots, i.e. it doesn't follow projectile motion") # We now have the zeroes ordered from furthest away to closest away # List can be 3 or four elements long, depending on the parabola potential_zeroes.sort(key=lambda p: p[0]**2 + p[1]**2, reverse=True) candidate_vector_1 = (potential_zeroes[0][0] - potential_zeroes[-1][0], potential_zeroes[0][1] - potential_zeroes[-1][1]) xy_line_directing_vector = (self.x_poly_base_t.coef[1], self.y_poly_base_t.coef[1]) # We need to check if these 2 vectors ar in the same direction. We check if dot product is positive dot_product = candidate_vector_1[0]*xy_line_directing_vector[0] + candidate_vector_1[1]*xy_line_directing_vector[1] if dot_product > 0: potential_zeroes.pop(1) else: potential_zeroes.pop(0) return potential_zeroes # Can throw an exception def __narrow_down_by_dist(self): # Ordered from furthest to nearest from origin ordered_narrowed_down_zeroes = self.__narrow_down_by_direction() if len(ordered_narrowed_down_zeroes) == 2: return ordered_narrowed_down_zeroes # If we make it here, there should be three potential zeroes dist1 = distance_between_points(ordered_narrowed_down_zeroes[0], ordered_narrowed_down_zeroes[1]) dist2 = distance_between_points(ordered_narrowed_down_zeroes[0], ordered_narrowed_down_zeroes[2]) if abs(dist1 - self.__zeroes_distance) < abs(dist2 - self.__zeroes_distance): ordered_narrowed_down_zeroes.pop(2) else: ordered_narrowed_down_zeroes.pop(1) return ordered_narrowed_down_zeroes # Can throw an exception # TODO: currently propagates the exception forward. Convenient for testing, but needs to be fixed eventually def get_xy_zeroes(self): if self.__xy_zeroes is None: self.__xy_zeroes = self.__narrow_down_by_dist() return self.__xy_zeroes # Currently throws an exception, which is not suitable. Will fix itself when get_xy_zeroes handles exception # TODO: handle the case where there are no zeroes (i.e. non-parabolic path) def get_parameter_range(self): if self.__parameter_range is None: xy_zeroes = self.get_xy_zeroes() parameter_bound_1 = (self.x_poly_base_t - xy_zeroes[0][0]).roots()[0] parameter_bound_2 = (self.x_poly_base_t - xy_zeroes[1][0]).roots()[0] self.__parameter_range = sorted([parameter_bound_1, parameter_bound_2]) return self.__parameter_range def get_3d_points_arr(self, amount=100): parameter_range = self.get_parameter_range() t_values = np.linspace(parameter_range[0], parameter_range[1], num=amount) shot_points_arr = np.empty([3, amount]) for i in range(amount): shot_points_arr[:,i] = self.evaluate_at(t_values[i]) return shot_points_arr r = math.sqrt(2) test3 = np.array([[r/2, r, 3*r/2, 2*r, 5*r/2], [r/2, r, 3*r/2, 2*r, 5*r/2], [0, 3, 4, 3, 0]]) test_parabola = ParametricParabola(test3) position_matrix = test_parabola.get_3d_points_arr() fig = plt.figure() ax = plt.axes(projection="3d") ax.scatter(position_matrix[0], position_matrix[1], position_matrix[2], 'red') plt.show()
''' Write a program to find the sum of the given elements of the list. (Hint: Use reduce method.) Example:Input:list = [1, 2, 3, 4, 5, 6, 7, 8, 9]''' from functools import reduce lst = [1,2,3,4,5,6,7,8,9] res = reduce(lambda a,b:a+b,lst) print(res)
'''Write a program to accept an input string from the user and determine the vowels in the string and calculate the number of vowels. ''' name = input("enter name") lst = ['a','i','o','u','e','A','E','I','O','U'] c = list(filter(lambda x: x in lst,name)) print(c)
data = "raj,sneha,sandy,Anu" print(list(map(lambda x: x.capitalize(),data.split(",")))) x = list(map(lambda x:x.capitalize(),data.split(","))) print(list(filter(lambda x:x.startswith("A"),x)))
max=6 for i in range(1,max+1): for j in range(max,i-1,-1): print(" ",end="") for k in range(1,i+1): print(k,end="") for l in range (k-1,0,-1): print(l,end="") print()
tnum = num = int(input("enter the number")) sum = 0 while num >9 : sum = (num%10+num//10) num = sum print(num)
from vending_machint.data import Drink flag = True balance = 0 drinks = { Drink('可樂',20), Drink('雪碧',20), Drink('茶裏王',20), Drink('原萃',25), Drink('純粹喝',25), Drink('水',20) } def desposit(): """ 儲值功能 :return: nothing """ global balance value = eval(input("儲值金額:")) while value < 1: print("====儲值金額需大於零====") value = eval(input("儲值金額:")) balance += value print(f'儲值後金額為{balance}元') def buy(): global balance, drinks print("請選擇商品") for i in range(len(drinks)): print(f'{i + 1}. {drinks[i]get.name} {drinks[i]["price"]}元') choose = eval(input('請選擇編號:')) while choose < 1 or choose > 6: print("請輸入1-6之間") choose = eval(input("請選擇: ")) buy_drink = drinks[choose - 1] while balance < buy_drink.price: print('====餘額不足,需要儲值嗎?====') want_deposit = input('y/n') if want_deposit == 'y': desposit() elif want_deposit == 'n': break else: print('====請重新輸入') if balance < buy_drink.price: print("====餘額不足====") desposit() else: balance -= buy_drink.price print(f'已購買{buy_drink["name"]} {buy_drink.price}元') print(f'購買後餘額為{balance}元') while flag: print("\n=============================") select = eval(input('1.儲值\n2.購買\n3.查詢餘額\n4.離開\n請選擇:')) if select == 1: machine.desposit() elif select == 2: machine.buy() elif select == 3: print(f'目前餘額為{balance}元') pass elif select == 4: print("bye") flag = False break else: print("====請輸入1-4之間") # # # # # # # # # # # # # # # # #
pos = -1 def search(list,n): l = 0 u = len(list)-1 while l <= u: mid = (l+u)//2 if list[mid] == n: globals()['pos'] = mid return True else: if list[mid] < n: l = mid+1 else: u = mid-1 return False list=[1,2,3,4,5,6,7] # list must b e sorted n = int(input('Please enter the number between 1 to 7: ')) if search(list,n): print(f'Found at {pos} index ') else: print('Not Found')
#Print the word with more than one occurrence from the given String Program def wordOccur(s): counter=[] st="" answer=[] res=list(set(s)) for i in res: count=0 for j in range(0,len(s)): if i==s[j]: count=count+1 counter.append(count) for i in range(0,len(counter)): if counter[i]>1: index=i element=res[index] answer.append(element) print(" ") print("The words with more than one occurence are: ") for i in answer: print(i) print("Enter the string: ") s=input().split(" ") wordOccur(s)
# Check if a Mth fibonacci number divides Nth fibonacci number m=int(input("Enter Mth fibonacci no: ")) n=int(input("Enter Nth fibonacci no: ")) a=1 b=1 arr=[] arr.append(a) arr.append(b) for i in range(2,n): c=a+b arr.append(c) a=b b=c print(arr) ele1=arr[m-1] ele2=arr[n-1] if ele2%ele1==0: print("Yes") else: print("No")
import sys def isPalindrome(str): for i in range(0, len(str)/2): if str[i] != str[len(str)-i-1]: return False return True def main(): user_input = raw_input("Enter a string to see if it's a palindrome: ") print(isPalindrome(user_input)) if __name__ == "__main__": main()
import numpy as np class SingleAxisTrajectory: """A trajectory along one axis. This is used to construct the optimal trajectory in one axis, planning in the jerk to achieve position, velocity, and/or acceleration final conditions. The trajectory is initialised with a position, velocity and acceleration. The trajectory is optimal with respect to the integral of jerk squared. Do not use this in isolation, this useful through the "RapidTrajectory" class, which wraps three of these and allows to test input/state feasibility. """ def __init__(self, pos0, vel0, acc0): """Initialise the trajectory with starting state.""" self._p0 = pos0 self._v0 = vel0 self._a0 = acc0 self._pf = 0 self._vf = 0 self._af = 0 self.reset() def set_goal_position(self, posf): """Define the goal position for a trajectory.""" self._posGoalDefined = True self._pf = posf def set_goal_velocity(self, velf): """Define the goal velocity for a trajectory.""" self._velGoalDefined = True self._vf = velf def set_goal_acceleration(self, accf): """Define the goal acceleration for a trajectory.""" self._accGoalDefined = True self._af = accf def generate(self, Tf): """ Generate a trajectory of duration Tf. Generate a trajectory, using the previously defined goal end states (such as position, velocity, and/or acceleration). """ #define starting position: delta_a = self._af - self._a0 delta_v = self._vf - self._v0 - self._a0*Tf delta_p = self._pf - self._p0 - self._v0*Tf - 0.5*self._a0*Tf*Tf #powers of the end time: T2 = Tf*Tf T3 = T2*Tf T4 = T3*Tf T5 = T4*Tf #solve the trajectories, depending on what's constrained: if self._posGoalDefined and self._velGoalDefined and self._accGoalDefined: self._a = ( 60*T2*delta_a - 360*Tf*delta_v + 720* 1*delta_p)/T5 self._b = (-24*T3*delta_a + 168*T2*delta_v - 360*Tf*delta_p)/T5 self._g = ( 3*T4*delta_a - 24*T3*delta_v + 60*T2*delta_p)/T5 elif self._posGoalDefined and self._velGoalDefined: self._a = (-120*Tf*delta_v + 320* delta_p)/T5 self._b = ( 72*T2*delta_v - 200*Tf*delta_p)/T5 self._g = ( -12*T3*delta_v + 40*T2*delta_p)/T5 elif self._posGoalDefined and self._accGoalDefined: self._a = (-15*T2*delta_a + 90* delta_p)/(2*T5) self._b = ( 15*T3*delta_a - 90*Tf*delta_p)/(2*T5) self._g = (- 3*T4*delta_a + 30*T2*delta_p)/(2*T5) elif self._velGoalDefined and self._accGoalDefined: self._a = 0 self._b = ( 6*Tf*delta_a - 12* delta_v)/T3 self._g = (-2*T2*delta_a + 6*Tf*delta_v)/T3 elif self._posGoalDefined: self._a = 20*delta_p/T5 self._b = -20*delta_p/T4 self._g = 10*delta_p/T3 elif self._velGoalDefined: self._a = 0 self._b =-3*delta_v/T3 self._g = 3*delta_v/T2 elif self._accGoalDefined: self._a = 0 self._b = 0 self._g = delta_a/Tf else: #Nothing to do! self._a = self._b = self._g = 0 #Calculate the cost: self._cost = (self._g**2) + self._b*self._g*Tf + (self._b**2)*T2/3.0 + self._a*self._g*T2/3.0 + self._a*self._b*T3/4.0 + (self._a**2)*T4/20.0 def reset(self): """Reset the trajectory parameters.""" self._cost = float("inf") self._accGoalDefined = self._velGoalDefined = self._posGoalDefined = False self._accPeakTimes = [None,None] pass def get_jerk(self, t): """Return the scalar jerk at time t.""" return self._g + self._b*t + (1.0/2.0)*self._a*t*t def get_acceleration(self, t): """Return the scalar acceleration at time t.""" return self._a0 + self._g*t + (1.0/2.0)*self._b*t*t + (1.0/6.0)*self._a*t*t*t def get_velocity(self, t): """Return the scalar velocity at time t.""" return self._v0 + self._a0*t + (1.0/2.0)*self._g*t*t + (1.0/6.0)*self._b*t*t*t + (1.0/24.0)*self._a*t*t*t*t def get_position(self, t): """Return the scalar position at time t.""" return self._p0 + self._v0*t + (1.0/2.0)*self._a0*t*t + (1.0/6.0)*self._g*t*t*t + (1.0/24.0)*self._b*t*t*t*t + (1.0/120.0)*self._a*t*t*t*t*t def get_min_max_acc(self, t1, t2): """Return the extrema of the acceleration trajectory between t1 and t2.""" if self._accPeakTimes[0] is None: #uninitialised: calculate the roots of the polynomial if self._a: #solve a quadratic det = self._b*self._b - 2*self._g*self._a if det<0: #no real roots self._accPeakTimes[0] = 0 self._accPeakTimes[1] = 0 else: self._accPeakTimes[0] = (-self._b + np.sqrt(det))/self._a self._accPeakTimes[1] = (-self._b - np.sqrt(det))/self._a else: #_g + _b*t == 0: if self._b: self._accPeakTimes[0] = -self._g/self._b self._accPeakTimes[1] = 0 else: self._accPeakTimes[0] = 0 self._accPeakTimes[1] = 0 #Evaluate the acceleration at the boundaries of the period: aMinOut = min(self.get_acceleration(t1), self.get_acceleration(t2)) aMaxOut = max(self.get_acceleration(t1), self.get_acceleration(t2)) #Evaluate at the maximum/minimum times: for i in [0,1]: if self._accPeakTimes[i] <= t1: continue if self._accPeakTimes[i] >= t2: continue aMinOut = min(aMinOut, self.get_acceleration(self._accPeakTimes[i])) aMaxOut = max(aMaxOut, self.get_acceleration(self._accPeakTimes[i])) return (aMinOut, aMaxOut) def get_max_jerk_squared(self,t1, t2): """Return the extrema of the jerk squared trajectory between t1 and t2.""" jMaxSqr = max(self.get_jerk(t1)**2,self.get_jerk(t2)**2) if self._a: tMax = -self._b/self._a if(tMax>t1 and tMax<t2): jMaxSqr = max(pow(self.get_jerk(tMax),2),jMaxSqr) return jMaxSqr def get_param_alpha(self): """Return the parameter alpha which defines the trajectory.""" return self._a def get_param_beta (self): """Return the parameter beta which defines the trajectory.""" return self._b def get_param_gamma(self): """Return the parameter gamma which defines the trajectory.""" return self._g def get_initial_acceleration(self): """Return the start acceleration of the trajectory.""" return self._a0 def get_initial_velocity(self): """Return the start velocity of the trajectory.""" return self._v0 def get_initial_position(self): """Return the start position of the trajectory.""" return self._p0 def get_cost(self): """Return the total cost of the trajectory.""" return self._cost #enums for feasibility results: class InputFeasibilityResult: """An enumeration of the possible outcomes for the input feasiblity test. If the test does not return ``feasible``, it returns the outcome of the first segment that fails. The different outcomes are: 0: Feasible -- trajectory is feasible with respect to inputs 1: Indeterminable -- a section's feasibility could not be determined 2: InfeasibleThrustHigh -- a section failed due to max thrust constraint 3: InfeasibleThrustLow -- a section failed due to min thrust constraint """ Feasible, Indeterminable, InfeasibleThrustHigh, InfeasibleThrustLow = range(4) @classmethod def to_string(cls,ifr): """Return the name of the result.""" if ifr==InputFeasibilityResult.Feasible: return "Feasible" elif ifr==InputFeasibilityResult.Indeterminable: return "Indeterminable" elif ifr==InputFeasibilityResult.InfeasibleThrustHigh: return "InfeasibleThrustHigh" elif ifr==InputFeasibilityResult.InfeasibleThrustLow: return "InfeasibleThrustLow" return "Unknown" class StateFeasibilityResult: """An enumeration of the possible outcomes for the state feasiblity test. The result is either feasible (0), or infeasible (1). """ Feasible, Infeasible = range(2) @classmethod def to_string(cls,ifr): """Return the name of the result.""" if ifr==StateFeasibilityResult.Feasible: return "Feasible" elif ifr==StateFeasibilityResult.Infeasible: return "Infeasible" return "Unknown" class RapidTrajectory: """Rapid quadrocopter trajectory generator. A quadrocopter state interception trajectory. The trajectory starts at a state defined by the vehicle's position, velocity, and acceleration. The acceleration can be calculated directly from the quadrocopter's attitude and thrust value. The trajectory duration is fixed, and given by the user. The trajectory goal state can include any combination of components from the quadrocopter's position, velocity, and acceleration. The acceleration allows to encode the direction of the quadrocopter's thrust at the end time. The trajectories are generated without consideration for any constraints, and are optimal with respect to the integral of the jerk squared (which is equivalent to an upper bound on a product of the inputs). The trajectories can then be tested with respect to input constraints (thrust/body rates) with an efficient, recursive algorithm. Whether linear combinations of states along the trajectory remain within some bounds can also be tested efficiently. For more information, please see the publication 'A computationally efficient motion primitive for quadrocopter trajectory generation', avaialable here: http://www.mwm.im/research/publications/ NOTE: in the publication, axes are 1-indexed, while here they are zero-indexed. """ def __init__(self, pos0, vel0, acc0, gravity): """Initialise the trajectory. Initialise the trajectory with the initial quadrocopter state, and the orientation of gravity for this problem. The orientation of gravity is required for the feasibility tests. Args: pos0 (array(3)): Initial position vel0 (array(3)): Initial velocity acc0 (array(3)): Initial acceleration gravity (array(3)): The acceleration due to gravity, in the frame of the trajectories (e.g. [0,0,-9.81] for an East-North-Up frame). """ self._axis = [SingleAxisTrajectory(pos0[i],vel0[i],acc0[i]) for i in range(3)] self._grav = gravity self._tf = None self.reset() def set_goal_position(self, pos): """ Define the goal end position. Define the end position for all three axes. To leave components free, list the end state as ``None`` in the argument, or use the function `set_goal_position_in_axis`. """ for i in range(3): if pos[i] is None: continue self.set_goal_position_in_axis(i,pos[i]) def set_goal_velocity(self, vel): """ Define the goal end velocity. Define the end velocity for all three axes. To leave components free, list the end state as ``None`` in the argument, or use the function `set_goal_velocity_in_axis`. """ for i in range(3): if vel[i] is None: continue self.set_goal_velocity_in_axis(i,vel[i]) def set_goal_acceleration(self, acc): """ Define the goal end acceleration. Define the end acceleration for all three axes. To leave components free, list the end state as ``None`` in the argument, or use the function `set_goal_acceleration_in_axis`. """ for i in range(3): if acc[i] is None: continue self.set_goal_acceleration_in_axis(i,acc[i]) def set_goal_position_in_axis(self, axNum, pos): """ Define the goal end position in axis `axNum`.""" self._axis[axNum].set_goal_position(pos) def set_goal_velocity_in_axis(self, axNum, vel): """ Define the goal end velocity in axis `axNum`.""" self._axis[axNum].set_goal_velocity(vel) def set_goal_acceleration_in_axis(self, axNum, acc): """ Define the goal end acceleration in axis `axNum`.""" self._axis[axNum].set_goal_acceleration(acc) def reset(self): """ Reset the trajectory generator. Removes all goal states, and resets the cost. Use this if you want to try multiple trajectories from one initial state. """ for i in range(3): self._axis[i].reset() def generate(self, timeToGo): """ Calculate a trajectory of duration `timeToGo`. Calculates a trajectory of duration `timeToGo`, with the problem data defined so far. If something (e.g. goal position) has not been defined, it is assumed to be left free. """ self._tf = timeToGo for i in range(3): self._axis[i].generate(self._tf) def check_input_feasibility(self, fminAllowed, fmaxAllowed, wmaxAllowed, minTimeSection): """ Run recursive input feasibility test on trajectory. Attempts to prove/disprove the feasibility of the trajectory with respect to input constraints. The result is one of three outcomes: (i): the trajectory is definitely input feasible (ii): the trajectory is definitely input infeasible (iii): input feasibility could not be determined If the feasibility is indeterminable, this should be treated as infeasible. Args: fminAllowed (float): minimum thrust allowed. [m/s**2] fmaxAllowed (float): maximum thrust allowed. [m/s**2] wmaxAllowed (float): maximum body rates allowed. [rad/s] minTimeSection (float): minimum time interval to be tested during the recursion. [s] Returns: An enumeration, of type InputFeasibilityResult. """ return self._check_input_feasibility_section(fminAllowed, fmaxAllowed, wmaxAllowed, minTimeSection, 0, self._tf) def _check_input_feasibility_section(self, fminAllowed, fmaxAllowed, wmaxAllowed, minTimeSection, t1, t2): """Recursive test used by `check_input_feasibility`. Returns: An enumeration, of type InputFeasibilityResult. """ if (t2-t1)<minTimeSection: return InputFeasibilityResult.Indeterminable #test the acceleration at the two limits: if max(self.get_thrust(t1), self.get_thrust(t2)) > fmaxAllowed: return InputFeasibilityResult.InfeasibleThrustHigh if min(self.get_thrust(t1), self.get_thrust(t2)) < fminAllowed: return InputFeasibilityResult.InfeasibleThrustLow fminSqr = 0 fmaxSqr = 0 jmaxSqr = 0 #Test the limits of the box we're putting around the trajectory: for i in range(3): amin, amax = self._axis[i].get_min_max_acc(t1, t2) #distance from zero thrust point in this axis v1 = amin - self._grav[i] #left v2 = amax - self._grav[i] #right #definitely infeasible: if (max(v1**2, v2**2) > fmaxAllowed**2): return InputFeasibilityResult.InfeasibleThrustHigh if(v1*v2 < 0): #sign of acceleration changes, so we've gone through zero fminSqr += 0 else: fminSqr += min(np.fabs(v1), np.fabs(v2))**2 fmaxSqr += max(np.fabs(v1), np.fabs(v2))**2 jmaxSqr += self._axis[i].get_max_jerk_squared(t1, t2) fmin = np.sqrt(fminSqr) fmax = np.sqrt(fmaxSqr) if fminSqr > 1e-6: wBound = np.sqrt(jmaxSqr / fminSqr)#the 1e-6 is a divide-by-zero protection else: wBound = float("inf") #definitely infeasible: if fmax < fminAllowed: return InputFeasibilityResult.InfeasibleThrustLow if fmin > fmaxAllowed: return InputFeasibilityResult.InfeasibleThrustHigh #possibly infeasible: if (fmin < fminAllowed) or (fmax > fmaxAllowed) or (wBound > wmaxAllowed): #indeterminate: must check more closely: tHalf = (t1 + t2) / 2.0 r1 = self._check_input_feasibility_section(fminAllowed, fmaxAllowed, wmaxAllowed, minTimeSection, t1, tHalf) if r1 == InputFeasibilityResult.Feasible: #check the other half return self._check_input_feasibility_section(fminAllowed, fmaxAllowed, wmaxAllowed, minTimeSection, tHalf, t2) else: #infeasible, or indeterminable return r1 #definitely feasible: return InputFeasibilityResult.Feasible def check_position_feasibility(self, boundaryPoint, boundaryNormal): """Test whether the position trajectory is allowable w.r.t. a plane. Test whether the position trajectory remains on the allowable side of a given plane. The plane is defined by giving a point on the plane, and the normal vector to the plane. The result is of the class StateFeasibilityResult, either Feasible or Infeasible. Args: boundaryPoint (array(3)): a point lying on the plane defining the boundary. boundaryNormal (array(3)): a vector defining the normal of the boundary. All points lying in the direction of the normal from the boundary are taken as feasible. Returns: An enumeration, of type StateFeasibilityResult. """ boundaryNormal = np.array(boundaryNormal) boundaryPoint = np.array(boundaryPoint) #make sure it's a unit vector: boundaryNormal = boundaryNormal/np.linalg.norm(boundaryNormal) #first, we will build the polynomial describing the velocity of the a #quadrocopter in the direction of the normal. Then we will solve for #the zeros of this, which give us the times when the position is at a #critical point. Then we evaluate the position at these points, and at #the trajectory beginning and end, to see whether we are feasible. coeffs = np.zeros(5) for i in range(3): coeffs[0] += boundaryNormal[i]*self._axis[i].get_param_alpha()/24.0 # t**4 coeffs[1] += boundaryNormal[i]*self._axis[i].get_param_beta() /6.0 # t**3 coeffs[2] += boundaryNormal[i]*self._axis[i].get_param_gamma()/2.0 # t**2 coeffs[3] += boundaryNormal[i]*self._axis[i].get_initial_acceleration()/6.0 # t coeffs[4] += boundaryNormal[i]*self._axis[i].get_initial_velocity() # 1 #calculate the roots tRoots = np.roots(coeffs) #test these times, and the initial & end times: for t in np.append(tRoots,[0,self._tf]): distToPoint = np.dot(self.get_position(t) - boundaryPoint, boundaryNormal) if distToPoint <= 0: return StateFeasibilityResult.Infeasible #all points tested feasible: return StateFeasibilityResult.Feasible def get_jerk(self, t): """ Return the trajectory's 3D jerk value at time `t`.""" return np.array([self._axis[i].get_jerk(t) for i in range(3)]) def get_acceleration(self, t): """ Return the trajectory's 3D acceleration value at time `t`.""" return np.array([self._axis[i].get_acceleration(t) for i in range(3)]) def get_velocity(self, t): """ Return the trajectory's 3D velocity value at time `t`.""" return np.array([self._axis[i].get_velocity(t) for i in range(3)]) def get_position(self, t): ''' Return the trajectory's 3D position value at time `t`.''' return np.array([self._axis[i].get_position(t) for i in range(3)]) def get_normal_vector(self, t): """ Return the vehicle's normal vector at time `t`. The vehicle's normal vector is that vector along which the thrust points, e_3. The required body rates to fly a trajectory can be calculated by finding that angular velocity which rotates this normal vector from one direction to another. Note that the result will be expressed in the planning frame, so that a rotation is necessary to the body frame. Args: t (float): time argument. Returns: np.array() containing a unit vector. """ v = (self.get_acceleration(t) - self._grav) return v/np.linalg.norm(v) def get_thrust(self, t): """ Return the thrust input at time `t`. Returns the thrust required at time `t` along the trajectory, in units of acceleration. Args: t (float): time argument. Returns: np.array() containing a unit vector. """ return np.linalg.norm(self.get_acceleration(t) - self._grav) def get_body_rates(self, t, dt=1e-3): """ Return the body rates input at time `t`, in inertial frame. Returns the body rates required at time `t` along the trajectory, in units of [rad/s]. This is done by discretizing the normal direction trajectory, with discretization `dt`. **To get (p,q,r) rates, rotate these with the vehicle's attitude.** Args: t (float): time argument. dt (float, optional): discretization time, default is 1ms Returns: np.array() containing the rates, in the inertial frame. """ n0 = self.get_normal_vector(t) n1 = self.get_normal_vector(t + dt) crossProd = np.cross(n0,n1) #direction of omega, in inertial axes if np.linalg.norm(crossProd) > 1e-6: return np.arccos(np.dot(n0,n1))/dt*(crossProd/np.linalg.norm(crossProd)) else: return np.array([0,0,0]) def get_cost(self): """ Return the total trajectory cost. Returns the total trajectory cost. Trajectories with higher cost will tend to have more aggressive inputs (thrust and body rates), so that this is a cheap way to compare two trajectories. """ return self._axis[0].get_cost() + self._axis[1].get_cost() + self._axis[2].get_cost() def get_param_alpha(self, axNum): """Return the three parameters alpha which defines the trajectory.""" return self._axis[axNum].get_param_alpha() def get_param_beta(self, axNum): """Return the three parameters beta which defines the trajectory.""" return self._axis[axNum].get_param_beta() def get_param_gamma(self, axNum): """Return the three parameters gamma which defines the trajectory.""" return self._axis[axNum].get_param_gamma()
""" Given an array a of n integers and a number, d , perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers. """ import math import os import random import re import sys # Complete the rotLeft function below. def rotLeft(a, d): shift = a[d:] + a[:d] return shift if __name__ == '__main__': nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) print(result)
""" Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed. countingValleys has the following parameter(s): n: the number of steps Gary takes s: a string describing his path """ import math import os import random import re import sys # Complete the countingValleys function below. def countingValleys(n, s): lvl = 0 count = 0 for char in s: if char == "U" : lvl += 1 else: if lvl == 0: count += 1 lvl -=1 return count if __name__ == '__main__': n = int(input()) s = input() result = countingValleys(n, s) print(result)
import sys # Se determina opcion 1 para que el ciclo pueda ser ejecutado opcion = 1 # Se declara una funcion por cada opcion posible # En este caso es determinar si un numero es mayor o menor que 0 def mayorcero(): numero = int(input('Ingrese un numero: ')) if numero > 0: print(f'{numero} es mayor que 0') else: print(f'{numero} es menor que 0') # En este caso se determina la suma de todos los numeros primos entre 2 y 20 def primo(): numero = 2 acumulado = 0 divisor = 0 while numero >= 2 and numero <= 20: divisor = 2 while numero % divisor != 0: divisor += 1 if numero == divisor: acumulado = acumulado + numero numero = numero + 1 return acumulado # En este caso se determina cuantos numeros primos hay entre el 2 y el 20 y se muestra la suma de estos def primo2(): numero = 2 acumulado = 0 divisor = 0 primo = 0 while numero >= 2 and numero <= 20: divisor = 2 while numero % divisor != 0: divisor += 1 if numero == divisor: primo = primo + 1 acumulado = acumulado + numero numero = numero + 1 return primo, acumulado # En este caso se determina si un numero es par o impar mediante booleanos def parimpar(): numero = int(input('Ingrese un numero: ')) if numero % 2 == 0: par = True else: par = False return par # En este caso se va a imprimir las tablas de multiplicar ingresando parametros como la tabla desde cuando hasta cuando def tablaMultiplicar(tabla, valorInicial, valorFinal): tabla = int(input('Ingrese una tabla a usar: ')) valorInicial = int(input('Ingrese desde cuando se empezara a multiplicar: ')) valorFinal = int(input('Ingrese hasta cuando se multiplicara: ')) for i in range(valorInicial, valorFinal + 1, 1): resultado = tabla * i print(f'{tabla} x {i} = {resultado}') # Ingresas un texto y te lo regresa en mayusculas def mayusculaminuscula(texto): texto = input('Ingresa cualquier texto: ') texto = texto.upper() return texto # Los numeros de fibonacci def fib(numero): if numero == 0: return 0 elif numero == 1: return 1 else: return fib(numero - 1) + fib(numero - 2) # Bucle que se repite para que sea el usuario el que decide cuando salirse while opcion >= 1 and opcion <= 8: # Se imprimen todas las opciones print('\n1. Numero mayor que 0') print('2. suma de numeros primos') print('3. Retorno de booleano') print('4. indicar cuantos numeros primos y la suma') print('5. Tablas de multiplicar') print('6. Nombre a mayusculas') print('7. fibonacci') print('8. Salir') # El usuario decide que opcion va a poner opcion = int(input('Ingresa una opcion: ')) if opcion >= 1 and opcion <= 8: if opcion == 1: mayorcero() elif opcion == 2: print('La suma de numeros primos entre 2 y 20 es: ', primo()) elif opcion == 3: if parimpar() == True: print('Es par') else: print('Es impar') elif opcion == 4: print('La cantidad de numeros enteros y la suma de estos es: ', primo2()) elif opcion == 5: tabla = 0 valorInicial = 0 valorFinal = 0 tablaMultiplicar(tabla, valorInicial, valorFinal) elif opcion == 6: texto = '' print('El texto ingresado convertido a mayusculas es: ', mayusculaminuscula(texto)) elif opcion == 7: numero = int(input('Ingresa un numero: ')) for i in range(0, numero + 1, 1): if i == 0: continue fibonacci = fib(i) print(fibonacci, end=' ') elif opcion == 8: sys.exit() else: print('opcion no valida')
# Programa que simule un tablero de ajedrez con estas caracteristicas f = int(input('Ingrese numero de filas: ')) c = int(input('Ingrese numero de columnas: ')) ajedrez = [[0 for j in range(c)]for i in range(f)] if f == 8 and c == 8: for i in range(0, f, 1): for j in range(0, c, 1): if i == 0: ajedrez[i][0] = 2 ajedrez[i][7] = 2 ajedrez[i][1] = 3 ajedrez[i][6] = 3 ajedrez[i][2] = 4 ajedrez[i][5] = 4 ajedrez[i][3] = 5 ajedrez[i][4] = 6 elif i == 7: ajedrez[i][0] = -2 ajedrez[i][7] = -2 ajedrez[i][1] = -3 ajedrez[i][6] = -3 ajedrez[i][2] = -4 ajedrez[i][5] = -4 ajedrez[i][3] = -5 ajedrez[i][4] = -6 elif i == 1: ajedrez[i][j] = 1 elif i == 6: ajedrez[i][j] = -1 else: ajedrez[i][j] = 0 for i in range(0, f, 1): for j in range(0, c, 1): print(ajedrez[i][j], end = ' ') print('\n') else: print('El tamaño del tablero no es correcto')
# Matrices en python f = 0 c = 0 valor = 0 suma = 0 contador = 0 # Declarar la matriz f = int(input('Ingrese numero de filas de la matriz: ')) c = int(input('Ingrese numero de columnas de la matriz: ')) matriz1 = [[0 for j in range(c)] for i in range(f)] # Llenar la matriz con datos elegidos for i in range(0, f, 1): for j in range(0, c, 1): valor = int(input(f'matriz1[{i}][{j}] = ')) matriz1[i][j] = valor # Imprimir la matriz print('----------MATRIZ1----------') for i in range(0, f, 1): for j in range(0, c, 1): print(matriz1[i][j], end = ' ') print('\n') # Generar promedio for i in range(0, f, 1): for j in range(0, c, 1): if matriz1[i][j] % 2 == 0: suma = suma + matriz1[i][j] # cuenta de los primos de la matriz if matriz1[i][j] > 1: divisor = 2 while matriz1[i][j] % divisor != 0: divisor = divisor + 1 if matriz1[i][j] == divisor: contador = contador + 1 # Mostrar resultados de operaciones print(f'La suma de pares es: {suma}') print(f'La cantidad de primos es: {contador}')
# Programa que imprime numeros de 5 a 1 for i in range(5, 0, -1): print(i)
# Robert Higgins G00364712 # 12th Feb 2018 # Euler Project Problem 5: Smallest multiple of numbers from 1 - 20 prod = 1 num = 1 while num <= 20: if prod % num != 0: prod = num*prod num +=1 print("LCM of all numbers from 1 - 20, inclusive, is:", prod)
# Robert Higgins G00364712 # 12th Feb 2018 # Euler Project Problem 2: Even Fibonacci Numbers fibNo1 = 0 fibNoLast = 1 fibNoCurr = fibNo1 + fibNoLast sumTotal = 0 while (fibNoCurr < 4000000): if (fibNoCurr % 2 == 0): sumTotal += fibNoCurr fibNo1 = fibNoLast fibNoLast = fibNoCurr fibNoCurr = fibNo1 + fibNoLast else: fibNo1 = fibNoLast fibNoLast = fibNoCurr fibNoCurr = fibNo1 + fibNoLast print("Sum of even Fibonacci Numbers, less than 4,000,000 is :", sumTotal)
""" Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. """ """ 解题思路: 建立一个新的对应关系,增加小数字的一些组合 Note:只需要一个小数字在左边即可 举例说明: 9:"IX" 因为如果是8的话是三个小数字在右边 此时变为VIII """ class Solution(object): def intToRoman(self, num): """ :type num: int :rtype: str """ list_num = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] list_roman = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] res = "" for k, v in enumerate(list_num): while(num >= v): res += list_roman[k] num -= v return res
''' You are to calculate the diagonal disproportion of a square matrix. The diagonal disproportion of a square matrix is the sum of the elements of its main diagonal minus the sum of the elements of its collateral diagonal. The main and collateral diagonals of a square matrix are shown in figures 1 and 2 respectively. The elements of the main diagonal are shown in green in figure 1, and the elements of the collateral diagonal are shown in cyan in figure 2. Given a String[] matrix, return its diagonal disproportion. The j'th character of the i'th element of matrix should be treated as the element in the i'th row and j'th column of the matrix. ''' class DiagonalProportion: def getDisproportion(self, matrix): def trace(matrix): return sum([row[i] for i, row in enumerate(matrix)]) return trace(matrix) - trace([x[::-1] for x in matrix])
import sqlite3 import hashlib def initializeTables(): #create the user table in user.db if the table does not already exist conn = sqlite3.connect("databases/users.db") c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS users (username text, password text) ''') conn.commit() conn.close() #create the posts table in myDatabase.db if the table does not already exist conn = sqlite3.connect("databases/myDatabase.db") c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS posts (username text, title text, body text) ''') conn.commit() conn.close() #authenticate checks the usernames and if the hash of the password matches with the password already in the database #returns true or false def authenticate(username,password): # if (username == "admin" and password == "password"): # return True # else: # return False hpass = hashlib.sha224(password).hexdigest() conn = sqlite3.connect("databases/users.db") c = conn.cursor() ans = c.execute('SELECT * FROM users WHERE username = "'+username+'" and password = "'+hpass+'";') for r in ans: return True return False #the users.db file should contain the username and the hashed password #passwords stored as hashlib.sha224(<password>).hexdigest() def registerCheck(username): conn = sqlite3.connect("databases/users.db") c = conn.cursor() ans = c.execute('SELECT * FROM users WHERE username = "'+username+'";') for r in ans: return False return True #if user exists in database, returns False def register(username,password): hpass = hashlib.sha224(password).hexdigest() conn = sqlite3.connect("databases/users.db") c = conn.cursor() c.execute('INSERT INTO users VALUES("'+username+'","'+hpass+'");') conn.commit() conn.close() #check if username is in the database already #might put this check somewhere else? def makePost(username,title,body): conn = sqlite3.connect("databases/myDatabase.db") c = conn.cursor() ans = c.execute('INSERT INTO posts VALUES("'+username+'","'+title+'","'+body+'");') conn.commit() #adds a post to the database based on parameters def getAllPosts(): conn = sqlite3.connect("databases/myDatabase.db") c = conn.cursor() c.execute('select * from posts;') return c.fetchall(); #2d array #first index = row id #second index - 0=name, 1=title, 2=body
from array import * def main(): num = float(input("Ingrese un valor en centimetros: ")) print("El valor en pulgadas es: ", round(num/2.54, 4)) if __name__ == "__main__": main()
from array import * def main(): num1 = int(input("Ingrese el primer numero entero: ")) num2 = int(input("Ingrese el segundo numero entero: ")) num3 = int(input("Ingrese el tercer numero entero: ")) # Valida si los tres numeros son iguales if num1==num2 and num1==num3: for x in range(3): print(num1+num2+num3, end = ' ') else: print(num1+num2+num3, end = ' ') if __name__ == "__main__": main()
# The purpose of this script is to generate a random # DNA sequence of length n, n is an int argument from sys import argv as argument from random import * """Script requires int as argument""" numToBase = {'0':'A','1':'T','2':'C','3':'G'} if(len(argument) != 2): print("Error in argument length; int is required...") else: DNAseq = "" for x in range(0, int(argument[1])): newBase = numToBase[str(randint(0,3))] DNAseq = DNAseq + newBase print(DNAseq)
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_deriv(x): return sigmoid(x) * (1 - sigmoid(x)) class neural_network: # Layer nodes describes the shape of the neural network (how many nodes in each layer) # lr is the learning rate, used to scale the amount the weights/biases shift each time the machine is trained def __init__(self, layerNodes, lr): self.layerNums = len(layerNodes) self.learningRate = lr # Weights for each layer # The number of rows is the number of hidden units of that layer (neurons) # The number of columns is the number of features/rows of the previous layer (neurons of last layer) self.weightLayers = [] # Biases for each layer # The number of rows is the number of hidden units of that layer (neurons) # Only one column self.biasLayers = [] # Populating layers (not input layer) with weights/biases for i in range(1, self.layerNums): weight = np.random.rand(layerNodes[i], layerNodes[i - 1])*2-1 bias = np.random.rand(layerNodes[i], 1)*2-1 self.weightLayers.append(weight) self.biasLayers.append(bias) def train(self, input_data, target_data): # Transposing input and target to convert to 1 column array (aka a layer) input_layer = np.reshape(input_data, (len(input_data), 1)) target_layer = np.reshape(target_data, (len(target_data), 1)) # Feed Forward # Creating activation data for layers # activation_data is data yet to be put through the activation function # Whilst sigmoid_data is post activation function data activation_data = [] sigmoid_data = [] # looping forward through the layers for i in range(self.layerNums - 1): # Input layer (create first activation layer) if i == 0: temp_a = self.weightLayers[i].dot(input_layer) + self.biasLayers[i] temp_s = sigmoid(temp_a) # Hidden+output layers else: temp_a = self.weightLayers[i].dot(sigmoid_data[i - 1]) + self.biasLayers[i] temp_s = sigmoid(temp_a) activation_data.append(temp_a) sigmoid_data.append(temp_s) # Back propagation # Creating an array of errors for back propagation (array will be reversed due to moving backwards) errors = [] # delta = array of (error)*(derivative of activation function)*(learning rate) # Use delta for weight and bias adjustments, since delta involves the error gradient deltas = [] for i in reversed(range(self.layerNums - 1)): # As error array consists only of error signals, length is self.layerNums-2 # as well as -1 due to indexing in arrays error_signal_layer = self.layerNums-2-1-i # (Hidden layers) error = weight from previous neuron * error signal of current neuron if i != self.layerNums-2: temp_error = self.weightLayers[i+1].T.dot(errors[error_signal_layer]) temp_delta = temp_error*sigmoid_deriv(activation_data[i])*self.learningRate # (Output layer) error = expected-output else: temp_error = target_layer-sigmoid_data[i] temp_delta = temp_error*sigmoid_deriv(activation_data[i])*self.learningRate errors.append(temp_error) deltas.append(temp_delta) # Updating weight and biases bias_adjustment = deltas[len(deltas)-1] # Weight adjustment for hidden layers if i != 0: # (i-1) index accessed as don't want to use output layers activation data # since trying to adjust weights/biases to effect output layers activation weight_adjustment = deltas[len(deltas)-1].dot(sigmoid_data[i-1].T) # Weight adjustment for input layer else: weight_adjustment = deltas[len(deltas)-1].dot(input_layer.T) self.biasLayers[i] += bias_adjustment self.weightLayers[i] += weight_adjustment # A feed forward once function, that returns the output layer (the result) # Already explained feed forward within train function, thus no comments for test def test(self, input_data): input_layer = np.reshape(input_data, (len(input_data), 1)) activation_data = [] sigmoid_data = [] for i in range(self.layerNums - 1): if i == 0: temp_a = self.weightLayers[i].dot(input_layer) + self.biasLayers[i] temp_s = sigmoid(temp_a) else: temp_a = self.weightLayers[i].dot(sigmoid_data[i - 1]) + self.biasLayers[i] temp_s = sigmoid(temp_a) activation_data.append(temp_a) sigmoid_data.append(temp_s) # Returns the output layer (the result) return sigmoid_data[len(sigmoid_data)-1]
#coding: utf-8 #Gabriel Dantas Santos de Azevêdo #Matrícula: 118210140 #Problema: Caixa Preta (descartando leituras) controle = True contp = 0 contc = 0 conta = 0 while True: dados = raw_input().split() peso = int(dados[0]) combust = int(dados[1]) altitude = int(dados[2]) for i in range(len(dados)): if peso >= 0 and int(dados[i]) == peso: contp += 1 elif combust >= 0 and int(dados[i]) == combust: contc += 1 elif altitude >= 0 and int(dados[i]) == altitude: conta += 1 else: break if controle: if int(dados[0]) < 0: print 'dado inconsistente. peso negativo.' controle = False break elif int(dados[1]) < 0: print 'dado inconsistente. combustível negativo.' controle = False break elif int(dados[2]) < 0: print 'dado inconsistente. altitude negativa.' controle = False break print 'peso: %d' % (contp) print 'combustível: %d' % (contc) print 'altitude: %d' % (conta)
#coding: utf-8 #Gabriel Dnatas Santos de Azevêdo #Matrícula: 118210140 #Problema: Unnamed conjunto_de_conjuntos = [] conjunto = [] entrada = "" contador = 0 elementos = 0 while entrada != "fim": entrada = raw_input() if entrada == "fim": break elif int(entrada) >= 0: conjunto.append(entrada) elif int(entrada) < 0: conjunto_de_conjuntos.append(conjunto) conjunto = [] maior_conjunto = 0 for n in range(len(conjunto_de_conjuntos)): if len(conjunto_de_conjuntos[n]) > maior_conjunto: maior_conjunto = len(conjunto_de_conjuntos[n]) contador = n elementos = len(conjunto_de_conjuntos[n]) elif len(conjunto_de_conjuntos) == 1: contador = n elementos = len(conjunto_de_conjuntos) if len(conjunto_de_conjuntos) > 0: print "Conjunto %d - %d elemento(s)" %(contador + 1, elementos)
#coding: utf-8 #Gabriel Dantas Santos de Azevêdo #Matrícula: 118210140 #Problema: Controle de Qualidade peso_cong = float(raw_input()) peso_dps = float(raw_input()) peso_ag = peso_cong - peso_dps perc_ag = peso_ag * 100.0 / peso_cong if perc_ag >= 5 and perc_ag < 10: print '%.1f%% do peso do produto é de água congelada.' % (perc_ag) print 'Produto em conformidade.' elif perc_ag >= 10: print '%.1f%% do peso do produto é de água congelada.' % (perc_ag) print 'Produto não conforme.' elif perc_ag < 5: print '%.1f%% do peso do produto é de água congelada.' % (perc_ag) print 'Produto qualis A.'
a = 3 b = 5 a=4 #print(a*b-b) city = "P a r i s" #print(3*len(city)) # 3*len(city) # len([1,2,5,6,9]) def fenelon_longueur(toto): o = 0 for letter in toto: o = o + 1 print(o) #print(fenelon_longueur('Ba+---^???!rcelone')) #print(fenelon_longueur('r')* 5 ) #print(type(78.9), type('pi')) # def check_arobas(email): # if type(email) != str: # print('Email incorrect1') # elif '@' in email: # print('OK') # else: # print('Email incorrect2') # check_arobas(3.14) # def ma_fonction(arg1, arg2): # return arg1 + arg2 # print(ma_fonction(3,5)) city = "pARIS" city = 'paris' city='pariSs' #print(lower(city)) #print(city.lower().capitalize()) #print(city.endswith("s")) # print le nom de chaque élève dont le prénom a une longueur < 4 # students = ['max','julie','mbape','zidane', 'lea'] # for person in students: # if len(person) < 4 : # print(person) # print le nom en majuscule de chaque élève dont la dernière lettre est 'a' # students = ['max','julie','tata','mbape','zidane', 'lea'] # for person in students: # if person.endswith('a'): # print(person.upper()) l = [1,2.5,'toto',3.14,[5,6]] # print les éléments n'étant pas de type float # for f in l: # if type(f)!= float: # print(f) city = 'Paris'*2 while len(city)>4: print(city) city = city[:-1]
items_count = int(input("Введите количество элементов списка ")) my_list = [] i = 0 number = 0 while i < items_count: my_list.append(input("Введите следующее значение списка ")) i += 1 for elem in range(int(len(my_list) / 2)): my_list[number], my_list[number + 1] = my_list[number + 1], my_list[number] number += 2 print(my_list)
import random import turtle l = open("wordfile.txt").read().splitlines() x = l[random.randint(0, len(l)-1)] h = list(x) w = ["_", "_", "_", "_", "_", "_", "_"] errorattempts = 8 prevguessleft = 8 attempts = 0 t = turtle.Turtle() t.pensize(10) t.pencolor("black") t.fd(200) t.bk(100) t.lt(90) t.fd(400) t.rt(90) t.fd(100) t.rt(90) t.fd(50) t.penup() t.fd(100) t.pendown() t.rt(270) def hangman(y, s, z): result = False for i in range(0,len(s)): if y == s[i] and y != z[i]: z[i] = y result = True elif y == s[i] and y == z[i]: print("You have already guessed that letter") result = True return result def guesscheck(result): global errorattempts global attempts if result == True: attempts = attempts + 1 print("You have ", errorattempts, " error attempts left") else: errorattempts = errorattempts - 1 attempts = attempts + 1 if errorattempts == 0: print("You have no error attempts left. Game over. The secret word was ", x) else: print("You have ", errorattempts, " error attempts left") def drawman(): global errorattempts if errorattempts == 7: t.circle(50) elif errorattempts == 6: t.rt(90) t.fd(150) elif errorattempts == 5: t.lt(45) t.fd(100) t.penup() elif errorattempts == 4: t.bk(100) t.pendown() t.rt(90) t.fd(100) t.penup() elif errorattempts == 3: t.bk(100) t.lt(45) t.bk(75) t.pendown() t.lt(135) t.fd(100) t.penup() elif errorattempts == 2: t.bk(100) t.lt(90) t.pendown() t.fd(100) t.penup() elif errorattempts == 1: t.bk(100) t.lt(135) t.bk(125) t.rt(90) t.fd(25) t.pendown() t.circle(5) t.penup() elif errorattempts <= 0: t.bk(50) t.pendown() t.circle(5) print(w) while True: a = (input(str("Enter a letter here: "))) ret = hangman(a, h, w) print(w) guesscheck(ret) if w == h: print("Congratulations! You found the word in ", attempts, " attempts!") break elif errorattempts <= 0: print("You have no more error attempts left. Game over.") break if prevguessleft != errorattempts: drawman() prevguessleft = errorattempts
import math figure = str(input()) if figure == "треугольник": a = float(input()) b = float(input()) c = float(input()) p = (a + b + c)/2 s = math.sqrt(p*(p-a)*(p-b)*(p-c)) print(s) elif figure == "прямоугольник": a = float(input()) b = float(input()) s = a * b print(s) elif figure == "круг": r = float(input()) s = 3.14 * r**2# math.pi * r**2 print(s)
"""Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation. """ def what_century(year): century = int(year) // 100 + 1 century = str(century) if year[-3:] == "000" or year[-2:] == "00": if year[1::-3] == "3": return str(int(century) - 1) + "rd" elif year[1::-3] == "2": return str(int(century) - 1) + "nd" elif year[1::-3] == "1": return str(int(century) - 1) + "st" else: return str(int(century) - 1) + "th" elif century == "11" or century == "12" or century == "13": return century + "th" elif century[-1] == "1": return century + "st" elif century[-1] == "2": return century + "nd" elif century[-1] == "3": return century + "rd" else: return century + "th"
# index(원소) : 리스트 내 특정한 원소의 인덱스를 찾기 list1 = ['나동빈', '강종구', '박진경', '박지훈'] print(list1.index('박진경')) #print(list.index('이태일')) #reverse() : 리스트의 원소를 뒤집기/그 함수를 불러오자 마자 자동으로 해당 변수의 값이 바로 뒤집혀짐 # 슬라이싱 기법 : 슬라이싱으로 변경된 list를 기존의 리스트에 다시 담아줘야 변경된 결과가 출력됨 list1 = [1,2,3] list1.reverse() print(list1) list1 = list1[::-1] print(list1) # 슬라이싱 기법으로 뒤집기 # sum(리스트 자료형) : 리스트의 모든 원소의 합 list1 = [1,2,3] print(sum(list1)) ''' 문자는 숫자와 함께 더해질 수 없으므로 오류 발생 list = [1,2, "133"] print(sum(list)) ''' # range(시작, 끝) : 특정 범위를 지정, 끝-1 값까지 실제 지정된 값임. # list(특정 범위) : 특정 범위의 원소를 가지는 리스트를 반환 my_range = range(5, 10) print(my_range) list = list(my_range) # 왜 에러가 발생하는지 확인? print(list) # all()/ any() : 리스트의 모든 원소가 참인지 판별 / 하나라도 참인지 판별 list1 = [True, False, True] print(all(list1)) print(any(list1))
password = 'a123456' i = 0 while i < 3: userpw = input('pls enter password') if password == userpw : print('login success') break else : i = i + 1 if 3 - i > 0: print('login fail , pls retry again') print('remain', 3 - i, 'times') #elif 3 - i == 0: #print('login fail , no more chance')
def get_prime(nth): prime = [2, 3] n = prime[-1] + 2 while len(prime) < nth: isPrime = True for x in prime: if n % x == 0: isPrime = False break if isPrime: prime.append(n) n += 2 return prime def get_prime_less_than(target): prime = [2, 3] n = prime[-1] + 2 while n < target: isPrime = True for x in prime: if n % x == 0: isPrime = False break if isPrime: prime.append(n) n += 2 return prime # primes = get_prime(10001) primes = get_prime_less_than(2000000) print(f"The sume of all primes below 2 million is : {sum(primes)}") print(f"The last prime is {primes[-1]}") # print(f"The 10001st prime is: {primes[-1]}")
questions = ["name", "quest", "favourite colour"] answers = ["lancelot", "the holy grail", "blue"] for q, a in (zip(reversed(questions), reversed(answers))): print(f"what is your {q}? It is {a}.")
import sys class Node: def __init__(self, data): self.dataVal = data self.nextVal = None # Class representing a queue.The front stores the front node and rear stores the last node of Linked List class Queue: def __init__(self): self.front = None self.rear = None def isEmpty(self): return self.front == None # Method to add an item to the queue, where the insertion happens at the rear def enqueue(self, item): newItem = Node(item) # Inserting the first item in the queue if self.rear == None: self.front = newItem self.rear = newItem return # For inserting subsequent nodes in the queue self.rear.nextVal = newItem self.rear = newItem # Method to remove an item from queue, where the removal happens from the front def dequeue(self): # Return if the queue is empty if self.isEmpty(): return # Changing the front node to the next Value after removing front node temp = self.front self.front = temp.nextVal # When last node is removed if (self.front == None): self.rear = None # Prints out the stack def printQueue(self): item = self.front if self.isEmpty(): print("Queue is empty!") else: print("Queue is :") while (item != None): print(item.dataVal, "->", end=" ") item = item.nextVal return class Stack: # Set head to null def __init__(self): self.head = None # Checks if stack is empty def isEmpty(self): if self.head == None: return True else: return False # Method to add data to the stack. Its always added to the top of the stack def push(self, data): if self.head == None: self.head = Node(data) else: newNode = Node(data) newNode.nextVal = self.head self.head = newNode # Remove element that is the current head i.e. top of the stack def pop(self): if self.isEmpty(): print("Cannot pop any element as the stack is empty!") return None else: # Removes the head node and make the next one the new head removedNode = self.head self.head = self.head.nextVal removedNode.nextVal = None return removedNode.dataVal # Returns the head node data value def top(self): if self.isEmpty(): return None else: return self.head.dataVal # Prints the stack def printStack(self): element = self.head if self.isEmpty(): print("Stack Underflow") else: print("\nStack is :") while (element != None): print(element.dataVal, "->", end=" ") element = element.nextVal return if __name__ == '__main__': try: q = Queue() q.enqueue(1) q.enqueue(2) q.dequeue() q.dequeue() q.enqueue(3) q.enqueue(4) q.printQueue() s = Stack() s.push(11) s.push(22) s.push(33) s.push(33) s.push(55) # Delete top elements of stack s.pop() s.pop() # Display stack elements s.printStack() except NameError: print("\nName error occured. Error message: ",sys.exc_info()[1]) except TypeError: print("\nType mismatch occured. Error message: ",sys.exc_info()[1]) except ValueError: print("\nValue error occurred. Error message: ",sys.exc_info()[1]) except IndexError: print("\nIndex error occurred. Error message: ",sys.exc_info()[1]) except SyntaxError: print("\nSyntax error ocurred. Error message: ",sys.exc_info()[1]) except AttributeError: print("\nAttribute error occured. Error message: ",sys.exc_info()[1]) except Exception: print("Error encountered : ", sys.exc_info()[0]) print("Try again...")
from collections import defaultdict import timeit import sys try: #Read all words from txt file words_file = open("words.txt","r") lines = words_file.readlines() words_file.close() #Initializing variable and data structures dictL={} sortedWordDict={} croppedDict={} anagramDict={} tempDict={} newDict=[] n = int(input("Enter the number of letters for which all anagrams are required: ")) #New dictionary with key as original word from file and value as sorted value of the same word for x in lines: # Convert to lower case and remove eol character str=x.rstrip('\n').lower() dictL[str]=sorted(str) #Filter out those elements which are not of given length n for x in dictL: if len(x) ==n: croppedDict.update({x:dictL[x]}) #Function to find anagrams of given length def findAnagrams(sortedWordDict): for key in sortedWordDict: #Converted value from List to string listToStr = ''.join(sortedWordDict[key]) tempDict[key]=listToStr anagramDict = defaultdict(list) for k, v in tempDict.items(): anagramDict[v].append(k) #New list to hold the final list sorted by the count of the anagrams sortedList = [] for x in anagramDict: num=len(anagramDict[x]) if num>1: str = (num,anagramDict[x]) sortedList.append(str) #Printing the final anagrams list for i in sorted(sortedList): print(i,'\n') #Invoke function to find anagrams of given length findAnagrams(croppedDict) #Calculate execution time of the program execution_time = timeit.timeit() print("Runtime of the program :", execution_time) except: e = sys.exc_info()[0] print("Error encountered : ", e) print("Try again...")
#!usr/bin/env python from Queue import PriorityQueue class State(object): """docstring for State""" def __init__(self, value, parent, start = 0, goal = 0): self.children = [] self.parent = parent self.value = value self.dist = 0 if parent: self.path = parent.path[:] self.path.append(value) self.start = parent.start self.goal = parent.goal else: self.path = [value] self.start = start self.goal = goal def get_dist(self): pass def create_children(self): pass class StateString(State): """docstring for StateString""" def __init__(self, value, parent, start = 0, goal = 0): super(StateString, self).__init__( value, parent, start, goal) self.dist = self.get_dist() def get_dist(self): if self.value == self.goal: return 0 dist = 0 for i in range(len(self.goal)): letter = self.goal[i] dist += abs(i - self.value.index(letter)) return dist def create_children(self): if not self.children: for i in range(len(self.goal)-1): val = self.value val = val[:i] + val[i+1] + val[i] + val[i+2:] child = StateString(val, self) self.children.append(child) class AStarSolver(object): """docstring for AStarSolver""" def __init__(self, start, goal): self.path = [] self.visited_queue = [] self.priority_queue = PriorityQueue() self.start = start self.goal = goal def solve(self): start_state = StateString( self.start, 0, self.start, self.goal ) self.priority_queue.put((0,start_state)) while not self.path and self.priority_queue.qsize(): closest_child = self.priority_queue.get()[1] closest_child.create_children() self.visited_queue.append(closest_child.value) for child in closest_child.children: if child.value not in self.visited_queue: if not child.dist: self.path = child.path break self.priority_queue.put((child.dist, child)) if not self.path: print "Could not reach the goal: " + self.goal return self.path # Main if __name__ == "__main__": start = "123456789" goal = "987654321" print "solving ..." a= AStarSolver(start, goal) a.solve() for i in xrange(len(a.path)): print "(%d) " %i + a.path[i]
#!/usr/bin/env python3 # This code was designed to learn how to handle a Sentiment Analysis with TextBlob library. # libs from textblob import TextBlob # returns the sentiment of text def analyze(obj): sentiment = obj.sentiment.polarity # print(sentiment) if sentiment == 0: print('Neutral') elif sentiment > 0: print('Positive') else: print('Negative') # read inline parameter line = "" while True: try: line = line + "\n" + input() except EOFError: break obj = TextBlob(line) # detect input language language = obj.detect_language() # translate if necessary if language != "en": try: obj = obj.translate(from_lang= language, to='en') analyze(obj) except: # if not possible translate print('Translation failed!') else: analyze(obj)
#!/usr/bin/python from passlib.hash import sha512_crypt import getpass import re import sys print("***** Chose your password wisely. It should be longer than 7 character, contain atleast a capital letter, a small letter and a number *****") print( "Please enter your password") raw_password = getpass.getpass() print("Please repeat the password") raw_password_repeat = getpass.getpass() if raw_password != raw_password_repeat: print("Passwords doesn't match") sys.exit(1) if len(raw_password) > 5: digit = re.match(".*\d.*", raw_password) small_l = re.match(".*[a-z].*", raw_password) cap_l = re.match(".*[A-Z].*", raw_password) if digit and small_l and cap_l: print("Good password. ") else: print("Come on, You can do better than that!") sys.exit(2) else: print("Password length is less than 10 characters is not accepted.") sys.exit(3) hash_password = sha512_crypt.using(rounds=5000).hash(raw_password) print("Please note your password hash: \n%s" %hash_password)
"""Implementation of a StringBuilder""" class StringBuilder(): """Builds a string""" def __init__(self, delimiter: str = '') -> None: self.delimiter = delimiter self.charlist = [] def append(self, word: str) -> None: self.charlist += list(word) def to_string(self) -> str: self.delimiter.join(self.charlist)
""" Assignment # 4 - ATM Alan Petrie This program asks the user for their PIN number. """ import random def main(): """ Main function: Evaluates if a user entered PIN is correct """ pin = 1234 counter = 0 max_tries = 3 #Get PIN from user while True: try: user_pin = input('\nEnter PIN number: ') except EOFError: continue try: user_pin = int(user_pin) except ValueError: print('Invalid entry. You must enter only digits.') user_pin = 0 continue if user_pin == pin: balance = random.random() * 1000 print(f'Your account balance is: ${balance:,.2f}') break else: counter += 1 if counter == max_tries: print('Account locked. The police are on their way.') break attempts_remaining = max_tries - counter if attempts_remaining == 1: print(f'Invalid PIN. You have {attempts_remaining} attempt remaining.') else: print(f'Invalid PIN. You have {attempts_remaining} attempts remaining.') if __name__ == '__main__': main()
def somme(nb1, nb2): return nb1 + nb2 def moyenne(nb1, nb2): return somme(nb1, nb2) / 2 note1 = 10 note2 = 30 moyenne = moyenne(note1, note2) print("Note 1 : ", note1) print("Note 2 : ", note2) print("La moyenne est de", moyenne) def mean(nb1, nb2, nb3): return (nb1 + nb2 + nb3) / 3 print(mean(1,2,3))
from User import User users = [] #Messages Format successMsg = 'AWESOME YOU HAVE ALREADY IN OUR APP' minorErorMsg = 'OPPS, YOU ARE MINOR' errorMsg = 'Password or user incorret' welcomeMsg='<<<<Welcome to our login form made with python>>>>' option1Msg = '1- Create a User from Scratch' option2Msg = '2- Login using JWT' exitMsg = '3- Exit' #Bussiness Logic def signIn(userName,password): for user in users: if(user.getUserName() == userName and user.getPassword() == password): return(userName + " have login Succesfully") return(errorMsg) def signUp(username,password,age,career): if validateAge(age): newUser = User(username,password,age,career) users.append(newUser) return(successMsg) else : return(minorErorMsg) def validateAge(age): render = True if(age < 18): render = False return render def menu(): print(welcomeMsg) print(option1Msg) print(option2Msg) print(exitMsg) return int(input("Please select an option: ")) #App Starting option = menu() while(option != 3): if(option==1): username = input('Enter your UserName: ') password = input('Enter your Password: ') age = int(input('Enter your age: ')) career = input('Enter your professional career: ') print(signUp(username,password,age,career)) elif(option==2): username = input('Enter your UserName: ') password = input('Enter your Password: ') print(signIn(username,password)) option = menu() print('Good Bye')
class Parrafo(): def __init__(self): self.lineas = [] def agregar_lineas(self, nombre): entry = input("\nIngrese parrafo. Para terminar ingresesolamente '.': \n") while entry != ".": self.lineas.append(entry) entry = input("") self.lineas = '\n'.join(self.lineas) f = open(nombre, 'a') f.writelines(self.lineas + "\n\n") f.close()
#!/usr/bin/env python3 import random import sys min = 1 max = 20 number = 0 part1 = 0 part2 = 0 while True: upordown = random.randint(0,1) if upordown == 1: result = random.randint(1,max) part1 = random.randint(1,result) part2 = result - part1 else: part1 = random.randint(1,max) part2 = random.randint(1,part1) result = part1 - part2 if upordown == 1: question = '%s + %s = ' % (str(part1), str(part2)) else: question = '%s - %s = ' % (str(part1), str(part2)) givenread = input(question) if givenread == '': sys.exit(0) given = int(givenread) if given == result: print('OK! super') else: print('WOEPS! het antwoord was %s' % str(result))
from tkinter import * class Calc(Frame): def __init__(self, master=None): Frame.__init__(self,master) self.grid() self.criaComponet() def criaComponet(self): self.entrada = Entry(self.master, width=34, bd =3 ) self.entrada.grid(row=1, column=0) botoes=["7","8","9","+","4","5","6","*","1","2","3","/","0","-","C","="] linha = 1 coluna =1 for i in botoes: comando= lambda x=i:self.calcular(x) self.botao=Button(self, text=i, width=6, height=2, command=comando) self.botao.grid(row=linha,column=coluna) if coluna >=4: linha+=1 coluna=0 coluna+=1 def calcular(self, valor): if valor =="=": try: calculo=eval(self.entrada.get()) self.entrada.insert(END, "="+str(calculo)) except: self.entrada.insert(END, "ERRO") elif valor =="C": self.entrada.delete(0, END) else: if "=" in self.entrada.get(): self.entrada.delete(0,END) self.entrada.insert(END, valor) root =Tk() a=Calc(master=root) a.mainloop()
import unittest from pprint import pprint from src.RandomGenerator.RandomGenerator import RandomGenerator class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.random = RandomGenerator() # Assigning start and end range of numbers to perform random function. self.start = 1 self.end = 1000 self.length = 5 # no of random number to append in List. self.seed = 5 # Seed function is used to save the state of a random function. def test_instantiate_calculator_self(self): self.assertIsInstance(self.random, RandomGenerator) def test_random_without_seed_integer(self): test_int_random = self.random.random_num_without_seed_integer(self.start, self.end) pprint(test_int_random) self.assertEqual(isinstance(self.random.random_num_without_seed_integer(self.start, self.end), int), True) def test_random_without_seed_decimal(self): test_decimal_random = self.random.random_num_without_seed_decimal(self.start, self.end) pprint(test_decimal_random) self.assertEqual(isinstance(self.random.random_num_without_seed_decimal(self.start, self.end), float), True) def test_random_with_seed_integer(self): test_seed_int_random = self.random.random_num_with_seed_integer(self.start, self.end, self.seed) pprint(test_seed_int_random) self.assertEqual(self.random.random_num_with_seed_integer(self.start, self.end, self.seed), test_seed_int_random) def test_random_with_seed_decimal(self): test_seed_decimal_random = self.random.random_num_with_seed_decimal(self.start, self.end, self.seed) pprint(test_seed_decimal_random) self.assertEqual(self.random.random_num_with_seed_decimal(self.start, self.end, self.seed), test_seed_decimal_random) def test_random_list_with_seed_integer(self): test_int_list = self.random.random_list_with_seed_integer(self.start, self.end, self.length, self.seed) pprint(test_int_list) for x in test_int_list: test_data = int(x) self.assertEqual(isinstance(test_data, int), True) def test_random_list_with_seed_decimal(self): test_decimal_list = self.random.random_list_with_seed_decimal(self.start, self.end, self.length, self.seed) pprint(test_decimal_list) for x in test_decimal_list: test_data = float(x) self.assertEqual(isinstance(test_data, float), True) if __name__ == '__main__': unittest.main()
from src.Calculator.Addition import addition from src.Calculator.Division import division def calculate_mean(data): try: total_sum = 0.0 for num in data: total_sum = addition(total_sum, num) return division(len(data), total_sum) # division will perform total_sum / len(data) except ZeroDivisionError: print("You can't divide by zero.") except ValueError: print("No valid integer!") except IndexError: print("It's a empty list.")
''' #author: cristianlepore ''' class Animal(object): def __init__(self, age, name = None): self.age = age self.name = name def get_age(self): return self.age def get_name(self): return self.name def set_age(self, newAge): self.age = newAge def set_name(self, newName = None): self.name = newName def __str__(self): return "animal:" + str(self.name) + ",", str(self.age) myAnimal1 = Animal(2) myAnimal2 = Animal(3, 'Mike')
''' @author: cristianlepore ''' def factorial(x): ''' input: a number output: the factorial of x ''' if x == 1: return 1 else: return x * factorial(x-1) x = 4 print(factorial(x))
''' @author: cristianlepore ''' count = 0 strToFind = "bob" s = "azcbobobegghakl" while(strToFind in s): s = s[s.find(strToFind) + 1 : -1] count += 1 print(count)
''' @author: cristianlepore ''' def applyToEach(L, f): ''' input: a list and a function output: A list after having applied the function f to each element of the list ''' for i in range(len(L)): L[i] = f(L[i]) return L def mult(a): ''' input: one numbers output: one number. The multiplication of a times 5 ''' return a * 5 def add(a): ''' input: one numbers output: one number. Add +1 to the element a ''' return a + 1 def square(a): ''' input: one numbers output: one number. The power of a ''' return a**2 testList = [1, -4, 8, -9] ''' # Applied function print(applyToEach(testList, mult)) # Add +1 to each element print(applyToEach(testList, add)) ''' # Square of each element print(applyToEach(testList, square))
def oddTuples(aTup): ''' input: a tuple. output: a new tuple containing only the odd element of the input tuple ''' # Start code here # Definition of the new tuple myTuple = () # Loop for i in range(len(aTup)): if i % 2 == 0: myTuple += (aTup[i],) # Return value return myTuple # Definition of my tuple aTup = ('I', 'am', 'a', 'test', 'tuple') # Call the procedure print(oddTuples(aTup))
def mult(a, b): ''' input: two numbers output: a recursion of a times b ''' if b == 1: return a else: return a + mult(a, b-1) a = 10 b = 5 print(mult(a, b))
# 1: Создайте функцию, принимающую на вход имя, возраст и город проживания человека. Функция должна возвращать строку # вида «Василий, 21 год(а), проживает в городе Москва» def anketa(name, age, sity): info = f'{name.title()}, {age} год(а), проживает в городе {sity.title()}' return info print(anketa('катя', 21, 'кирОв')) # 2: Создайте функцию, принимающую на вход 3 числа и возвращающую наибольшее из них. def max_numbers(a, b, c): numbers = [a, b, c] return max(numbers) print(max_numbers(101, 15, 42)) # 3: Давайте опишем пару сущностей player и enemy через словарь, который будет иметь ключи и значения: # name - строка полученная от пользователя, # health = 100, # damage = 50. # Поэкспериментируйте с значениями урона и жизней по желанию. # Теперь надо создать функцию # attack(person1, person2). # Примечание: имена аргументов можете указать свои. # Функция в качестве аргумента будет принимать атакующего и атакуемого. # В теле функция должна получить параметр damage атакующего и отнять # это количество от health атакуемого. # Функция должна сама работать со словарями и изменять их значения. # 4: Давайте усложним предыдущее задание. Измените сущности, добавив новый параметр - armor = 1.2 (величина # брони персонажа) # Теперь надо добавить новую функцию, которая будет вычислять и возвращать полученный урон по формуле # damage / armor # Следовательно, у вас должно быть 2 функции: # Наносит урон. Это улучшенная версия функции из задачи 3. # Вычисляет урон по отношению к броне. # # Примечание. Функция номер 2 используется внутри функции номер 1 для вычисления урона и вычитания его из # здоровья персонажа. player1_name = input('Player 1: ') player2_name = input('Player 2: ') player1 = { 'name': player1_name, 'health': 100, 'damage': 50, 'armor': 1.2 } player2 = { 'name': player2_name, 'health': 100, 'damage': 50, 'armor': 1.2 } def result_damage(damage, armor): return round(damage / armor) def attack(player, enemy): print(f'{player["name"]} атакует {enemy["name"]}') damage = result_damage(player['damage'], enemy['armor']) enemy['health'] -= damage print(f'{enemy["name"]} health = {enemy["health"]}') attack(player1, player2)
# code_report Solution # https://youtu.be/yMxoRT381yQ # from https://docs.python.org/3/library/bisect.html import bisect def find_lt(a, x): 'Find rightmost value less than x' i = bisect.bisect_left(a, x) if i: return a[i-1] raise ValueError def find_le(a, x): 'Find rightmost value less than or equal to x' i = bisect.bisect_right(a, x) if i: return a[i-1] raise ValueError def find_gt(a, x): 'Find leftmost value greater than x' i = bisect.bisect_right(a, x) if i != len(a): return a[i] raise ValueError def find_ge(a, x): 'Find leftmost item greater than or equal to x' i = bisect.bisect_left(a, x) if i != len(a): return a[i] raise ValueError # Solution l = list () for i in range (0, 31): for j in range (0, 31): if (i != j): l.append (2**i + 2**j) l.sort () t = int (input ()) for i in range (0, t): N = int (input ()) ans = 0 if (N < 3): ans = 3 - N else: ans = min (N - find_le (l, N), find_gt (l, N) - N) print (ans)
import time start_time = time.time() def count(name): for i in range(1, 50001): print(name, " : ",i) num_list = ['p1','p2','p3','p4'] for num in num_list: count(num) print("---%s seconds ---" % (time.time() - start_time))
print("Введите элементы списка в строку:") num = input() nums = num.split() nums = list(map(int, nums)) n = len(nums) print('nums =', nums) def is_monotonic(nums): i = 1 counter = 0 for i in range(1,n): if min(nums) == nums[0]: if nums[i] >= nums[i-1]: continue else: counter += 1 elif max(nums) == nums[0]: if nums[i] <= nums[i-1]: continue else: counter += 1 else: return False if counter == 0: return True else: return False print(is_monotonic(nums))
#Bài 4. Nhập họ tên, tách họ tên thành 2 phần họ và tên riêng name = str(input('Nhập họ tên: ')) list_name = [] # Thêm các chữ trong họ tên vào một mảng for word in name.split(): if word.isalpha(): list_name.append(word) # Tên sẽ là chữ có vị trí cuối cùng trong mảng vừa tạo print('Họ: ', end = '') for i in range(len(list_name)): if i != len(list_name) - 1: print(list_name[i], end = ' ') else: print() print('Tên riêng: {}'.format(list_name[i]))
# Bài 53. Viết chương trình nhập một ma trận số nguyên có kích thước MxN. In ra: # Tổng các phần tử của ma trận # Số các phần tử dương, phần tử âm, phần tử 0 của ma trận # Phần tử lớn nhất, nhỏ nhất của ma trận # Các phần tử trên đường chéo chính của ma trận (M = N) # Tổng các phần tử trên đường chéo chính của ma trận (M = N) def scan_matrix(): n = 2 matrix = [ [] , [] ] for i in range(2): for j in range(2): n = int(input('[{}][{}] = '.format(i, j))) matrix[i].append(n) return matrix # Tổng các phần tử của ma trận def sum_element(matrix): sum = 0 n = len(matrix) for i in range(n): for j in range(n): sum += matrix[i][j] return sum # Số các phần tử dương, phần tử âm và phần tử 0 của ma trận def count_element(): am = 0 duong = 0 khong = 0 n = len(matrix) for i in range(n): for j in range(n): if (matrix[i][j] > 0): duong += 1 elif (matrix[i][j] < 0): am += 1 else: khong += 1 print('Số phần tử dương của ma trận: ' + str(duong)) print('Số phần tử âm của ma trận: ' + str(am)) print('Số phần 0 của ma trận: ' + str(khong)) # Phần tử lớn nhất, phần tử nhỏ nhất của ma trận def find_element(matrix): min_matrix = 999999 max_matrix = -999999 n = len(matrix) for i in range(n): for j in range(n): if (matrix[i][j] < min_matrix): min_matrix = matrix[i][j] if (matrix[i][j] > max_matrix): max_matrix = matrix[i][j] print('Phần tử nhỏ nhất của ma trận: ' + str(min_matrix)) print('Phần tử lớn nhất của ma trận: ' + str(max_matrix)) # Các phần tử trên đường chéo chính của ma trận (M = N) # Tổng các phần tử trên đường chéo chính của ma trận (M = N) def main_diagonal(matrix): print('Các phần tử trên đường chéo chính của ma trận: ') sum = 0 n = len(matrix) for i in range(n): for j in range(n): if (i == j): print(matrix[i][j], end = ' ') sum +=matrix[i][j] print('\nTổng các phần tử trên đường chéo chính của ma trận: ' + str(sum)) if __name__ == "__main__": matrix = scan_matrix() print(matrix) main_diagonal(matrix)
from gpio import GPIO import time #GPIO.setmode(GPIO.BCM) #GPIO.setup(26,GPIO.OUT) #GPIO.setup(19,GPIO.OUT) #GPIO.setup(13,GPIO.OUT) #GPIO.setup(6,GPIO.OUT) #GPIO.setup(5,GPIO.OUT) #GPIO.setup(11,GPIO.OUT) #GPIO.setup(9,GPIO.OUT) #GPIO.setup(10,GPIO.OUT) #D=[26, 19, 13, 6, 5, 11, 9, 10] D=[0, 1, 2, 3, 4, 5, 6, 7] def num2dac(value): s=[0,0,0,0,0,0,0,0] c = bin(value) m = 7 for n in reversed(c): if n =='b': break elif n == "1": s[m] = 1 else: s[m] = 0 m = m - 1 m = 7 for n in s: if n == 1: GPIO.output(D[m], 1) else: GPIO.output(D[m], 0) m = m - 1 while True: try: number = int(input('Введите число (-1 для выхода):')) 1/(number+1) if number<0 or number>255: number=number+'error' except(ZeroDivisionError): print ('Выход') exit() except(TypeError): print("Число не входит в диапазон") else: num2dac(number) input("для продолжения нажмите enter") finally: for n in D: GPIO.output(n, 0)
import math def isPalindrome(val): if ( len(val) == 1 or len(val) == 0): return 1 elif ( val[:1] == val[len(val)-1:]): return isPalindrome(val[1:len(val)-1]) else: return 0 lrg=0 for i in range(100,999): for j in range(100,999): prod = i * j string = str(prod) if (isPalindrome(string)): if (int(string) > lrg ): lrg = int(string) print lrg
def initializeDict(pat_dict): # Initialize the value to 0 for each key for key in pat_dict.keys(): pat_dict[key] = 0 return pat_dict def initializeList(lst): # Initialize the list to empty for i in range(len(lst)): lst.pop() return lst def leastSubstring(pattern, article): # Use list to store each word of article # In python, can use split function : # art_list = article.split(' ') # Here don't use split function art_list = list() # Split words as spaces start_char_pos = 0 for i in range(len(article)): if article[i] is ' ': end_char_pos = i art_list.append(article[start_char_pos:end_char_pos]) start_char_pos = (i + 1) # In the article end, don't have spaces, only word elif i == len(article)-1: art_list.append(article[start_char_pos:len(article)]) # Create a pattern dictionary and initialize it pat_dict = dict() for char in pattern: pat_dict[char] = 0 # Start: # Create a list to record the start and end position for substring record = list() substr = dict() j = 0 while j < len(art_list): # From the position j to article end start a new poll h = j while h < len(art_list): # Get the don't used word pat = [word for word in pat_dict.keys() if pat_dict[word] == 0] if len(record) == 3: substr[max(record) - min(record)] = (min(record), max(record)) pat_dict = initializeDict(pat_dict) record = initializeList(record) break if art_list[h] in pat: pat_dict[art_list[h]] = 1 record.append(h) h += 1 j += 1 # Get the least sub string start = substr[min(substr.keys())][0] end = substr[min(substr.keys())][1] return ' '.join(art_list[start:end+1]) if __name__ == "__main__": print(leastSubstring(['hello', 'world', 'good'], 'hello world I am a students hello you are good in the world'))
def mergeStringSet(set_list, merge_set_list): used_set = list() set_1 = set_list[0] used_set.append(0) j = 1 while j < len(set_list): count = 0 for char in set_list[j]: if char in set_1: count += 1 if count > 0: for char in set_list[j]: if char not in set_1: set_1.append(char) used_set.append(j) j += 1 merge_set_list.append(set_1) set_list = updateSetList(set_list, used_set) return merge_set_list, set_list def updateSetList(set_list, used_set): used_set = sorted(used_set, reverse=True) for i in used_set: set_list.pop(i) return set_list def main(str_set): # Transfer set to list set_list = list() for i in range(len(str_set)): set_list.append(list(str_set[i])) set_list2 = set_list[:] merge_set_list = list() while len(set_list) != 0: merge_set_list, set_list = mergeStringSet(set_list2, merge_set_list) print(merge_set_list) main([{'aaa', 'bbb', 'ccc'}, {'bbb', 'ddd'}, {'eee', 'fff'}, {'ggg'}, {'ddd', 'hhh'}])
def StringContain(long_str, short_str): # In order to sort it, transfer string to list long_str_list = list(long_str) short_str_list = list(short_str) # Sort list long_str_list.sort() short_str_list.sort() # print(long_str_list, short_str_list) # Polling character from short string to long string long_len = len(long_str_list) short_len = len(short_str_list) for ps in range(short_len): short_chars = short_str_list[ps] pl = 0 while pl < long_len and long_str_list[pl] < short_chars: pl += 1 if pl >= long_len or short_chars > long_str_list[pl]: return False return True if __name__ == "__main__": print(StringContain('ACBD', 'ACB'))
import sys from _collections import deque class Deque(): def __init__(self): self.deque = deque() def push_front(self, num): self.deque.appendleft(num) def push_back(self, num): self.deque.append(num) def pop_front(self): if self.size() == 0: return -1 else: return self.deque.popleft() def pop_back(self): if self.size() == 0: return -1 else: return self.deque.pop() def size(self): return self.deque.__len__() def empty(self): if self.size() == 0: return 1 else: return 0 def front(self): if self.size() == 0: return -1 else: return self.deque[0] def back(self): if self.size() == 0: return -1 else: return self.deque[-1] def print(self): print(self.deque) if __name__ == "__main__": N = int(sys.stdin.readline()) D = Deque() for i in range(N): lst = list(map(str, sys.stdin.readline().split())) if lst[0] == 'push_front': D.push_front(int(lst[1])) elif lst[0] == 'push_back': D.push_back(int(lst[1])) elif lst[0] == 'pop_front': print(D.pop_front()) elif lst[0] == 'pop_back': print(D.pop_back()) elif lst[0] == 'size': print(D.size()) elif lst[0] == 'empty': print(D.empty()) elif lst[0] == 'front': print(D.front()) elif lst[0] == 'back': print(D.back())
# 1. 1000보다 작은 음이 아닌 정수 10개를 입력 받는다. # 2. 입력된 값이 1000보다 작은 음이 아닌 정수가 아닐 경우 다시 입력 받도록 한다. # 3. list 하나를 만들고 입력 받은 수에 42로 나눈 나머지 값을 리스트에 저장한다. # 4. list를 set 집합으로 바꾸어서 중복된 값을 제거한다. # 5. set의 길이를 출력한다. list = [] for i in range(10): while(True): num = int(input()) if (0<= num < 1000): break list.append(num % 42) new_list = set(list) print(len(new_list))
month = input ('Which month? ') valid = True febMonth = False if month == 'january' or month == 'march' or month == 'may' or month == 'july' or month == 'august' or month == 'october' or month == 'december': days = '31' elif month == 'april' or month == 'june' or month == 'september' or month == 'november': days = '30' elif month == 'february': febMonth = True curYear = input ('What year is it? ') if int(curYear) % 4 == 0: leapYr = 'y' if int(curYear) % 100 == 0 and int(curYear) % 400 != 0: leapYr = 'n' else: leapYr = 'n' if leapYr == 'y': days = '29' else: days = '28' else: valid = False if febMonth: print (month + " has " + days + " days in " + str(curYear)) elif valid: print (month + " has " + days + " days") else: print (month + " is not a valid input")
''' Dominic Rochon DNA program COMP1405A - Fall2020 ID: 101195449 I have all the needed functions in here... A+ pls :D ''' def pair (strand): ''' Program checks the inputted letters and assigns matching pair a,A,t,T,c,C,g,G are the valid inputs, A goes with T, and C goes with G lowercase letters are automatically turned into upper case in their pair --- Expected input & output example --- strand = 'aCtGg' print(pair (strand)) ... TGACC ... ''' #Creates string so we can add to it later matchStrand = '' #Checking letters & assigning pair for i in strand: if i == 'a' or i == 'A': match = 'T' elif i == 't' or i == 'T': match = 'A' elif i == 'c' or i == 'C': match = 'G' elif i == 'g' or i == 'G': match = 'C' #Recreate matching strand 1 by 1 adding matchStrand = matchStrand + match return matchStrand def compress (strand): ''' Program compresses a strand into a shorter form A,T,C,G are what the user is supposed to input, but the program would word with any character Program takes repeated letters and shortens it to a number and a letter (the number is how many of those letters there are) The program does not compress single letters (A does not become 1A) --- Expected input & output example --- strand = 'AACCCCTTGAA' print(compress (strand)) ... 2A4C2TG2A ... ''' #Creating string so we can add to it later cStrand = '' i = 0 #while loop runs through length of strand while i < len(strand): num = 1 sameLetter = True while sameLetter: #While loop counts the number of times a certain letter has been repeated if not i + num == len(strand) and strand[i] == strand[i+num]: num += 1 #Num is the number of repitions of a number else: sameLetter = False #Adding to the string, attach a number if a letter is repeated more than once if num > 1: cStrand = cStrand + str(num) + strand[i] else: cStrand = cStrand + strand[i] #i goes up by increments of num to prevent reading letters that have been already read i += num return cStrand def expand(compressedStrand): ''' Program expands a strand into a longer form A user inputs a number, then a letter, and the program prints out that letter the number amount of times Valid inputs are numbers and the letters A,T,C,G although again, this program would work with any characters The program also checks if a number has more than one digit! That was the hardest part for me to do --- Expected input & output example --- strand = '10A2C4G' print(expand (strand)) ... AAAAAAAAAACCGGGG ... ''' eStrand = '' i = 0 #looping through compressed strand while i < len(compressedStrand): num = 1 letterHit = False if compressedStrand[i].isnumeric(): while not letterHit: #This while loop is mainly here to check if the user put in a number longer than 1 digit if compressedStrand[i+num].isnumeric(): num += 1 #num is how many digits of numbers there are else: letterHit = True num = int(compressedStrand[i:i+num]) #num changes to become the actual number before the letter eStrand = eStrand + compressedStrand[i+len(str(num))] * (num - 1) else: eStrand = eStrand + compressedStrand[i] i += len(str(num)) #i goes up by increments of the number of digits in num return eStrand #Leftovers of what I used to test my programs #print(expand("3AT12GA")) #print (compress('AAATTGAA'))
import helper import datetime def count_vowels(word: str): vowels = 0 for i in word: if helper.vowel_check(i): vowels += 1 return vowels def number_of_hits(target, word): count = 0 findPos = 0 while not findPos == -1: findPos = word.find(target) if not findPos == -1: count += 1 word = word[findPos+len(target):] return count def dateFormat(d: str): info = d.split('/') x = datetime.datetime(int(info[2]), int(info[1]), int(info[0])) print(f'{x:%A}, {x:%B} {x:%d}, {x:%Y}') print(f'{x:%Y}/{x:%m}/{x:%d}') print(f'{x:%d}-{x:%m}-{x:%y} ({x:%h})') def dateSlice(d: str): day = d[0:2] month = d[3:5] year = d[6:] shortenedYear = year[2:] print(month + "/" + day + "/" + year) print(year + '/' + month + '/' + day) print(day + '-' + month + '-' + shortenedYear) def dateSplit(d: str): info = d.split('/') day = info[0] month = info[1] year = info[2] print(month + "/" + day + "/" + year) print(year + '/' + month + '/' + day) print(day + '-' + month + '-' + year[2] + year[3]) def main(): #print(count_vowels('Apples')) #dateSlice("14/05/2015") #dateSplit("14/05/2015") # dateFormat("14/05/2015") print(number_of_hits("ok", "okay then I okay dokay cook")) if __name__ == "__main__": # execute only if run as a script main()
# To extract the youtube trailer link of a movie import urllib3 from bs4 import BeautifulSoup import re from mechanize import Browser import json import requests from bs4 import BeautifulSoup from requests import get import pandas as pd from urllib.parse import urlparse import httplib2 import urllib.request import sqlite3 import re import sys def if_webpage_exists(url): requested_web_page = requests.get(url) if (requested_web_page.status_code == 200): return 1 return 0 def extract_data(url): with urllib.request.urlopen(url) as response: contents = response.read() return contents ### To extract the movie trailer page on youtube def get_movie_trailer_page(movie): movie_dup = movie.replace(' ', '+') youtube_link = "https://www.youtube.com/" movie_url = youtube_link + "results?search_query=" + movie_dup return movie_url ### To extract the movie trailer def extract_movie_trailer_link(movie): movie_link_to_be_parsed = get_movie_trailer_page(movie) data = extract_data(movie_link_to_be_parsed) soup = BeautifulSoup(data, features="html5lib") for link in soup.find_all('a'): if ('/watch?v=' in link.get('href')): return "https://www.youtube.com" + link.get('href') #print(extract_movie_trailer_link(sys.argv[1])) def main(): movie = input("Please enter the movie of your choice: \n") result = extract_movie_trailer_link(movie) print('\n' + result) main()
s = "Deeam is a wonderful girl " ss = "is" f = s.find(ss)+len(ss) print(f)
class Foo(object): def __init__(self, func): super(Foo, self).__init__() self._func = func def __call__(self): print('class decorator') self._func() # 类装饰器 @ Foo def bar(): print('I am bar') bar()
movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情'] print('------删除之前------') for tempName in movieName: print(tempName) movieName.pop() print('------删除之后------') for tempName in movieName: print(tempName)
import random # 定义一个列表用来保存3个办公室 offices = [[],[],[]] # 定义一个列表用来存储8位老师的名字 names = ['A','B','C','D','E','F','G','H'] i = 0 for name in names: index = random.randint(0,2) offices[index].append(name) i = 1 for tempNames in offices: print('办公室%d的人数为:%d'%(i,len(tempNames))) i+=1 for name in tempNames: print("%s"%name,end='') print("-"*20)
import random playerInput=input("请输入(0剪刀、1石头、2布:)") player = int(playerInput) computer = random.randint(0, 2) if (player == 0 and computer == 2) or (player == 1 and computer == 0)\ or (player == 2 and computer == 1): print("电脑出的拳头是%s,恭喜,你赢了!"%computer) elif(player == 0 and computer == 0) or (player == 1 and computer == 1)\ or (player == 2 and computer == 2): print("电脑出的拳头是%s,打成平局了!"%computer) else: print("电脑出的拳头是%s你输了,再接再厉!"%computer)
# 批量在文件名前加前缀 import os funFlag = 1 # 1表示添加标志 2表示删除标志 folderName = './' # 获取指定路径的所有文件名字 dirList = os.listdir(folderName) # 遍历输出所有文件名字 for name in dirList: print(name) if funFlag == 1: newName = '[黑马程序员]-' + name elif funFlag == 2: num = len('[黑马程序员]-') newName = name[num:] print(newName) os.rename(folderName+name, folderName+newName)
import time # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 将格式字符串转换为时间戳 a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))
age=30 print("------if判断开始------") if age>=18: print("------我已经成年了-----") print("------if判断结束------")
# 定义类 class Demo: data1 = 100 # 定义为属性data2赋值的方法 def set(self, num): self.data2 = num # 重载方法 def __repr__(self): # 返回自定义的字符串 return 'data1 = %s; data2 = %s'%(self.data1, self.data2) # 创建实例对象 demo = Demo() # 调用方法给属性赋值,并创建属性 demo.set(200) # 调用__repr__方法进行转换 print(demo) print(str(demo)) print(repr(demo))
# 定义类 class Car: # 移动 def move(self): print("车在奔跑...") # 鸣笛 def toot(self): print("车在鸣笛...嘟嘟...") # 创建一个对象,并用变量BMW保存它的引用 BMW = Car() # 添加表示颜色的属性 BMW.color = "黑色" # 调用方法 BMW.move() BMW.toot() # 访问属性 print(BMW.color)