text
stringlengths
37
1.41M
# WAP to accept lower limit and upper limit and print the even and odd numbers between those def oddEven(ll,ul): odd =[] even = [] for x in range (ll,ul): if (x % 2==0): even.append(x) else: odd.append(x) return even,odd ll = int(input("enter the lower limit")) ul = int(input("enter the upper limit")) even, odd = oddEven(ll,ul) print("even = ", even) print ("odd = ", odd)
import json class PingPong: """ This class is for get the person who lose the second game and get the information about his games losed Params **partidos: is dictionary with the games return Print results who lose the second game and json with the game losed in order """ def __init__(self, **partidos): self.partidos = partidos def __ppares(self, n_partidos): """ This a private method is for validate the games :param n_partidos: is a number for minimal games playing :return ppares: is boolean value """ try: if n_partidos % 2 == 0: p_pares = True else: p_pares = False return p_pares except Exception as e: print('An error has occurred for fn ppares: ', e) def __p_perdidos(self, p_pares, t_partidos): """ This a private method is for create a list of games playing for depending of total games playing :param p_pares: is a boolean value for create the list :param t_partidos: is a number of total games :return p_perdidos: is a list with losing games """ try: if p_pares: p_perdidos = [x for x in range(1, int(t_partidos)) if x % 2 == 0] else: p_perdidos = [x for x in range(1, int(t_partidos)) if x % 2 != 0] return p_perdidos except Exception as e: print('An error has occurred in fn p_perdidos: ', e) def segundopartido(self): """ This public method print the player what lose the second game and json with game losed """ # initial variables t_partidos = 0 l_partidos = [] # iter for get the values of dictionary for v in self.partidos.values(): # save values in a list for get the less games played l_partidos.append(v) # sum of total of games for all players t_partidos += v # get the less game played min_partidos = min(l_partidos) # As the pinpong is game of two divide the value of 2 for get the total of games t_partidos = t_partidos/2 # call the function for get if the less match playing, played in the first game o second. p_pares = self.__ppares(min_partidos) # Call function for get the list with the game lose p_perdidos = self.__p_perdidos(p_pares, t_partidos) # iter the value get the name of the player who lose the second game if 2 in p_perdidos: for k, v in self.partidos.items(): if v == min_partidos: perdedor = k break # print results print(f'Who lose the second match is: {perdedor}') # create a dict whith the person who lose the second game with value list of all game losed jsonpartidos = {perdedor: p_perdidos} resultado = json.dumps(jsonpartidos) print(f'resultado: {resultado}') if __name__ == '__main__': juegos = {'Ana': 17, 'José': 15, 'Juan': 10} partido = PingPong(**juegos) partido.segundopartido()
import unittest def binary(num): arr=[0,0,0,0,0,0,0,0] count=7 while num!=0: r=num%2 num=num//2 arr[count]=arr[count]+r count=count-1 # print(arr) return arr def hamming_distance(x,y): x_binary=binary(x) y_binary=binary(y) count=0 # print(x_binary) # print(y_binary) for i in range(0,8): if x_binary[i]!=y_binary[i]: count=count+1 # print(count) return count class Test(unittest.TestCase): def testcase_1(self): actual = hamming_distance(25,30) expected = 3 self.assertEqual(actual, expected) def testcase_2(self): actual = hamming_distance(1,4) expected = 2 self.assertEqual(actual, expected) def testcase_3(self): actual = hamming_distance(25,30) expected = 3 self.assertEqual(actual, expected) def testcase_4(self): actual = hamming_distance(100,250) expected = 5 self.assertEqual(actual, expected) def testcase_5(self): actual = hamming_distance(1,30) expected = 5 self.assertEqual(actual, expected) def testcase_6(self): actual = hamming_distance(0,255) expected = 8 self.assertEqual(actual, expected) unittest.main(verbosity=2)
import unittest def is_valid(string): # Determine if the input code is valid brackets = [] bracket_map = { '(': 0, '{': 0, '[': 0, ')': '(', '}': '{', ']': '[', } for ch in string: if ch in bracket_map: brack = bracket_map[ch] if brack == 0: brackets.append(ch) else: if len(brackets) <= 0: return False top = brackets.pop() if brack != top: return False if len(brackets) == 0: return True return False # Tests class Test(unittest.TestCase): def test_valid_short_code(self): result = is_valid('()') self.assertTrue(result) def test_valid_longer_code(self): result = is_valid('([]{[]})[]{{}()}') self.assertTrue(result) def test_mismatched_opener_and_closer(self): result = is_valid('([][]}') self.assertFalse(result) def test_missing_closer(self): result = is_valid('[[]()') self.assertFalse(result) def test_extra_closer(self): result = is_valid('[[]]())') self.assertFalse(result) def test_empty_string(self): result = is_valid('') self.assertTrue(result) unittest.main(verbosity=2)
import operator def GetCount(List,Map,num): Count=[0]*num temp=0 for val,id in List: if id==1: temp+=1 elif id==3: temp-=1 else: Count[Map[val]]=temp return Count def points_cover(starts, ends, points): Map = {} for index,val in enumerate(points): Map[val]=index List=[(val,1) for val in starts] List+=[(val,2) for val in points] List+=[(val,3) for val in ends] List.sort(key=operator.itemgetter(0,1)) return GetCount(List,Map,len(points)) def main(): data = list(map(int, input().split())) n, m = data[0], data[1] input_starts=[] input_ends=[] for i in range(n): start,end=list(map(int, input().split())) input_starts.append(start) input_ends.append(end) input_points = list(map(int, input().split())) output = points_cover(input_starts, input_ends, input_points) [print(val,end=" ") for val in output] if __name__ == "__main__": main()
# Fractional Knapsack, Greedy Approach def maximum_loot_value(capacity, weights, prices): value=0 temp={} for i in range(len(prices)): temp[i] = (prices[i]/weights[i]) # Per unit value of each item while capacity>0: x = max(temp, key=temp.get) # Choose Item of Max per unit value amount = min(weights[x],capacity) value+= amount*temp[x] capacity-=amount temp[x]=0 return value if __name__ == "__main__": input_capacity = eval(input()) input_weights = list(map(eval,input().split())) input_prices = list(map(eval,input().split())) opt_value = maximum_loot_value(input_capacity, input_weights, input_prices) print("{:.10f}".format(opt_value))
import json import random import time from sort_algorithms import selection_sort, insertion_sort, shell_sort, start_merge_sort def generate_array(numbers_array, n_experiment, len_array): """ :param numbers_array: a list of numbers from 0 to pow(2, 15) to save time on creating random lists, instead every time generate random number I use random.sample from this numbers_array :param n_experiment: a number of experiment to understand what type of array to return :param len_array: a length of returned array :return: a random array with len_array length """ array = [] if n_experiment == 1: # get an array of len_array length randomly chosen elements # from numbers_array array = random.sample(numbers_array, k=len_array) elif n_experiment == 2: # get an array of len_array length from 0 to len_array # in numbers_array array = numbers_array[:len_array] elif n_experiment == 3: # get an array of len_array length from 0 to len_array # in numbers_array and reverse it array = numbers_array[:len_array] array.reverse() elif n_experiment == 4: # shuffle elements of previous array fro fourth experiment random.shuffle(numbers_array) return array def compare_algorithms_time(): """ :return: save a json with all experiments data, format is such: "experiment1": { "selection_sort": { "array_size": [], "algorithm_time": [], "algorithm_if_operations": [] }, "insertion_sort": { "array_size": [], "algorithm_time": [], "algorithm_if_operations": [] } ... "experiment2": {.... """ # start power - a minimum length of array to sort # end power - a maximum length of array to sort start_pow = 5 end_pow = 15 end_len_array = pow(2, end_pow) numbers_array = [i for i in range(end_len_array)] # create array123 of {1, 2, 3} repeated elements one_third_len = end_len_array // 3 array1 = [1 for _ in range(one_third_len)] array2 = [2 for _ in range(one_third_len)] array3 = [3 for _ in range(end_len_array - 2 * one_third_len)] array123 = array1 + array2 + array3 # create len_arrays of length of arrays for cycle len_arrays = [] for i in range(start_pow, end_pow + 1): len_arrays.append(pow(2, i)) algorithms_names = ["selection_sort", "insertion_sort", "merge_sort", "shell_sort"] # create a structure of result json of data for experiments experiments_data_dict = dict() for n_experiment in range(1, 5): algorithms_data_dict = dict() for i, algo in enumerate(algorithms_names): algorithms_data_dict[algo] = { "array_size": len_arrays, "algorithm_time": [0 for _ in range(end_pow - start_pow + 1)], "algorithm_if_operations": [0 for _ in range(end_pow - start_pow + 1)] } experiments_data_dict["experiment" + str(n_experiment)] = algorithms_data_dict for n_experiment in range(1, 5): # a variable to save position length of a current array # to get it from len_arrays to save the result of experiment # on certain position in result json step_len_array = 0 for len_array in len_arrays: print("len_array", len_array) print("n_experiment", n_experiment) # a variable to repeat experiments 1th and 4th make_experiments = 1 if n_experiment == 1: make_experiments = 5 elif n_experiment == 4: make_experiments = 3 array = [] # dicts to save time of each repeated experiment and after to get mean value of it algo_times_dict = { 0: [], 1: [], 2: [], 3: [] } algo_if_operations_dict = { 0: [], 1: [], 2: [], 3: [] } for i in range(make_experiments): if n_experiment == 4: if i == 0: array = random.sample(array123, k=len_array) else: # for 4th experiment after first repetition of experiment we should # shuffle the same elements of first array generate_array(array, n_experiment, len_array) else: array = generate_array(numbers_array, n_experiment, len_array) algo_time, if_operations = 0, 0 time_difference = 0 for n_algorithm in range(1, 5): if n_algorithm == 1: start_time = time.perf_counter() if_operations = selection_sort(array) time_difference = time.perf_counter() - start_time print("Selection sort time", time_difference) elif n_algorithm == 2: start_time = time.perf_counter() if_operations = insertion_sort(array) time_difference = time.perf_counter() - start_time print("Insertion sort time", time_difference) elif n_algorithm == 3: start_time = time.perf_counter() if_operations = start_merge_sort(array, if_operations) time_difference = time.perf_counter() - start_time print("Merge sort time", time_difference) elif n_algorithm == 4: start_time = time.perf_counter() if_operations = shell_sort(array) time_difference = time.perf_counter() - start_time print("Shell sort time", time_difference, '\n\n\n\n') algo_times_dict[n_algorithm - 1].append(time_difference) algo_if_operations_dict[n_algorithm - 1].append(if_operations) # add mean variable of all repetitions of the experiment to result json for n_algo_name in range(4): experiments_data_dict["experiment" + str(n_experiment)][algorithms_names[n_algo_name]]["algorithm_time"][step_len_array] \ = sum(algo_times_dict[n_algo_name]) / len(algo_times_dict[n_algo_name]) experiments_data_dict["experiment" + str(n_experiment)][algorithms_names[n_algo_name]]["algorithm_if_operations"][step_len_array] \ = sum(algo_if_operations_dict[n_algo_name]) / len(algo_if_operations_dict[n_algo_name]) step_len_array += 1 with open("algorithms_data.json", "w", encoding="utf-8") as f: json.dump(experiments_data_dict, f, indent=4, ensure_ascii=False) if __name__ == '__main__': compare_algorithms_time()
#Unix/Linux操作系统提供了一个fork()系统调用 #它非常特殊。普通的函数调用,调用一次,返回一次,但是fork()调用一次,返回两次 #因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程) #然后,分别在父进程和子进程内返回 import os print('Process (%s) start...' % os.getpid()) # Only works on Unix/Linux/Mac: pid = os.fork() if pid == 0:#如果返回0(子进程永远返回0,而父进程返回子进程的ID) print('I am child process (%s) and my dad is %s.' % (os.getpid(), os.getppid())) else: print('I (%s) just created a child process (%s).' % (os.getpid(), pid)) #子进程只需要调用getppid()就可以拿到父进程的ID #我是dad是getpid,我儿子就是pid #我是儿子getpid,我dad就是getppid #!!!!!windows玩不了fork,呵呵呵!欺负穷逼!拜拜了您!
#在Python中,读写文件这样的资源要特别注意,必须在使用完毕后正确关闭它们。 #正确关闭文件资源的一个方法是使用try...finally: try: f = open('/path/to/file', 'r') f.read() finally: if f: f.close() #写try...finally非常繁琐。 #Python的with语句允许我们非常方便地使用资源,而不必担心资源没有关闭, #所以上面的代码可以简化为: with open('/path/to/file', 'r') as f: f.read()
#Python的标准库提供了两个模块:_thread和threading, #_thread是低级模块,threading是高级模块,对_thread进行了封装。 #绝大多数情况下,我们只需要使用threading这个高级模块 #启动线程 import time, threading # 新线程执行的代码: def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n = n + 1 print('thread %s >>> %s' % (threading.current_thread().name, n)) time.sleep(1) print('thread %s ended.' % threading.current_thread().name) print('thread %s is running...' % threading.current_thread().name) t = threading.Thread(target=loop, name='LoopThread') t.start() t.join() print('thread %s ended.' % threading.current_thread().name) #由于任何进程默认就会启动一个线程,我们把该线程称为主线程, #主线程又可以启动新的线程,Python的threading模块有个current_thread()函数, #它永远返回当前线程的实例。 #主线程实例的名字叫MainThread, #子线程的名字在创建时指定,我们用LoopThread命名子线程。 #名字仅仅在打印时用来显示,完全没有其他意义, #如果不起名字Python就自动给线程命名为Thread-1,Thread-2……
#允许对Student实例添加name和age属性 class Student(object): __slots__ = ('name', 'age') >>> s = Student() # 创建新的实例 >>> s.name = 'Michael' # 绑定属性'name' >>> s.age = 25 # 绑定属性'age' >>> s.score = 99 # 绑定属性'score' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'score' #slots狭缝,缝外的一律对calss 类不管用!!!
#filter,和map类似,也接受一个函数和一个序列 #把传入的函数依次作用于每个元素,根据返回值是True还是False决定保留还是丢弃 #保留奇数,过滤掉偶数 def must_odd(n): return n % 2 == 1 print(list(filter(must_odd,[1,2,3,4,5,6,7,8,9]) ) ) #1%2 的意思是求1除以2得到的余数,而1除以2 = 0 余1 所以 1%2是1 #把list中的元素代入must_odd中,1,3,5,7,9 %2都余1,返回值为True,保留 #2,4,6,8 %2余0,返回值为Fales,丢弃 #去掉空字符串 def not_empty(q): return q and q.strip() #经过q and q.strip()还有值的就返回True,是空的字符串的就就False print(list(filter(not_empty,['A','b','',' ',None,' jiang']) ) )
#Class responsible recording the video and storing it in a specified location. import cv2; import numpy as np; from videocamera import CameraClass; ''' # setDriveLocation: set the path where video will be stored. # getDriveLocation: get the path where video will be stored. # setpreferedFormat: format in which video is to recorded. # setpreferedFormat: format in which video is recorded. # starRecording: initiates the camera and starts recording. ''' class RecordVideo(CameraClass): def __init__(self,url,vFormat): #super(RecordVideo, self).__init__(0,"mp4"); self.driveLocation=url; self.preferedFormat=vFormat; def setDriveLocation(self,url): self.driveLocation=url; def getDriveLocation(self): return self.driveLocation; def setPreferedFormat(self,vFormat): self.preferedFormat=vFormat; def getPreferedFormat(self): return self.preferedFormat; def startRecording(self): CameraClass.startCamera(0); #Input path and video type print "Enter the location where you want to store the video:"; path=raw_input('---->'); print "Enter the format of video:"; vFormat=raw_input('---->'); #Create an object. RV=RecordVideo(path,vFormat); RV.startRecording();
# Reference: https://leetcode.com/problems/palindrome-number/ # Sequence = 9. Palindrome Number # Prepared by - Maddy Rai import time class Solution: def isPalindrome(self, x): if x not in range(-2**31, 2**31): raise Exception("Input number is out of range.") return str(x) == str(x)[::-1] x = 2 tic = time.perf_counter() result = Solution.isPalindrome(None, x) toc = time.perf_counter() print(f"Time taken = {toc - tic:0.8f} seconds") print(result) # Testcases print("----Starting Testcases-----") print('Pass') if Solution.isPalindrome(None, -121) is False else print('Failed') print('Pass') if Solution.isPalindrome(None, 10) is False else print('Failed') print('Pass') if Solution.isPalindrome(None, -101) is False else print('Failed!!') print('Pass') if Solution.isPalindrome(None, 123321) is True else print('Failed!!')
# Reference: https://leetcode.com/problems/shuffle-the-array/ # Sequence = 1470. Shuffle the Array # Prepared by - Maddy Rai import time class Solution: def shuffle(self, nums, n): if n not in range(1, 501): raise Exception("n is out of range.") if len(nums) != 2*n: raise Exception("Unexpected size of input list.") if (min(nums) < 1) or (max(nums) > 1000): raise Exception("Min or Max values exceed the desired range.") lsans = len(nums) * [None] for i in range(0, n): lsans[i*2] = nums[i] lsans[i*2+1] = nums[n] n += 1 return lsans nums = [1,2,3,4,5,6,7,8,9,10] n = 5 tic = time.perf_counter() result = Solution.shuffle(None, nums, n) toc = time.perf_counter() print(f"Time taken = {toc - tic:0.8f} seconds") print(result)
# Reference: https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/ # Sequence = 1880. Check if Word Equals Summation of Two Words # Prepared by - Maddy Rai import time class Solution: def isSumEqual(self, firstWord, secondWord, targetWord): if len(firstWord) not in range(1, 9) or len(secondWord) not in range(1, 9) or len(targetWord) not in range(1, 9): raise Exception("Unexpected length of inputs.") dictm = {'a': '0', 'b': '1', 'c': '2', 'd': '3', 'e': '4', 'f': '5', 'g': '6', 'h': '7', 'i': '8', 'j': '9'} s1 = ''.join([dictm[i] for i in firstWord]) s2 = ''.join([dictm[i] for i in secondWord]) s3 = ''.join([dictm[i] for i in targetWord]) if (int(s1) + int(s2)) == int(s3): return True else: return False firstWord = "acb" secondWord = "cba" targetWord = "cdb" tic = time.perf_counter() result = Solution.isSumEqual(None, firstWord, secondWord, targetWord) toc = time.perf_counter() print(f"Time taken = {toc - tic:0.8f} seconds") print(result)
import ctypes from time import time class DynamicArray: def __init__(self): self._n = 0 self._capacity = 1 self._A = self._make_array(self._capacity) def __len__(self): return self._n def __getitem__(self,k): if not 0 <= k < self._n: raise IndexError('invalid index') return self._A[k] def append(self,obj): if self._n == self._capacity: self._resize(2*self._capacity) self._a[self._n] = obj self._n += 1 def _resize(self,c): B = self._make_array(c) for k in range(self._n): B[k] = self._A[k] self._A = B self._capacity = c def _make_array(self,c): return (c*ctypes.py_object)() def compute_average(n): data = [] start = time() for k in range(n): data.append(None) end = time() A = [3,5,19,2,7,13,17] def insertion_sort(A): for k in range(1,len(A)): cur = A[k] j = k while j > 0 and A[j-1] > cur: A[j] = A[j-1] j -= 1 A[j] = cur
import requests from bs4 import BeautifulSoup import smtplib # This program looks at a raspberry pi camera and # emails me if the price has fallen below a certain amount # https://www.youtube.com/watch?v=Bg9r_yLk7VY&t=330s&ab_channel=DevEd URL = 'https://www.amazon.com/Raspberry-Camera-Vision-IR-Cut-Longruner/dp/B07R4JH2ZV/ref=sr_1_6?dchild=1&keywords=raspberry+pi+camera&qid=1603577903&sr=8-6' response = requests.get(URL) headers = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'} def check_price(): try: page = requests.get(URL, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') title = soup.find(id='productTitle').get_text() price = soup.find(id='priceblock_ourprice').get_text() # converts to float and only shows first 5 characters. It starts at the 1 index because the dollar sign cannot be converted to a float string_price_to_float = float(price[1:5]) print(title.strip()) print(price.strip()) print(f"Here is the price in float form: {string_price_to_float}") if string_price_to_float < 23: send_mail() else: print("price has not dropped") except AttributeError: pass def send_mail(): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login('[email protected]', 'vnjqtzgmqrzuqgua') subject = 'Price fell down!' body = 'Check the link! \n https://www.amazon.com/Raspberry-Camera-Vision-IR-Cut-Longruner/dp/B07R4JH2ZV/ref=sr_1_6?dchild=1&keywords=raspberry+pi+camera&qid=1603577903&sr=8-6' msg = f"Subject: {subject}\n\n{body}" server.sendmail( '[email protected]', '[email protected]', msg ) print('Email has been sent!') server.quit() check_price() # while(True): if I want it to continually run and check once a day, I can uncomment this out and get rid of the check_price() call on line 57 # check_price() # time.sleep(86400)
# Now, Dasher! Now, Dancer! Now, Prancer, and Vixen! On, Comet! On, Cupid! On, # Donder and Blitzen! That's the order Santa wanted his reindeer...right? # What do you mean he wants them in order by their last names!? Looks like we need your help! # Write a function that accepts a sequence of Reindeer names, # and returns a sequence with the Reindeer names sorted by their last names. # Example # for this input: # [ # "Dasher Tonoyan", # "Dancer Moore", # "Prancer Chua", # "Vixen Hall", # "Comet Karavani", # "Cupid Foroutan", # "Donder Jonker", # "Blitzen Claus" # ] # you should return this output: # [ # "Prancer Chua", # "Blitzen Claus", # "Cupid Foroutan", # "Vixen Hall", # "Donder Jonker", # "Comet Karavani", # "Dancer Moore", # "Dasher Tonoyan", # ] # Tests # sort_reindeer(['Kenjiro Mori', 'Susumu Tokugawa', 'Juzo Okita', 'Akira Sanada']), # ['Kenjiro Mori', 'Juzo Okita', 'Akira Sanada', 'Susumu Tokugawa']) # sort_reindeer(['Yasuo Kodai', 'Kenjiro Sado', 'Daisuke Aihara', 'Susumu Shima', 'Akira Sanada', # 'Yoshikazu Okita', 'Shiro Yabu', 'Sukeharu Nanbu', 'Sakezo Yamamoto', 'Hikozaemon Ohta', # 'Juzo Mori', 'Saburo Tokugawa']), # ['Daisuke Aihara', 'Yasuo Kodai', 'Juzo Mori', 'Sukeharu Nanbu', # 'Hikozaemon Ohta', 'Yoshikazu Okita', 'Kenjiro Sado', 'Akira Sanada', # 'Susumu Shima', 'Saburo Tokugawa', 'Shiro Yabu', 'Sakezo Yamamoto']) def sort_reindeer(reindeer : list) -> list: return sorted(reindeer, key=lambda x : x.split()[-1]) print(sort_reindeer([ "Dasher Tonoyan", "Dancer Moore", "Prancer Chua", "Vixen Hall", "Comet Karavani", "Cupid Foroutan", "Donder Jonker", "Blitzen Claus" ]))
# The function is not returning the correct values. Can you figure out why? # def get_planet_name(id): # This doesn't work; Fix it! # name="" # switch id: # case 1: name = "Mercury" # case 2: name = "Venus" # case 3: name = "Earth" # case 4: name = "Mars" # case 5: name = "Jupiter" # case 6: name = "Saturn" # case 7: name = "Uranus" # case 8: name = "Neptune" # return name # Example # get_planet_name(3) # should return 'Earth' # Tests # get_planet_name(3) # get_planet_name(8) # get_planet_name(1) # get_planet_name(5) def get_planet_name(id): return ( { 1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars", 5: "Jupiter", 6: "Saturn", 7: "Uranus" , 8: "Neptune" } ).get(id, "Not valid id") print(get_planet_name(3)) # output -> Earth print(get_planet_name(8)) # output -> Neptune print(get_planet_name(1)) # output -> Mercury print(get_planet_name(0)) # output -> Not valid id
#Python orbital visualizer. By M. Ewers, P. Brabant, I. Laurent, P. Jermann and F. Meyer. 2021. # Our goal is to draw a 3D representation of a few orbitals # we import packages we need for our program import numpy # we use numpy in order to use mathematical tools depending on x, y, z from mayavi import mlab # we use mlab in order to draw our orbitals import matplotlib import matplotlib.pyplot as plt # We import all the modules we need to use in order to draw the graph (probability) import sys a0=0.52 # we define the Bohr radius A="Orbital group, for example 3d" print("This program displays the orbital shape as well as the most probable distance between the electron and the nuclei for a chosen orbital in the hydrogen atom.") name = input("Which orbital do you wish to visualize? Please enter the name of the orbital: ") # the user chooses the orbital he wants to draw # We define the spherical coordinates r, theta, phi depending on x, y, z r = lambda x,y,z: numpy.sqrt(x**2+y**2+z**2) theta = lambda x,y,z: numpy.arccos(z/r(x,y,z)) phi = lambda x,y,z: numpy.arctan(y/x) # We create a library of each equation we need to draw the different orbitals # Each section contains the radial part of the solution to the schrodinger equation, the wavefunction and the probability of presence for a given orbital. #1s rad1s = lambda r:((1/a0)**(3/2))*2*numpy.exp(-(r/a0)) WF1s = lambda r,theta,phi: rad1s(r)*(1./(numpy.sqrt(4*numpy.pi))) Prob1s = lambda r,theta,phi: abs(WF1s(r,theta,phi)**2) #2s rad2s = lambda r:((1/a0)**(3/2))*(1/(2*numpy.sqrt(2)))*(2-(r/a0))*numpy.exp(-(r/(2*a0))) WF2s = lambda r,theta,phi: rad1s(r)*(1./(numpy.sqrt(4*numpy.pi))) Prob2s = lambda r,theta,phi: abs(WF1s(r,theta,phi)**2) #2py rad2py = lambda r:((1/a0)**(3/2))*(1/(2*numpy.sqrt(6)))*(r/a0)*numpy.exp(-(r/(2*a0))) WF2py = lambda r,theta,phi: rad2py(r)*(numpy.sqrt(3/(4*numpy.pi))*numpy.sin(theta))*numpy.sin(phi) Prob2py = lambda r,theta,phi: abs(WF2py(r,theta,phi)**2) #2px rad2px = lambda r:((1/a0)**(3/2))*(1/(2*numpy.sqrt(6)))*(r/a0)*numpy.exp(-(r/(2*a0))) WF2px = lambda r,theta,phi: rad2px(r)*(numpy.sqrt(3/(4*numpy.pi))*numpy.sin(theta))*numpy.cos(phi) Prob2px = lambda r,theta,phi: abs(WF2px(r,theta,phi)**2) #2pz rad2pz = lambda r:((1/a0)**(3/2))*(1/(2*numpy.sqrt(6)))*(r/a0)*numpy.exp(-(r/(2*a0))) WF2pz = lambda r,theta,phi: rad2pz(r)*(numpy.sqrt(3/(4*numpy.pi))*numpy.cos(theta)) Prob2pz = lambda r,theta,phi: abs(WF2pz(r,theta,phi)**2) #3s rad3s = lambda r:((1/a0)**(3/2))*(1/(9*numpy.sqrt(3)))*(6-((4*r)/a0)+((4*r**2)/9*a0**2))*numpy.exp(-(r/(3*a0))) WF3s = lambda r,theta,phi: rad3s(r)*(numpy.sqrt(1/(4*numpy.pi))) Prob3s = lambda r,theta,phi: abs(WF3s(r,theta,phi)**2) #3pz rad3pz = lambda r:((1/a0)**(3/2))*(1/(9*numpy.sqrt(6)))*((2*r)/(3*a0))*(4-((2*r)/(3*a0)))*numpy.exp(-(r/(3*a0))) WF3pz = lambda r,theta,phi: rad3pz(r)*(numpy.sqrt(3/(4*numpy.pi))*numpy.cos(theta)) Prob3pz = lambda r,theta,phi: abs(WF3pz(r,theta,phi)**2) #3dz2 rad3dz2 = lambda r:((1/a0)**(3/2))*(1/(9*numpy.sqrt(30)))*((4*r**2)/(9*a0**2))*numpy.exp(-(r/(3*a0))) WF3dz2 = lambda r,theta,phi: rad3dz2(r)*(numpy.sqrt(5/(16*numpy.pi))*(3*(numpy.cos(theta)**2)-1)) Prob3dz2 = lambda r,theta,phi: abs(WF3dz2(r,theta,phi)**2) #3dxy rad3dxy = lambda r:((1/a0)**(3/2))*(1/(9*numpy.sqrt(30)))*((4*(r**2))/(9*(a0**2)))*numpy.exp(-(r/(3*a0))) WF3dxy = lambda r,theta,phi: rad3dxy(r)*(numpy.sqrt(5/(16*numpy.pi))*((numpy.sin(theta))**2)*numpy.sin(2*phi)) Prob3dxy = lambda r,theta,phi: abs(WF3dxy(r,theta,phi)**2) #3dxz rad3dxz = lambda r: ((1/a0)**(3/2))*(1/(9*numpy.sqrt(30)))*(4*(r**2)/9*(a0**2))*numpy.exp(-(r/(3*a0))) WF3dxz = lambda r,theta,phi: rad3dxz(r)*(numpy.sqrt(5/(16*numpy.pi))*numpy.cos(phi)*numpy.sin(2*theta)) Prob3dxz = lambda r,theta,phi: abs(WF3dxz(r,theta,phi)**2) #3dyz rad3dyz = lambda r: ((1/a0)**(3/2))*(1/(9*numpy.sqrt(30)))*((4*(r**2))/(9*(a0**2)))*numpy.exp(-(r/(3*a0))) WF3dyz = lambda r,theta,phi: rad3dyz(r)*(numpy.sqrt(5/(16*numpy.pi))*((numpy.sin(theta))*numpy.sin(phi)*numpy.cos(theta))) Prob3dyz = lambda r,theta,phi: abs(WF3dyz(r,theta,phi)**2) #3dx2y2 rad3dx2y2 = lambda r:((1/a0)**(3/2))*(1/(9*numpy.sqrt(30)))*((4*r**2)/9*a0**2)*numpy.exp(-(r/(3*a0))) WF3dx2y2 = lambda r,theta,phi: rad3dx2y2(r)*(numpy.sqrt(5/(16*numpy.pi))*(numpy.sin(theta))**2*numpy.cos(2*phi)) Prob3dx2y2 = lambda r,theta,phi: abs(WF3dx2y2(r,theta,phi)**2) #we define the grid on which we want to draw the orbitals with one hundred steps x,y,z = numpy.ogrid[-10:10:100j,-10:10:100j,-10:10:100j] # we create the figure mlab.figure() mask = 1 # We draw the orbital that the user chose by checking the input. We allocate a value to w which wil help in the visualization # and A which will help for the probability graph if name == "1s": w=Prob1s(r(x,y,z),theta(x,y,z),phi(x,y,z)) A="1s" elif name == "2s": w=Prob2s(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "2s" elif name == "2py": w=Prob2py(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "2p" elif name == "2px": w=Prob2px(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "2p" elif name == "2pz": w=Prob2pz(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "2p" elif name == "3s": w=Prob3s(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "3s" elif name == "3pz": w=Prob3pz(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "3p" elif name == "3dz2": w=Prob3dz2(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "3d" elif name == "3dxy": w=Prob3dxy(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "3d" elif name == "3dxz": w=Prob3dxz(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "3d" elif name == "3dyz": w=Prob3dyz(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "3d" elif name == "3dx2y2": w=Prob3dx2y2(r(x,y,z),theta(x,y,z),phi(x,y,z)) A = "3d" else: # If the input doesn't match with any of the orbitals the program stops to prevent an error print("Please restart the program and enter a valid orbital name") sys.exit() # We apply the orbital's mathematical description to the mask in order to draw it. mlab.contour3d(w*mask,contours=20,transparent=False) #We take a few extra steps and "voilà" the orbital shows itself mlab.colorbar() mlab.outline() mlab.show() # We create a new library of functions that correspond to the radial def radial1s(x,y,z): r=numpy.sqrt(x**2+y**2+z**2) a0=5.29 R=(1/a0)**(3/2)*2*numpy.exp(-r/a0) return(R) def radial2s(x,y,z) : r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) a0 = 5.29 R = (1/a0) ** (3/2) * (1/ (2 * numpy.sqrt(2))) * (2 - (r / a0)) * numpy.exp(-r / (2 * a0)) return (R) def radial2p(x, y,z) : r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) a0 = 5.29 R = (1 / a0) ** (3 / 2) * (1 / (2 * numpy.sqrt(6))) * (r / a0) * numpy.exp(-r / (2 * a0)) return (R) def radial3s(x, y,z) : r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) a0 = 5.29 R = ((1 / a0) ** (3 / 2)) * (1 / (9 * numpy.sqrt(3))) * (6 - (4 * r / a0) + (4* r**2 / (9 * a0 **2))) * numpy.exp(-r / (3 * a0)) return (R) def radial3pz(x, y,z) : r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) a0 = 5.29 R = ((1 / a0) ** (3 / 2)) * (1 / (9 * numpy.sqrt(6))) * (2 * r /3 * a0) * (4 - 2 * r / (3 * a0)) * numpy.exp(-r / (3 * a0)) return (R) def radial3d(x, y,z) : r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) a0 = 5.29 R = (1 / a0) ** (3 / 2) * (1 / (9 * numpy.sqrt(30))) * (4 * r**2 /9 * a0**2) * numpy.exp(-r / (3 * a0)) return (R) # we create a grid in order to be able to make a graph, so we define the coordinates and the axis dz = 0.5 zmin = 0 zmax = 50 x = numpy.arange(zmin, zmax, dz) y = numpy.arange(zmin, zmax, dz) z = numpy.arange(zmin, zmax, dz) X, Y, Z = numpy.meshgrid(x, y, z) # we start a loop of "if" related to the orbital chosen by the user # according to the chosen orbital, it will plot the right graph representing the most probable distance between the electron and the nucleus if A == "1s" : R = radial1s(x,y,z) a0 = 5.29 r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) graphX = r / a0 graphY = (R ** 2) * (r ** 2) * a0 plt.title("Probability density of the radial presence times a0 depending on r/a0") plt.xlabel("r/a0") plt.ylabel("a0Dr") plt.plot(graphX, graphY) ymax = numpy.max(graphY) xmax = graphX[numpy.argmax(graphY)] print("xmax =", xmax, "a0") plt.scatter(xmax, ymax) plt.text(xmax, ymax, " Maximum probability distance : 0.9822594371846185 a0 ") plt.show() matplotlib.pyplot.close() elif A == "2s": R = radial2s(x,y,z) a0 = 5.29 r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) graphX = r / a0 graphY = (R ** 2) * (r ** 2) * a0 plt.title("Probability density of the radial presence times a0 depending on r/a0") plt.xlabel("r/a0") plt.ylabel("a0Dr") plt.plot(graphX, graphY) ymax = numpy.max(graphY) xmax = graphX[numpy.argmax(graphY)] print("xmax =", xmax, "a0") plt.scatter(xmax, ymax) plt.text(xmax, ymax, "Maximum probability distance : 5.238716998317965 a0 ") plt.show() matplotlib.pyplot.close() elif A == "2p": R = radial2p(x,y,z) a0 = 5.29 r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) graphX = r / a0 graphY = (R ** 2) * (r ** 2) * a0 plt.title("Probability density of the radial presence times a0 depending on r/a0") plt.xlabel("r/a0") plt.ylabel("a0Dr") plt.plot(graphX, graphY) ymax = numpy.max(graphY) xmax = graphX[numpy.argmax(graphY)] print("xmax =", xmax, "a0") plt.scatter(xmax, ymax) plt.text(xmax, ymax, "Maximum probability distance : 3.929037748738474 a0 ") plt.show() matplotlib.pyplot.close() elif A == "3s": R = radial3s(x,y,z) a0 = 5.29 r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) graphX = r / a0 graphY = (R ** 2) * (r ** 2) * a0 plt.title("Probability density of the radial presence times a0 depending on r/a0") plt.xlabel("r/a0") plt.ylabel("a0Dr") plt.plot(graphX, graphY) ymax = numpy.max(graphY) xmax = graphX[numpy.argmax(graphY)] print("xmax =", xmax, "a0") plt.scatter(xmax, ymax) plt.text(xmax, ymax, " Maximum probability distance : 13.096792495794915 a0 ") plt.show() matplotlib.pyplot.close() elif A == "3p": R = radial3pz(x,y,z) a0 = 5.29 r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) graphX = r / a0 graphY = (R ** 2) * (r ** 2) * a0 plt.title("Probability density of the radial presence times a0 depending on r/a0") plt.xlabel("r/a0") plt.ylabel("a0Dr") plt.plot(graphX, graphY) ymax = numpy.max(graphY) xmax = graphX[numpy.argmax(graphY)] print("xmax =", xmax, "a0") plt.scatter(xmax, ymax) plt.text(xmax, ymax, " Maximum probability distance : 11.950823152412857 a0 ") plt.show() matplotlib.pyplot.close() elif A == "3d": R = radial3d(x,y,z) a0 = 5.29 r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2) graphX = r / a0 graphY = (R ** 2) * (r ** 2) * a0 plt.title("Probability density of the radial presence times a0 depending on r/a0") plt.xlabel("r/a0") plt.ylabel("a0Dr") plt.plot(graphX, graphY) ymax = numpy.max(graphY) xmax = graphX[numpy.argmax(graphY)] print("xmax =", xmax, "a0") plt.scatter(xmax, ymax) plt.text(xmax, ymax, "Maximum probability distance : 9.004044840859002 a0 ") plt.show() matplotlib.pyplot.close()
import sys print(sys.maxsize) print(sys.float_info.max) #Guys this is way of max limit of any float or int value cn1 = 7 + 3j cn2 = 8 + 2j cn = (cn1 + cn2)*(- 1) print(cn) # ya guys the above example was for operation of complex numbers
def allowed_dating_age(my_age): girls_age = my_age/2 + 10 return girls_age Buckys_limit = allowed_dating_age(27) print("Bucky can date girls",Buckys_limit,"or older") # now we gonna do some multiple exampples Rahuls_limit = allowed_dating_age(15) print("Rahul can date girls",Rahuls_limit,"or older") sandys_limit = allowed_dating_age(75) print("sandy can date girls",sandys_limit,"or older")
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() charlotte = { "id": 6, "name": "Charlotte", "children": [] } harrison = { "id": 5, "name": "Harrison", "children": [] } harry = { "id": 4, "name": "Harry", "children": [harrison] } william = { "id" : 3, "name" : "William", "children": [charlotte] } charles = { "id": 2, "name": "Charles", "children": [william, harry] } elizabeth = { "id": 1, "name": "Elizabeth", "children": [charles] } new_list = [] def list_all(parent): # your code goes here for child in parent["children"]: new_list.append(child) return list_all(child) return new_list def find_one(parent, id): print("for loop initiated with " + parent["name"]) for child in parent["children"]: print("testing for " + child["name"] + " with id " + str(child["id"]) + "==" + str(id)) if child["id"] == id: print("if statement initiated") return child print("Not the id that we want, moving on") return find_one(child, id) # print(find_one(elizabeth, 6))
# USE RANGE def fizz_buzz(numbers): # I think that you need to use range and len here so that when it iterates through it keeps the list. if you just use for i in numbers, it will return the values as individuals for i in range(len(numbers)): num=numbers[i] if num %3 ==0: numbers[i]="fizz" if num %5 ==0: numbers[i]="buzz" if num %3 ==0 and num % 5==0: numbers[i]="fizzbuzz" numbers=[45,22,14,65,97,72] fizz_buzz(numbers) numbers #USE ENUMERATE enumerate allows you to iterate through a list AND its indicies returning a tuple def fizz_buzz(numbers): # I think that you need to use range and len here so that when it iterates through it keeps the list. if you just use for i in numbers, it will return the values as individuals breakpoint() for i, num in enumerate(numbers): num=numbers[i] if num %3 ==0: numbers[i]="fizz" if num %5 ==0: numbers[i]="buzz" if num %3 ==0 and num % 5==0: numbers[i]="fizzbuzz" numbers=[45,22,14,65,97,72] fizz_buzz(numbers) numbers
## USE PARAMETERIZED QUERIES TO INSERT DATA - NAMED PLACEHOLDERS # New data is stored in variables and is inserted into the query strings using parameters # Results are gethered by the row and are printed by using list locations import sqlite3 as lite import sys uId = 4 con = lite.connect('test.db') with con: cur = con.cursor() cur.execute("SELECT Name, Price FROM Cars WHERE Id = :Id", {"Id": uId}) con.commit() row = cur.fetchone() print row[0], row[1]
## CREATES AND INSERTS DATA INTO DATABASE # Assigns all data to be inserted into a list of tuples # Table is destroyed if already exists and new one created # executemany is used to insert all data from 'cars' list by using a parameterized string import sqlite3 as lite import sys cars = ( (1, 'Audi', 52642), (2, 'Mercedes', 57127), (3, 'Skoda', 9000), (4, 'Volvo', 29000), (5, 'Bentley', 350000), (6, 'Citroen', 21000), (7, 'Hummer', 41400), (8, 'Volkswagen', 21600) ) con = lite.connect('test.db') with con: cur = con.cursor() cur.execute("DROP TABLE IF EXISTS Cars") cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)") cur.executemany("INSERT INTO Cars VALUES (?, ?, ?)", cars)
## RETRIEVE DATA FROM DATABASE - DICTIONARY # Sets cursor to a dictionary style cursor # Grabs data in all rows at once and prints row by row using the column id's (dictionary keys) through for loop import sqlite3 as lite con = lite.connect('test.db') with con: con.row_factory = lite.Row cur = con.cursor() cur.execute("SELECT * FROM Cars") rows = cur.fetchall() for row in rows: print "%s %s %s" % (row["Id"], row["Name"], row["Price"])
class BankAccount(object): def __init__(self, object): self.name = object self.balance = 0 def make_deposit(self, amount): self.balance = (self.balance + amount) def make_withdrawal(self, amount): if self.balance > amount: self.balance -= amount else: print('insufficient funds. choose a smaller amount') def check_balance(self, amount): self.balance = (self.balance - amount) if self.balance < 0: print('insufficient funds') else: print(self.balance) def is_balance_positive(self): if self.balance < 0: print('you do not have a positive balance') # christian=BankAccount('christian') # christian.make_deposit(800) # print(christian.check_balance(1000)) # print(christian.__dict__)
#Escreva um programa que receba notas de um aluno (0 - 10), caso #a nota digitada esteja fora dessa intervalo peça para o professor digitar #novamente. while True: nota_aluno = int(input('Digite a nota do aluno: ')) if nota_aluno >= 0 and nota_aluno <= 10: print(f'Nota armazenada com sucesso {nota_aluno}') break print('Nota inválida digite novamente')
class Block: def __init__(self): self.block = [None]*800 #each element will be either 0 or 1 class DiskA: def __init__(self): self.disk = [Block() for i in range(200)] class DiskB: def __init__(self): self.disk = [Block() for i in range(300)] def API_for_write(block_No, data): if(block_No <= 200): #read and write from diska diska.disk[block_No-1] = data print diska.disk[block_No-1] # print diska else: #read and write from diskb diskb.disk[block_No-201] = data print diskb.disk[block_No-201] def API_for_read(block_No): if(block_No <= 200): #read and write from diska return diska.disk[block_No-1] # print diska else: #read and write from diskb return diskb.disk[block_No-201] diska = DiskA() diskb = DiskB() API_for_write(1 , "mamm") API_for_write(200, "ww") print API_for_read(88) # print diska.disk # s = stru() # s.a = 10
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt import random # public symbols __all__ = ['Perceptron'] class Perceptron(object): """ Perceptron class """ def __init__(self): self.N = None self.d = None self.w = None self.rho = 0.5 def fit(self, X, label): self.N = X.shape[0] self.d = X.shape[1] self.w = np.random.rand(self.d+1)[:, np.newaxis] # initialize np.random.seed() while True: #for i in range(100): data_index_list = list(range(self.N)) random.shuffle(data_index_list) misses = 0 for n in data_index_list: predict = calculate_value(self.w, X[n,:]) label_value = label[n,:].sum() # perceptron learning rule if predict != label_value: self.w += label_value * self.rho * phi(X[n,:]) misses += 1 # learning finish when all data points are correctly classified print(misses) if misses == 0: break def predict(self, X): """ predict label """ n_samples = X.shape[0] n_features = X.shape[1] label_predict = np.array([1 if hyperplane(self.w, x) > 0 else -1 for x in X])[:, np.newaxis] return label_predict def phi(x): # vertical vector return np.concatenate(([1], x))[:, np.newaxis] def hyperplane(w, x): return np.dot(w.T, phi(x)) def calculate_value(w, X_n): # assumes shape (1, 1), so use sum() return np.sign(hyperplane(w, X_n).sum()).astype(np.int64) def draw_graph(X, weight, label, perceptron): if perceptron.d == 2: xmax, xmin, ymax, ymin = 3, -3, 3, -3 seq = np.arange(xmin, xmax, 0.02) xlist, ylist = np.meshgrid(seq, seq) zlist = np.array([[calculate_value(weight, np.array([x_elem, y_elem])) for x_elem, y_elem in zip(x, y)] for x, y in zip(xlist, ylist)]) # draw true separation hyperplane plt.pcolor(xlist, ylist, zlist, alpha=0.2, edgecolors='white') label_reshape = label.reshape(len(label)) plt.plot(X[label_reshape== 1,0], X[label_reshape== 1,1], 'o', color='red') plt.plot(X[label_reshape== -1,0], X[label_reshape== -1,1], 'o', color='blue') # draw separation hyperplane based on the trained weight plain_x = np.linspace(xmin, xmax, 5) w_0, w_1, w_2 = perceptron.w[0], perceptron.w[1], perceptron.w[2] # (w_0)*(x_0) + (w_1)*(x_1) + (w_2)*(x_2) = 0 where x_0 = 1 plain_y = - (w_1/w_2) * plain_x - (w_0/w_2) plt.plot(plain_x, plain_y, 'r-', color='black') plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.show()
# 1. Получите текст из файла. import re with open('text.txt', 'r', encoding='UTF-8') as f: text = f.read() print(text) # 2. Разбейте текст на предложения. #разбиваем текст на предложения и записываем в файл text2.txt (эксперимент) pattern2 = re.compile('(?<=\w[.!?])( |\n)') text_list = pattern2.split(text) for t in text_list: print(t) with open('text2.txt', 'w', encoding='UTF-8') as f1: print(*text_list, file=f1, sep="\n") # 3. Найдите самую используемую форму слова, состоящую из 4 букв и более, на русском языке. pattern3 = re.compile('([а-яА-ЯёЁ]{4,})') text_list3 = pattern3.findall(text) result = {i: text_list3.count(i) for i in text_list3}; max_rezult = max(result.values()) print(result) print(max_rezult) print("3 задание ",{word:kol for word, kol in result.items() if kol == max_rezult}) # 4. Отберите все ссылки. pattern4 = re.compile('([\w+\.]{1,}[ru/][\w+\.]{1,}|[\w+\.]{1,}ru)') text_list4 = pattern4.findall(text) print("4 задание ",text_list4) # 5. Ссылки на страницы какого домена встречаются чаще всего? text1 = text.lower() text_list5 = re.findall('\w+\.ru',text1) result5 = {i: text_list5.count(i) for i in text_list5}; max_rezult5 = max(result5.values()) print(text_list5) print(result5) print(max_rezult5) print("5 задание ",{domen:kol for domen, kol in result5.items() if kol == max_rezult5}) # 6. Замените все ссылки на текст «Ссылка отобразится после регистрации». # Исключила Mail.ru - эксперимент pattern6 = re.compile(' ([a-z0-9]+[\.]){1,}ru[/\w+]{0,}') text_list6 = pattern6.sub('"Ссылка отобразится после регистрации"',text) print("6 задание ",text_list6)
import math as m num=int(input("")) r=0 sum=0 temp=num for i in range(1,num+1): r=num%10 sum+=m.pow(r,3) num=num//10 #print(r) #s=m.pow(r,3) #print(s) #sum=sum+s #print(int(sum)) if(temp==sum): print("Arom Strong Number") else: print("not")
shoes = ['nike', 'reebok', 'adidas', 'puma'] print(shoes) print(shoes[0]) print(shoes[0].title()) print(shoes[-1]) message = f"My first shoe brand was {shoes[0].title()}." print(message) # Adding to a list shoes.append('fila') print(shoes) shoes = [] # Adding elements to an empty list shoes.append('nike') shoes.append('reebok') shoes.append('adidas') shoes.append('puma') print(shoes) # Inserting into a list shoes.insert(0, 'fila') print(shoes) # Removing an item from a list del shoes[0] print(shoes) popped_shoe = shoes.pop() # "pops" off last item in list print(shoes) print(popped_shoe) print(f"The last shoe I owned was a {popped_shoe.title()}.") first_owned = shoes.pop(0) print(f"The first shoe I owned was a {first_owned.title()}.") shoes = ['nike', 'reebok', 'adidas', 'puma'] print(shoes) shoes.remove('reebok') print(shoes) # Sorting a list permanently shoes = ['nike', 'reebok', 'adidas', 'puma'] shoes.sort() print(shoes) shoes.sort(reverse=True) print(shoes) # Sorting a list temporarily print("\nHere is the sorted list:") print(sorted(shoes)) # Printing list in reverse order shoes = ['nike', 'reebok', 'adidas', 'puma'] print("\nHere is the reverse list:") print(shoes) shoes.reverse() print(shoes)
with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents.rstrip()) print("\n") # Reading line by line filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip()) print("\n") # Making a list of lines from a File filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() # readlines() method takes each line from the file and stores it in a list print(lines) for line in lines: print(line.rstrip()) print("\n") # Working with a File's Contents filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() print(pi_string) print(f"The amount of characters in this text: {len(pi_string)}")
# 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. # Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate # for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() # and use the function to do the computation. The function should return a value. # Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). # You should use input to read a string and float() to convert the string to a number. # Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. # Do not name your variable sum or use the sum() function. def computepay(h,r): if(h <= 40): gp = h * r else: extraHour = h - 40 extraHourPay = extraHour * ( r * 1.5) normalHourPay = 40 * r gp = extraHourPay + normalHourPay return gp hrs = input("Enter Hours:") rph = input("Enter rate per hour:") try: hours = float(hrs) ratePerHour = float(rph) p = computepay(hours, ratePerHour) print("Pay",p) except: print('Problem found') 148/4 = 37 60/ 37= 1.62 = ects per credit* 148cr = total ects
# print('hi') # x = 2 # print(x) # x = x + 2 # print(x) # Using conditional statement # x = 2 # if x < 5: # print('smaller') # else: # print('bigger') # # While loop # # i = 10 # # while( i > 0): # # print(i) # # i = i-1 # # print('Boom') # # array # a = [ 10, 20 ] # i = 0 # while( i < len(a) ): # print(a[i]) # i = i + 1 # print('Boom') # take input # nam = input('zia'); # print('welcome Mr.','asdasd', nam); # europe usa lift problem # inp = input('europe floor: ') # print('Europe floor', inp) # usf = int(inp) + 1 # print('USA floor', usf) # print("123" + "abc") Spam = 2 x = int(98.6) print(x)
# cook your dish here #Solved by ROSHAN-RAUT in PYTHON ON 9-8-2020 from copy import deepcopy for test in range(int(input())): str = list(input()) pat = list(input()) for i in pat: str.remove(i) str.sort() deep = deepcopy(str) deep.append(pat[0]) deep = sorted(deep,reverse=True) if pat[0] not in str: print(''.join(str[0:len(deep) - deep.index(pat[0]) - 1])+''.join(pat)+ ''.join(str[len(deep) - deep.index(pat[0])-1:])) else: ans = ''.join(str[0:str.index(pat[0])]) +''.join(pat)+''.join(str[str.index(pat[0]):]) print(min(ans,''.join(str[0:len(deep) - deep.index(pat[0]) - 1]) + ''.join(pat) + ''.join(str[len(deep) - deep.index(pat[0])-1:])))
sample1 = [x**x for x in range(10)] sample2 = [[x*n for n in range(5)] for x in range(10)] sample3 = {x: x**x for x in range(5)} if __name__ == '__main__': print('sample 1:', sample1) print('sample 2:', sample2) print('sample 3:', sample3)
print('Hello World') class FileName(object): def __init__(self, filename): self.filename = filename self._get_file_name_info() def _get_file_name_info(self): file_str = ''.join(self.filename.split('.')[0:-1]) self._file_type = self.filename.split('.')[-1] self._file_number_str = self._get_ending_number(file_str) self._file_number = int(self._file_number_str) self._file_base_str = file_str[:-len(self._file_number_str)] def _get_ending_number(self, str): res = '' print str for char in reversed(str): if char.isdigit(): print char res += char else: return res[::-1] def get_next_file_names(self): new_file_name = self._file_base_str + str(self._file_number + 1) + \ '.' + self._file_type format_str = '0' + str(len(self._file_number_str)) + 'd' number_str = ("{0:" + format_str + '}').format(self._file_number + 1) new_file_name_with_leading_zeros = self._file_base_str + \ number_str + '.' + self._file_type return new_file_name, new_file_name_with_leading_zeros def get_previous_file_names(self): new_file_name = self._file_base_str + str(self._file_number - 1) + \ '.' + self._file_type format_str = '0' + str(len(self._file_number_str)) + 'd' number_str = ("{0:" + format_str + '}').format(self._file_number - 1) new_file_name_with_leading_zeros = self._file_base_str + \ number_str + '.' + self._file_type return new_file_name, new_file_name_with_leading_zeros test1 = FileName('Fe7C3_150_1000.spe') print test1.get_next_file_names() print test1.get_previous_file_names()
#This is to use argument from sys import argv #This explains the components script, filename = argv #This gives open command to open the sample file txt = open(filename) #These prints the words in sanple file print "Here's your file %r:" % filename print txt.read() #This uses raw input to open file again print "Type the filename again:" file_again = raw_input(">") txt_again = open(file_again) print txt_again.read()
import math, random from collections import Counter import matplotlib.pyplot as plt def bucketize(point,bucket_size): return bucket_size*math.floor(point/bucket_size) def make_histogram (points, bucket_size): return Counter(bucketize(point,bucket_size) for point in points) def plot_histogram(points,bucket_size,title=""): histogram=make_histogram(points,bucket_size) plt.bar(histogram.keys(),histogram.values(),width=bucket_size) plt.title(title) plt.show() random.seed(0) #uniform=[200*random.random()-100 for _ in range(10000)] plot_histogram([1,1,2,2,2,3,3,10,10,8,8,11,12,13,1,0,1,1,1],2)
def rotate_string(s,rotateBy): # we calculate the displacement # required for the string and then # slice and join the string if len(s)==0: return x=len(s)-rotateBy s=s[x:]+s[0:x] print "Rotated String is" print s if __name__=="__main__": s = input("Enter the string\n") rotateBy = input("Enter a rotateby value\n") rotate_string(s,rotateBy)
import sys import collections def check_palindrome(s): odd_count = 0 freq = collections.Counter() for c in s: if c != ' ': freq[c] += 1 odd_count += -1 if freq[c]%2==0 else 1 return odd_count < 2 if __name__ == '__main__': for line in sys.stdin.readlines(): line = line.strip() print("{} is a permutation of a palindrome? :: {}".format(line, check_palindrome(line))) print()
import queue class Edge: def __init__(self, p, n, c=0): self.previous = p self.next = n self.cost = c class Graph: def __init__(self, size): self.num_nodes = size self.adjacency_list = [list() for x in range(size)] def add_edge(self, p, n, c=0): self.adjacency_list[p].append(Edge(p, n, c)) self.adjacency_list[n].append(Edge(n, p, c)) def __str__(self): string = list() for i, lst in enumerate(self.adjacency_list): string.append(f'{i}-') for edge in lst: string.append(f'->{edge.next}') string.append('\n') return ''.join(map(str, string)) def bfs_traversal(self, start): string = list() q = queue.Queue() visited = [False for x in range(self.num_nodes)] q.put((start, 1)) while not q.empty(): node, level = q.get() if not visited[node]: visited[node] = True string.append(f'->({node}, {level})') for edge in self.adjacency_list[node]: q.put((edge.next, level + 1)) return ''.join(map(str, string)) def dfs_traversal(self, start): string = list() q = queue.LifoQueue() visited = [False for x in range(self.num_nodes)] q.put((start, 1)) while not q.empty(): node, level = q.get() if not visited[node]: visited[node] = True string.append(f'->({node}, {level})') for edge in self.adjacency_list[node]: q.put((edge.next, level + 1)) return ''.join(map(str, string)) if __name__ == '__main__': num_graphs = int(input()) for i in range(num_graphs): nodes, edges = map(int, input().split()) graph = Graph(nodes) for j in range(edges): p, n = map(int, input().split('-')) graph.add_edge(p, n) print(f'-- Graph --\n{str(graph)}') for i in [0, 6, 3, 7]: print(f'-- BFS Traversal --\n{graph.bfs_traversal(i)}') for i in [0, 6, 3, 7]: print(f'-- DFS Traversal --\n{graph.dfs_traversal(i)}')
import sys import collections def check_permutation_hash(s1, s2): if len(s1) is not len(s2): return False hashmap = collections.Counter(s1) for c in s2: if hashmap[c] < 1: return False hashmap[c] -= 1 return True def check_permutation_sort(s1, s2): if len(s1) is not len(s2): return False s1 = sorted(s1) s2 = sorted(s2) for i, c in enumerate(s1): if c is not s2[i]: return False return True if __name__ == '__main__': for line in sys.stdin.readlines(): args = tuple(line.split()) print("{} and {} are permutations? :: {}".format(*args, check_permutation_hash(*args))) print("{} and {} are permutations? :: {}".format(*args, check_permutation_sort(*args))) print()
def mergesort(lst): if len(lst) <= 1: return lst lst_1 = mergesort(lst[:len(lst)//2]) lst_2 = mergesort(lst[len(lst)//2:]) lst_sorted = [] ptr_1 = 0 ptr_2 = 0 while ptr_1 < len(lst_1) or ptr_2 < len(lst_2): if ptr_1 == len(lst_1): lst_sorted.append(lst_2[ptr_2]) ptr_2 += 1 continue if ptr_2 == len(lst_2): lst_sorted.append(lst_1[ptr_1]) ptr_1 += 1 continue else: if lst_2[ptr_2] < lst_1[ptr_1]: lst_sorted.append(lst_2[ptr_2]) ptr_2 += 1 else: lst_sorted.append(lst_1[ptr_1]) ptr_1 += 1 return lst_sorted if __name__ == '__main__': num_tests = int(input()) for x in range(num_tests): l = list(map(int, input().split())) print(f"Test {x+1}:\n{l}\n{mergesort(l)}")
""" Module defines basic logical building blocks for writing rules """ #boolean logic def implies(a,b): return (not a) or b def xor(a,b): return (a and not b) or (not a and b) def iff(a,b): return implies(a,b) and implies(b,a) #tuple logic def eq(a,b, attr): return _op( a, b, attr, lambda s,t: s == t) def neq(a,b, attr): return _op( a, b, attr, lambda s,t: s != t) def gt(a,b, attr): return _op( a, b, attr, lambda s,t: s > t) def lt(a,b, attr): return _op( a, b, attr, lambda s,t: s < t) def _op(a , b, attr, comparator): if isinstance(a, tuple) and \ isinstance(b, tuple): return comparator(a[attr], b[attr]) elif isinstance(a, tuple): return comparator(a[attr],b) else: return comparator(a,b[attr]) #format operators def isFloat(a,attr): try: float(a[attr]) return True except: return False
#!usr/bin/env python #-*- coding: utf-8 -*- funcionario = input() horas = input() valor_hora = input() print "NUMBER = " + str(funcionario) print "SALARY = U$ {:0.2f}".format(valor_hora * horas)
# Merge sort algorithm # # This merge sort uses naturally sorted fragments and merges each of two following fragments # It is done iteratively def next_fragment(A, i): j = i+1 while j < len(A) and A[j-1] <= A[j]: j += 1 return A[i:j] def merge(B, C): i = j = k = 0 M = [None] * (len(B) + len(C)) while i < len(B) and j < len(C): if B[i] < C[j]: M[k] = B[i] i += 1 else: M[k] = C[j] j += 1 k += 1 while i < len(B): M[k] = B[i] i += 1 k += 1 while j < len(C): M[k] = C[j] j += 1 k += 1 return M def merge_sort(A): while True: i = 0 while i < len(A): start = i B = next_fragment(A, i) i += len(B) C = next_fragment(A, i) i += len(C) M = merge(B, C) for j in range(i-start): A[j+start] = M[j] if len(C) == 0: break A = [1,2,31,4,6,321,2,3,43,2,2,3] merge_sort(A) print(A)
import random class Node: def __init__ (self, val): self.val = val self.next = None def add_number (self, val): # test function temp = self.next self.next = Node(val) self.next.next = temp class TwoLists: def __init__ (self, even, odd): self.even = even self.odd = odd def split (linked_list): even_head = Node(-1); odd_head = Node(-1) # create sentinel nodes even = even_head; odd = odd_head while linked_list != None: if linked_list.val %2 == 0: even.next = linked_list even = even.next else: odd.next = linked_list odd = odd.next linked_list = linked_list.next odd.next = even.next = None return TwoLists(even_head.next, odd_head.next) # remove sentinel nodes by returning next nodes def output (two_lists): # test function print("Odd:", end=" ") while two_lists.odd != None: print(two_lists.odd.val, end=" ") two_lists.odd = two_lists.odd.next print("\nEven:", end=" ") while two_lists.even != None: print(two_lists.even.val, end=" ") two_lists.even = two_lists.even.next print() linked_list = Node(3) for _ in range(100): linked_list.add_number(random.randint(1,1000)) output(split(linked_list))
def insertion_sort(A): for i in range(len(A)): key = A[i] k = i-1 while k >= 0 and A[k] > key: A[k+1] = A[k] k -= 1 A[k+1] = key def bucket_sort(A): n = len(A) m = len(A) // 2 # should be propotional to len(A) max_value = max(A) buckets = [[] for _ in range(m+1)] # subset of [0, max_value] for num in A: buckets[int(num / max_value * m)].append(num) for bucket in buckets: insertion_sort(bucket) i = 0 B = [] for bucket in buckets: B[i:] = bucket i += len(bucket) A[:] = B A = [5,3,2.7,10.2, 0, 21.37, 5.3, 15.6, 21.36, 2.1] bucket_sort(A) print(A)
import math n = int(input('n = ')) b = 2 while n > 1 and b <= math.sqrt(n) : if n %b == 0 : print (b, end = ' ') n = n // b else : b += 1 if n > 1 : print(n)
def count_unique(list): """Count the number of distinct elements in a list. The list can contain any kind of elements, including duplicates and nulls in any order. :param list: list of elements to find distinct elements of :return: the number of distinct elements in list Examples: >>> count_unique(['a','b','b','b','a','c','c']) 3 >>> count_unique(['a','a','a','a']) 1 >>> count_unique([ ]) 0 """ unique = [] for char in list[::]: if char not in unique: unique.append(char) return len(unique) def binary_search(list, element): """Search element sorted in list by repeatedly dividing search interval in half. If the value of the search key is less than the list in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. :param list: List of elements to find sorted element :param element: The value that we want to check whether it is in the list or not :return: The position(index) of element in the list. Examples: >>> binary_search([2,4,6,1,3],3) 2 >>> binary_search([1],2) is None True >>> binary_search([1,2,3,6,8,4,80],None) Traceback (most recent call last): ''' TypeError: Search element must not be none """ list.sort() first = 0 last = len(list) - 1 count = 0 if element == None: raise TypeError("Search element must not be none") while first < last: midpoint = (first + last) // 2 if list[midpoint] == element: position = midpoint return position else: if list[midpoint] < element: count += 1 if list[midpoint + count] == element: return midpoint + count else: count += 1 if list[midpoint - count] == element: return midpoint - count
__author__ = 'Mike' import abc class AbstractConnection(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def send_obj(self, message_obj): """ Serializes the provided message, and sends it along the connection. """ return @abc.abstractmethod def recv_obj(self): """ Retrieves a serialized object from whatever the input stream is, and converts it to a Message object. If there is any file data coming with the message, this will need to retrieve it and pack it into the message as well. OR provide a mechanism for reading the data piece by piece. I don't really know how websocket file transfer is going to work yet, so maybe do that FIRST """ # fixme ^^^^ the part about ws:// file transfer. return @abc.abstractmethod def recv_next_data(self, length): """ Retrieves the next data[length] from this connection. So, a websock will keep grabing messages until length == length but what if one message gets you nBytes > length?? THEN ITS PROBABLY BAD. :param length: length of the data to return. Might be a little more? :return: """ return @abc.abstractmethod def send_next_data(self, data): """ Sends the specified data down the connection. It just does it. No regard for what the data is or how it happens. :param data: data to send :return: """ return @abc.abstractmethod def close(self): """ closes the connection. """ return """ OKAY SO HERES THE DEAL. Whenever we would be retrieving file data, we always go: "What's the message? oh cool, length of file data, lemme just while loop to pull the data." So, now its basically the same. We'll recv_obj -> see that there is file data coming, and while loop to pull it all down. And similar for the sending of files. Very #fuckitshipit. """
from mpmath import * from sympy import degree from sympy import * from sympy.abc import x import numpy as np import cmath print("Entere the polynomial whose roots you want to find\n") print("if you want to find roots of a(x^2) + b(x) + c then enter ' a*(x**2) + b*x + c '\n\n") fun= raw_input("polynomial--> ").strip() fun=sympify(fun) fun=Poly(fun,x) deg=degree(fun) co=fun.all_coeffs() co_r=[] for i in co: co_r.append(i) co_r.reverse() def bergie_vieta(p,tol): p0=p while(np.abs(fun.subs(x,p0))>tol): b=co[0] c=co[0] for i in range(1,deg): b=co[i]+ (p0*b) c=b + (p0*c) b= co[deg] + (p0*b) p0=p0-(b/c) return p0 def bairstow(a,r,s,g,roots,tolerance): if(g<1): return None if((g==1) and (a[1]<>0)): roots.append(float(-a[0])/float(a[1])) return None if(g==2): D = (a[1]**2.0)-(4.0)*(a[2])*(a[0]) X1 = (-a[1] - cmath.sqrt(D))/(2.0*a[2]) X2 = (-a[1] + cmath.sqrt(D))/(2.0*a[2]) roots.append(X1) roots.append(X2) return None n = len(a) b = [0]*len(a) c = [0]*len(a) b[n-1] = a[n-1] b[n-2] = a[n-2] + r*b[n-1] i = n - 3 while(i>=0): b[i] = a[i] + r*b[i+1] + s*b[i+2] i = i - 1 c[n-1] = b[n-1] c[n-2] = b[n-2] + r*c[n-1] i = n - 3 while(i>=0): c[i] = b[i] + r*c[i+1] + s*c[i+2] i = i - 1 Din = ((c[2]*c[2])-(c[3]*c[1]))**(-1.0) r = r + (Din)*((c[2])*(-b[1])+(-c[3])*(-b[0])) s = s + (Din)*((-c[1])*(-b[1])+(c[2])*(-b[0])) if(abs(b[0])>tolerance or abs(b[1])>tolerance): return bairstow(a,r,s,g,roots) if (g>=3): Dis = ((-r)**(2.0))-((4.0)*(1.0)*(-s)) X1 = (r - (cmath.sqrt(Dis)))/(2.0) X2 = (r + (cmath.sqrt(Dis)))/(2.0) roots.append(X1) roots.append(X2) return bairstow(b[2:],r,s,g-2,roots) k=0 roots=[] print("for bergie vieta method enter 1 \n for bairstow method enter 2\n\n") number=int(raw_input("choice--> ")) if number==1: p=float(raw_input("enter the initial guess-->")) tole=float(raw_input("enter the tolerance(eg:0.0000001)-->")) print("root is " +str(float(bergie_vieta(p,tole)))) if number==2: p=raw_input("enter the initial p-->") q=raw_input("enter the initial q-->") tol=raw_input("enter the tolerance(eg:0.0000001)-->") bairstow(co_r,p,q,deg,roots,tol) print "\nROOTS ARE: \n" for r in roots: print "R" + str(k) + " = " + str(r) k += 1
import random import characters import time import string class BattlePrep(): def __init__(self): # take int for total enemies begin = 1 end = random.randint(2,10) suspense = range(begin, end) timeString = '.'*end print (timeString) for i in suspense: time.sleep(0.5) end = end-1 timeString = '.'*end print(timeString) class BattleSetup(BattlePrep): def __init__(self, player, total): print("You hear something coming closer...") print("") super(BattleSetup, self).__init__() self.player = player enemyCount = 0 enemyName = random.choice(characters.GenerateEnemyList()) # need better way to do this >.< enemyString = "{}".format(enemyName) enemyNamed = enemyString[19:] enemyFinal = enemyNamed.strip("'>") enemy = enemyName(random.choice([True, False]), random.choice([True, False]), "{}".format(enemyFinal),random.randint(1,10),random.randint(1,99), random.randint(0,1), random.randint(0,400), random.randint(0,1)) print("") print ("{} Appeared!!!".format(enemyFinal)) print("") while enemy.health > 0: print("") print("[ e:Attack | s:Retreat \n" "[ i:Inventory | p:Player Info \n" "[v:Assess Enemy]") print("") answer = input(">>> ") if answer == "e": print("") print("You Attacked {}".format(enemyFinal)) print("") player.attacks(player, enemy) print("") print("{} health damaged to {}".format(enemyFinal, enemy.health)) if answer == "p": print("") player.card() if answer == "v": enemy.avatar()
import json # example dictionary to save as JSON data = { "first_name": "John", "last_name": "Doe", "email": "[email protected]", "salary": 1499.9, # just to demonstrate we can use floats as well "age": 17, "is_real": False, # also booleans! "titles": ["The Unknown", "Anonymous"] # also lists! } # save JSON file # 1st option with open("data1.json", "w") as f: json.dump(data, f) #kapws etsi mporeis na grapseis ena .json arxeio
#import plt and np from matplotlib import pyplot as plt import numpy as np #load file located in data/sunspots.txt and call it `data` with float data type data = np.loadtxt('data/sunspots.txt', dtype= float) #assign first column as t t = data[:,0] #convert t into month that starts from Jan, 1749; use timedelta library import datetime as dt start = dt.date(1749, 1, 1) month = [] #this for loop converts the first column into proper dates for i in t: time = dt.timedelta(i) month.append(start + dt.timedelta(i*365/12)) #assign second column as count count = data[:,1] #plot up to first 1000 data points as instructed plt.plot(month[:1000],count[:1000], 'b-') #b- means blue line #add labels plt.xlabel("Time") plt.ylabel("Sunspot Counts") #optional: add grid plt.grid(True) #show plot plt.show()
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt # class Solution(object): # def findSubstring(self, s, words): # """ # :type s: str # :type words: List[str] # :rtype: List[int] # """ # nw = len(words[0]) * len(words) # if len(s) < nw: return [] # sign_set = set() # import itertools # for xs in itertools.permutations(words): # sign = 0 # x = ''.join(xs) # for c in x: # sign = sign * 32 + ord(c) # print 'x = {}, sign = {}'.format(x, sign) # sign_set.add(sign) # sign = 0 # res = [] # base = 32 ** (nw - 1) # for idx in range(0, nw): # sign = sign * 32 + ord(s[idx]) # if sign in sign_set: # res.append(0) # for idx in range(nw, len(s)): # sign -= ord(s[idx - nw]) * base # sign = sign * 32 + ord(s[idx]) # if sign in sign_set: # res.append(idx - nw + 1) # return res class Solution(object): def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ words.sort() sws = ''.join(words) nw = len(words[0]) * len(words) if len(s) < nw: return [] pf_sign = sum(map(lambda x: ord(x), ''.join(words))) res = [] sign = 0 for idx in range(0, nw): sign = sign + ord(s[idx]) if sign == pf_sign: res.append(0) for idx in range(nw, len(s)): sign = sign - ord(s[idx - nw]) + ord(s[idx]) if sign == pf_sign: res.append(idx - nw + 1) def post_check(idx): xs = [] for i in range(0, len(words)): xs.append(s[idx + i*len(words[0]): idx + (i+1)*len(words[0])]) xs.sort() ss = ''.join(xs) return ss == sws # words_dict = {} # for w in words: # words_dict[w] = words_dict.get(w, 0) + 1 # words_set = set(words) # for i in range(len(words)): # ss = s[idx + i * len(words[0]) : idx + (i+1)*len(words[0])] # if ss not in words_dict or words_dict[ss] == 0: # return False # words_dict[ss] -= 1 # return True res = filter(lambda idx: post_check(idx), res) return res # class Solution(object): # def findSubstring(self, s, words): # """ # :type s: str # :type words: List[str] # :rtype: List[int] # """ # words.sort() # sws = ''.join(words) # # print sws # nw = len(words) * len(words[0]) # res = [] # for i in range(0, len(s) - nw + 1): # ss = s[i: i + nw] # xs = [] # for j in range(0, len(words)): # xs.append(ss[j*len(words[0]): (j+1)*len(words[0])]) # xs.sort() # # print xs # sxs = ''.join(xs) # if sxs == sws: # res.append(i) # return res if __name__ == '__main__': s = Solution() print s.findSubstring("barfoothefoobarman", ["foo", 'bar']) print s.findSubstring("wordgoodgoodgoodbestword",["word","good","best","good"])
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def recoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ def min_node(root): if not root: return None l = min_node(root.left) r = min_node(root.right) x = root if l and l.val < x.val: x = l if r and r.val < x.val: x = r return x def max_node(root): if not root: return None l = max_node(root.left) r = max_node(root.right) x = root if l and l.val > x.val: x = l if r and r.val > x.val: x = r return x def fx(root): if not root: return lmax = max_node(root.left) rmin = min_node(root.right) if lmax and rmin and lmax.val > rmin.val: lmax.val, rmin.val = rmin.val, lmax.val elif lmax and lmax.val > root.val: lmax.val, root.val = root.val, lmax.val elif rmin and rmin.val < root.val: rmin.val, root.val = root.val, rmin.val fx(root.left) fx(root.right) fx(root)
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ m = matrix n = len(matrix) for i in range(0, n / 2): for j in range(i, n - 1 - i): # print (i, j), (j, n-1-i), (n-1-i, n-1-j), (n-1-j, i) v = m[n-1-j][i] m[n-1-j][i] = m[n-1-i][n-1-j] m[n-1-i][n-1-j] = m[j][n-1-i] m[j][n-1-i] = m[i][j] m[i][j] = v if __name__ == '__main__': s = Solution() m = [[1,2],[3,4]] s.rotate(m) print m m = [[1,2,3],[4,5,6],[7,8,9]] s.rotate(m) print m m = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] s.rotate(m) print m
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ if not root: return [] st = [] res = [] root.parent = None st.append((root, sum, 0)) while st: (r, v, d) = st.pop() if not r: continue if r.left is None and r.right is None: if r.val == v: t = r path = [] while t: path.append(t.val) t = t.parent res.append(path[::-1]) continue if d == 0: st.append((r, v, d + 1)) ln = r.left if ln: ln.parent = r st.append((ln, v - r.val, 0)) elif d == 1: rn = r.right if rn: rn.parent = r st.append((rn, v - r.val, 0)) return res
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n == 0: return [] st = [] for i in range(n + 1): st.append([]) st[0].append(None) def copy_tree(t, off = 0): if not t: return None l = copy_tree(t.left, off) r = copy_tree(t.right, off) x = TreeNode(t.val + off) x.left = l x.right = r return x for i in range(1, n + 1): for j in range(0, i): # j+1 in middle. ls = st[j] rs = st[i-1-j] for l in ls: for r in rs: t = TreeNode(j+1) t.left = l t.right = copy_tree(r, j+1) st[i].append(t) return st[n]
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ res = [] def f(idx, r): if len(r) == k: res.append(r[:]) return rest = k - len(r) for i in range(idx, n - rest + 1): r.append(i + 1) f(i + 1, r) r.pop() r = [] f(0, r) return res if __name__ == '__main__': s = Solution() print s.combine(4, 2)
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ (s, e) = (0, len(nums) - 1) while s <= e: m = (s + e) / 2 if nums[m] == target: return m elif nums[m] < target: s = m + 1 else: e = m - 1 return s
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt class Solution(object): def fullJustify(self, words, maxWidth): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ gp = [] r = [] wc = 0 for w in words: # at least len(r)-1 spaces to separate words. if (wc + len(w) + len(r) - 1) < maxWidth: r.append(w) wc += len(w) else: gp.append(r) r = [w] wc = len(w) gp.append(r) gp2 = [] for r in gp[:-1]: wc = sum(map(len, r)) rest = maxWidth - wc if len(r) == 1: s = r[0] + ' ' * rest else: avg = rest / (len(r) - 1) left = rest - avg * (len(r) - 1) if left: s = (' ' * (1 + avg)).join(r[:left]) + ' ' * (1 + avg) + (' ' * avg).join(r[left:]) else: s = (' ' * avg).join(r) gp2.append(s) wc = sum(map(len, gp[-1])) rest = maxWidth - wc - len(gp[-1]) + 1 gp2.append(' '.join(gp[-1]) + ' ' * rest) return gp2 if __name__ == '__main__': s = Solution() # print s.fullJustify(["This", "is", "an", "example", "of", "text", "justification."], 16) # print s.fullJustify(["What","must","be","shall","be."], 12) print s.fullJustify(["Don't","go","around","saying","the","world","owes","you","a","living;","the","world","owes","you","nothing;","it","was","here","first."], 30)
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ p = self.locate_pivot(nums) a = self.bs_locate(nums, 0, p, target) if a != -1: return True a = self.bs_locate(nums, p + 1, len(nums) - 1, target) if a != -1: return True return False def bs_locate(self, nums, s, e, target): while s <= e: m = (s + e) / 2 if nums[m] == target: return m elif nums[m] > target: e = m - 1 else: s = m + 1 return -1 # # pivot is a[i] > a[i-1] and a[i] > a[i+1] # def locate_pivot(self, nums): # (s, e) = (0, len(nums) - 1) # # make sure 3 elements. # while (e - s) >= 2: # # print (s, e) # m = (s + e) / 2 # # 100 percent sure. # if ((m - 1) >= 0 and nums[m] > nums[m - 1]) and \ # ((m + 1) < len(nums) and nums[m] > nums[m + 1]): # return m # if nums[m] > nums[e]: # s = m # else: # e = m # # special cases. # if (e - s) == 1: # if nums[s] < nums[e]: return e # else: return s # else: # return s # TOOD(yan): FIX ME. not O(lgN) def locate_pivot(self, nums): p = 1 while p < len(nums): if nums[p-1] > nums[p]: return p-1 p += 1 return len(nums) / 2
import csv import os budgetpath = os.path.join('AMELIA-budget_data.csv') with open(budgetpath, newline = '') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') rowCount = 0 header = next(csv_reader) monthCount = 0 #for counting how many months netTotal = 0 #to hold the total of all the amounts month = "" #to hold the current month for i amount = 0 # tohold the amount for the current i lastAmount = 0 #to hold the amount for the previous i deltas = {} #to hold all of the deltas delta = 0 #to determine the change in amount from last month to current month averageDelta = 0 #to hold the average month to month change greatestAmount = 0 #to hold the highest amount greatestMonth = "" #to hold the month of the highest amount lowestAmount = 0 #to hold the lowest amount lowestMonth = "" #to hold the month of the latest amount for row in csv_reader: #define the current variables month = row[0] amount = int(row[1]) #count the months (one per row) monthCount += 1 #add amount to the running total CORRECT netTotal = netTotal + amount # test print(f"Total {netTotal}") if rowCount >= 1: #calculate the change from last month delta = amount - lastAmount #how do we set the previous amount? # test print(f"Delta {delta}") #add the change to the list of changes deltas[month] = delta #set lastAmount lastAmount = amount rowCount +=1 # determine the greatest or lowest amount # test print(f"Deltas {deltas}") greatestAmount = max(deltas.values()) lowestAmount = min(deltas.values()) greatestMonth = [month for month,amount in deltas.items() if amount == greatestAmount][0] lowestMonth = [month for month,amount in deltas.items() if amount == lowestAmount][0] #calculate the average month to month change WRONG averageDelta = sum(deltas.values())/len(deltas) #print findings print("Financial Analysis") print("----------------------------") print(f"Total Months: {monthCount}") print(f"Total: ${netTotal}") print(f"Average Change: ${averageDelta}") print(f"Greatest Increase in Profits: {greatestMonth} (${greatestAmount})") print(f"Greatest Decrease in Profits: {lowestMonth} (${lowestAmount})") #write output to file #open files f = open('AMELIA-budget_summary.txt', 'w') #write to file f.write("Financial Analysis\n----------------------------\nTotal Months: "+repr(monthCount)+"\nTotal: $"+repr(netTotal)+"\nAverage Change: $"+repr(averageDelta)+"\nGreatest Increase in Profits: "+repr(greatestMonth)+" ($"+repr(greatestAmount)+"\nGreatest Decrease in Profits: "+repr(lowestMonth)+" ($"+repr(lowestAmount)+")") #this will put the info in the file #close file f.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a basic calculator that can do four operations; addition, subtraction, summation and division. """ def addition(a, b): """ Addition Operator """ return a + b def subtraction(a, b): """ Subtraction Operator """ return a - b def summation(a, b): """ Summation Operator """ return a * b def division(a, b): """ Division Operator """ if b == 0: raise ValueError("Divison by Zero!") return a / b
# Print an introduction. Mention typing q to quit. # Get some user input # In each round (until the user types q to quit): # Generate the computer's move. Make use of some kind of random behavior. # Use some logic to determine who wins. # Let the player know who wins. # Any long term score keeping needs to happen here if it's happening at all. # Get next user input. # After user quits, print some goodbye message.
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from scipy import stats from sklearn.metrics import mean_squared_error, r2_score, explained_variance_score from sklearn.linear_model import LinearRegression, LassoLars, TweedieRegressor from sklearn.feature_selection import f_regression, SelectKBest, RFE from sklearn.preprocessing import PolynomialFeatures from math import sqrt import warnings warnings.filterwarnings('ignore') def plot_residuals(df, y, yhat): ''' This function takes in a dataframe, the y target variable and the yhat (model predictions) and creates columns for residuals and baseline residuals. It returns a graph of both residual columns. ''' # create a residual column df['residual'] = (yhat - y) # create a residual baseline column df['residual_baseline'] = (y.mean() - y) fig, ax = plt.subplots(figsize=(13,7)) ax.hist(df.residual_baseline, label='baseline residuals', alpha=.6) ax.hist(df.residual, label='model residuals', alpha=.6) ax.legend() def regression_errors(df, y, yhat): ''' Takes in a dataframe, a ytarget and yprediction and returns SSE, MSE, RMSE, ESS, TSS and R2 ''' SSE = mean_squared_error(y, yhat)*len(df) MSE = mean_squared_error(y, yhat) RMSE = sqrt(mean_squared_error(y, yhat)) ESS = sum((yhat - y.mean())**2) TSS = sum((y - y.mean())**2) # compute explained variance R2 = ESS / TSS print('SSE is:', SSE) print('ESS is:', ESS) print('TSS is:', TSS) print('R2 is:', R2) print('MSE is:', MSE) print('RMSE is:', RMSE) def baseline_mean_errors(df, y, yhat_baseline): ''' Takes in a dataframe, ytarget and ypred_baseline and returns SSE, MSE, RMSE ''' SSE_baseline = mean_squared_error(y, yhat_baseline)*len(df) MSE_baseline = mean_squared_error(y, yhat_baseline) RMSE_baseline = sqrt(mean_squared_error(y, yhat_baseline)) print('Baseline SSE is:', SSE_baseline) print('Baseline MSE is:', MSE_baseline) print('Baseline RMSE is:', RMSE_baseline) def better_than_baseline(df, y, yhat, yhat_baseline): ''' Takes in a dataframe, ytarget, y_pred and ypred_baseline and returns which performed better. ''' RMSE = sqrt(mean_squared_error(y, yhat)) RMSE_baseline = sqrt(mean_squared_error(y, yhat_baseline)) if RMSE < RMSE_baseline: print('The model performs better than the baseline') elif RMSE > RMSE_baseline: print('The baseline performs better than the model') else: print('error, it is possible they are equal') return RMSE, RMSE_baseline # KBEST FUNCTION def select_kbest(X_train_scaled, y_train, no_features): ''' This function takes in scaled data and number of features and returns the top features ''' # using kbest f_selector = SelectKBest(score_func=f_regression, k=no_features) # fit f_selector.fit(X_train_scaled, y_train) # display the two most important features mask = f_selector.get_support() return X_train_scaled.columns[mask] ## RFE FUNCTION def rfe(X_train_scaled, y_train, no_features): ''' This function takes in scaled data and number of features and returns the top features ''' # now using recursive feature elimination lm = LinearRegression() rfe = RFE(estimator=lm, n_features_to_select=no_features) rfe.fit(X_train_scaled, y_train) # returning the top chosen features return X_train_scaled.columns[rfe.support_]
""" Resources represent attributes that can be used or consumed as a resource, such as health, mana, rocket power, etc. """ from attribute import Attribute from resource_constants import AttributeType from save_wrapper import save_attr class Resource(object): """ Properties: name (string) - name of the attribute min (Attribute) - attribute value floor max (Attribute) - attribute value ceiling recharge_interval (number) - interval between recharges in seconds recharge_rate (number) - how much to increase the current value by, for each recharge interval will_charge (boolean) - if recharging is enabled cur_val (number) - current value of the resource attrobj (Attribute objref) - Evennia database attribute direct object reference, used to save changes to the handler """ def __init__(self, attrobj, name="resource", cur_val=0, min=None, max=None, recharge_interval=60, recharge_rate=1): self.name = name self._cur_val = cur_val self._min = Attribute(attrobj, **min) self._max = Attribute(attrobj, **max) self.recharge_rate = recharge_rate self.recharge_interval = recharge_interval self.will_recharge = False self.attrobj = attrobj @property def max_modifiers(self): return self._max.modifiers @property def min_modifiers(self): return self._min.modifiers @property def max(self): return self._max.cur_val @property def min(self): return self._min.cur_val @property def percentage(self): return self.cur_val / self.max @property def cur_val(self): return self._cur_val @cur_val.setter def cur_val(self, other): if other > self.max.cur_val: self._cur_val = self.max elif other < self.min.cur_val: self._cur_val = self.min else: self._cur_val = other def get_mod(self, attr_type, desc, **kwargs): """Get modifier based on attribute type, description, and filters. Arguments: attr_type (AttributeType) - what type of attribute we are adding modifier to desc (string) - name of the modifier kwargs (dict) - any filters we want to filter the result by Returns: Modifier """ if attr_type == AttributeType.MAX: return self.max_modifiers.get(desc, **kwargs) if attr_type == AttributeType.MIN: return self.min_modifiers.get(desc, **kwargs) assert 0, "invalid attr_type {}".format(attr_type) @save_attr def add_mod(self, attr_type, **kwargs): """Add a modifier to the resource's min, or max, based on attr type. Arguments: attr_type (string) - what type of attribute we are adding modifier to kwargs - filter arguments used to grab modifier Returns: None """ if attr_type == AttributeType.MAX: self.max_modifiers.add(**kwargs) elif attr_type == AttributeType.MIN: self.min_modifiers.add(**kwargs) else: assert 0, "invalid attr_type {}".format(attr_type) @save_attr def remove_mod(self, attr_type, modifier): """Remove a modifier from the resource min/max based on attr_type. Arguments: attr_type (string) - what type of attribute we are adding modifier to modifier (Modifier) - modifier to remove Returns: None """ if attr_type == AttributeType.MAX: self.max_modifiers.remove(modifier) elif attr_type == AttributeType.MIN: self.min_modifiers.remove(modifier) else: assert 0, "invalid attr_type {}".format(attr_type) def serialize(self): """Serialize for storage. Arguments: None Returns: dict """ return { "min": self._min.serialize(), "max": self._max.serialize(), "will_recharge": self.will_recharge, "cur_val": self.cur_val, "recharge_rate": self.recharge_rate, "recharge_interval": self.recharge_interval } @save_attr def restore(self): """Restore resource to the max. Arguments: None Returns: None """ self.cur_val = self.max @save_attr def deplete(self): """Deplete resource to the minimum. Arguments: None Returns: None """ self.cur_val = self.min @save_attr def recharge(self): """Recharge the resource by the recharge rate. Arguments: None Returns: None """ self.cur += self.recharge_rate @save_attr def toggle_recharge_on(self): """Enable recharging for this resource. Arguments: None Returns: None """ self.will_recharge = True @save_attr def toggle_recharge_off(self): """Disable recharging for this resource. Arguments: None Returns: None """ self.will_recharge = False
import sys sys.path.insert(0, 'D:\github-projects\data-structures\shared') from node import Node # Binary heap: implementation of a max heap # Definition: # Parent node: must be greater than each of its children # Insert: insert a new node at the leftmost available leaf # and percolateUp() until the new node satisfies the parent requirement class BinaryHeap: def __init__(self,data): self.root = Node(data) self.nodeCount = 1 def insert(self, data): leaf = self.getLeaf(self.root) # Percolate new node up heap percolateUp(leaf, data) self.nodeCount += 1 def getLeaf(self, node): if not node: return if node.left: getLeaf(node.left) if node.right: getLeaf(node.right) return node # Percolate new node up the heap until it satisfies min-heap requirements def percolateUp(parent, newNode): # If data is greater than parent, we can insert if newNode.data > parent.data: if not parent.left: parent.left = newNode elif not parent.right: parent.right = newNode else: print("Error: parent for percolate has no available children") return # Else swap with parent else: newNode.parent = parent.parent parent.parent = newNode newNode.
__author__ = "Charles Engen" class WordWizard: def __init__(self): self.name = "Word Wizard" def _remove_vowels_spell(self, word): return "".join([letter for letter in word if letter.lower() not in "aeiou"]) def _cast_spell(self, *spell): words = [] for word in spell: words.append(self._remove_vowels_spell(word)) return words def __call__(self, *args, **kwargs): print( "I will change your words! For the better of course. See: ", *self._cast_spell(*args) ) def __str__(self): return "My name is %s, nice to meet you!" % self.name
documents = [ {"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"}, {"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"}, {"type": "insurance", "number": "10006", "name": "Аристарх Павлов"} ] directories = { '1': ['2207 876234', '11-2'], '2': ['10006'], '3': [] } # p [people] def get_name_by_document_number(user_input): for doc in documents: if doc["number"] == user_input: return doc["name"] return user_input # s [self] def get_shelf_by_document_number(user_input): for key, value in directories.items(): if user_input in value: return key return user_input # l [list] def show_documents_list(): for doc in documents: return f'{doc["type"]} "{doc["number"]}" "{doc["name"]}"' # a [add] def add_document_and_put_on_shelf(input_number, input_name, input_type, input_shelf, notice=f'Полки с таким номером не существует'): for doc in documents: if doc["number"] == input_number: return f'Документ с номером: {input_number} уже существует' for key, value in directories.items(): if input_number not in value and input_shelf in key: notice = f'Документ {input_number} добавлен на полку {input_shelf}' documents.append({"type": {input_type}, "number": {input_number}, "name": {input_name}}) directories[input_shelf].append(input_number) return notice # d [delete] def delete_document_and_put_off_shelf(input_number, notice=f'Документа с таким номером не существует'): for doc in documents: if doc["number"] == input_number: documents.remove(doc) for value in directories.values(): if input_number in value: value.remove(input_number) notice = f'Документ с номером: {input_number} удален' return notice # m [move] def delete_document_from_one_shelf_and_put_on_another_shelf(input_number, input_shelf, notice=f'Документа и полки с таким номером не существует'): for key, value in directories.items(): if input_number not in value: notice = f'Документа с таким номером не существует' elif input_shelf not in key: notice = f'Полки с таким номером не существует' elif input_number in value and input_shelf in key: value.remove(input_number) directories[input_shelf].append(input_number) notice = f'Документа с номером {input_number} удален с полки {key} и перемещен на полку {input_shelf}' return notice # as (add shelf) def add_shelf(input_shelf, notice=f'Полка с таким номером уже существует'): if input_shelf not in directories.keys(): directories[input_shelf] = [] notice = f'Полка с номером {input_shelf} создана' return notice
import pandas as pd import plotly.express as px df = pd.read_csv("line_chart.csv") fig = px.line(df,x ='Year',y = 'Per capita income', color = "Country" ) fig.show()
import random import time no_of_rolls = int(input("How many dice? ")) min = 1 max = 6 # a = random.randint(min,max) # b = random.randint(min,max) # c = a + b roll_again = "yes" while roll_again == "yes" or roll_again == "y": print("Rolling the dices...") time.sleep(1) print("The values are...") time.sleep(1) a = random.randint(min,max) b = random.randint(min,max) c = a + b if no_of_rolls == 1: print(a) elif no_of_rolls == 2: print(a) print(b) print(f'Sum of the values is {c}') else: print('wrong input') no_of_rolls = int(input("How many dices? ")) roll_again = input("Roll again? ") # if roll_again == False: # break
''' Created on 28 dec. 2016 @author: radi961 ''' from _functools import reduce from src import test def combine(*args): combinedList = [] inputLists = [] for list in args: inputLists.append(list) while not lists_empty(inputLists): pop_lists(inputLists, combinedList) return combinedList def lists_empty(inputLists): empty = True for list in inputLists: if (len(list)): empty = False break return empty def pop_lists(inputLists, combinedList): for list in inputLists: if (len(list)): combinedList.append(list.pop(0)) if __name__ == "__main__": print(combine(['r', {'d': 7}, {'w': 9}, {'w': 9}, 1, 1, 8, 'r'], [7, {'r': 9}, 'd', 7, 'w'], ['w', 7, {'o': 6}, 1, {'c': 1}, 7, 1], [7, 'd', 8, 8, {'w': 9}], [1, 'd', 1, 1, {'d': 7}])) test.assert_equals(combine(['a', 'b', 'c'], [1, 2, 3]), ['a', 1, 'b', 2, 'c', 3]) test.assert_equals(combine(['a', 'b', 'c'], [1, 2, 3, 4, 5]), ['a', 1, 'b', 2, 'c', 3, 4, 5]) test.assert_equals(combine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]),['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5]) test.assert_equals(combine([{ 'a': 1 }, { 'b': 2 }], [1, 2]),[{"a":1},1,{"b":2},2]) test.assert_equals(combine([{ 'a': 2, 'b':1 }, { 'a': 1, 'b': 2 }], [1, 2, 3, 4],[5,6],[7]), [{"a":2,"b":1},1,5,7,{"a":1,"b":2},2,6,3,4])
""" Contains the Cube class. """ from itertools import product import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from cfop.algorithms.tools import alg_to_code from cfop.algorithms.alg_dicts import PARAM_DICT, TURN_DICT class Cube: """ Cube class which creates an object repreenting a 3x3 Rubik's cube in some specific permutation as described below. The permutation of the cube is stored as a dict with 27 entries. Each entry represents one cubie of the cube (a cubie is a solid piece of the cube, so 3x3x3=27 cubies) with the key as a 3-tuple for the coordinate (e.g. (x, y, z)) and the value as a 3 element list of the color for each coordinate. The 6 centers will have two 0's in the 3-tuple and two empty strings in the list, the 8 corners will have one 0 in the 3-tuple and one empty string in the list and the 12 corners will have no 0's or empty strings. A permutation is inputted as a 6 element list. Each element represents a face. This is done so in the order: Up, Left, Front, Right, Back, Down which was inspired by a memo technique for BLD solving using OP corners and M2 edges. The string of each element are the 9 stickers of that face starting in the upper left and going right and then repeating for the remaining two rows. This permutation is translated into the dict by the _convert_perm method to make the input of custom permuations simpler. Parameters: perm - (default 0) The permuation of the cube as described above. If no perm is given, a solved cube is assumed with a white Up face and green Front face. Perm can also be given as a dict that does not need to be converted. """ def __init__(self, perm=0): if isinstance(perm, dict): self.perm = perm else: if perm == 0: perm = ['wwwwwwwww', 'ooooooooo', 'ggggggggg', 'rrrrrrrrr', 'bbbbbbbbb', 'yyyyyyyyy'] self.perm = self._convert_perm(perm) @staticmethod def _convert_perm(perm): """ Converts the permuation from a six element list of nine char strings representing the stickers on each face to a 26 length dict for where each key is a cubie coordinate and each value are the sticker colors. """ # Turn each string into a 2D list where each element # is a 3-element list representing one row of # stickers on the cube converted_perm = [] for side in perm: face_list, row_str = [], '' for n, sticker in enumerate(side): row_str += sticker if not (n + 1) % 3: face_list.append(list(row_str)) row_str = '' converted_perm.append(face_list) # Create dict to put in the colors r = range(-1, 2) cube_dict = {coord: ['', '', ''] for coord in product(r, r, r)} cube_dict.pop((0, 0, 0)) # Adding colors to dict, it's messy and unintuitive, # I know. I should make it better looking for cubie in cube_dict: if cubie[0] == 1: i, j, k = 3, abs(cubie[1] - 1), abs(cubie[2] - 1) cube_dict[cubie][0] = converted_perm[i][j][k] if cubie[0] == -1: i, j, k = 1, abs(cubie[1] - 1), cubie[2] + 1 cube_dict[cubie][0] = converted_perm[i][j][k] if cubie[1] == 1: i, j, k = 0, cubie[2] + 1, cubie[0] + 1 cube_dict[cubie][1] = converted_perm[i][j][k] if cubie[1] == -1: i, j, k = 5, abs(cubie[2] - 1), cubie[0] + 1 cube_dict[cubie][1] = converted_perm[i][j][k] if cubie[2] == 1: i, j, k = 2, abs(cubie[1] - 1), cubie[0] + 1 cube_dict[cubie][2] = converted_perm[i][j][k] if cubie[2] == -1: i, j, k = 4, abs(cubie[1] - 1), abs(cubie[0] - 1) cube_dict[cubie][2] = converted_perm[i][j][k] return cube_dict def turn_rotate(self, ttype, side, dl=False): """ Will turn or rotate the cube by 'ttype' on face 'side'. Parameters: ttype - The type of rotation. Can be 'cw' for clockwise, 'ccw' for counterclockwise or 'dt' for a double turn side - The side of the face to turn or the rotation to do. Can be 'u', 'l', 'f', 'r', 'b', 'd', 'm', 'x', 'y' or 'z' dl - (default False) Will do a double layer turn of 'side'. This will not work with the middle slice 'm' or rotations 'x', 'y', 'z' """ if ttype not in ['cw', 'ccw', 'dt']: raise Exception(("A ttype of '{}' was used ").format(ttype) + "which is not 'cw', 'ccw' or 'dt'.") if side in ['m', 'x', 'y', 'z'] and dl: raise Exception('A double layer turn was chosen ' + ("with a side of '{}'. ").format(side) + 'If dl=True, side must be' + "'u', 'l', 'f', 'r', 'b' or 'd'.") if side not in ['u', 'l', 'f', 'r', 'b', 'd', 'm', 'x', 'y', 'z']: raise Exception('An incorrect side of {} was chosen'.format(side) + 'It is not the middle slice or a rotation.') # Checks if it's a rotation or turn rotate = side in ['x', 'y', 'z'] # Finds equivalent face to turn if side in ['x', 'y', 'z', 'm']: equiv_face = {'x': 'r', 'y': 'u', 'z': 'f', 'm': 'l'} face = equiv_face[side] else: face = side # Get the right parameters for the cubie rotation p = PARAM_DICT[ttype][face] new_coords = {} # Choose correct layers to rotate if dl: turning_layers = [0, p[1]] elif side == 'm': turning_layers = [0] elif rotate: turning_layers = [-1, 0, 1] else: turning_layers = [p[1]] for cubie, colors in self.perm.copy().items(): if cubie[p[0]] in turning_layers: new_coords[(p[2]*cubie[p[3]], p[4]*cubie[p[5]], p[6]*cubie[p[7]])] = \ [colors[p[3]], colors[p[5]], colors[p[7]]] # Updates the coordinates and colors self.perm.update(new_coords) def apply_alg(self, alg, alg_input=False): """ Applies the algorithm alg to the cube. The alg can either be written as a cubing algorithm or as the code syntax. Parameters: alg - Algorithm to apply to the cube alg_input - (default False) If True, will assume alg is written in cubing notation. If False, will assume alg is written as the coding syntax """ if alg_input: alg = alg_to_code(alg) for turn in alg: self.turn_rotate(*TURN_DICT[turn]) def graph_cube(self, gap_color='k', gap_width=2, bg_color='w', w='ghostwhite', y='gold', g='forestgreen', b='midnightblue', r='crimson', o='darkorange'): """ Graphs the cube for easy visualization with optional arguments for visual preference Parameters: gap_color - (default 'k') The color of the gap between all of the stickers gap_width - (default 2) The width of the gap between of the stickers. bg_color - (default 'w') The background color of the plot w - (default ghostwhite) The color of the white stickers y - (default gold) The color of the yellow stickers g - (default forestgreen) The color of the green stickers b - (default midnightblue) The color of the blue stickers r - (default crimson) The color of the red stickers o - (default darkorange) The color of the orange stickers """ X, Y = np.meshgrid([0, 1], [0, 1]) Z = np.array([[0.5, 0.5], [0.5, 0.5]]) # Creating the color scheme for each cubie colors = {'w': w, 'y': y, 'g': g, 'b': b, 'r': r, 'o': o, '': ''} perm_colors = {} for cubie in self.perm: c = self.perm[cubie] perm_colors[cubie] = [colors[c[0]], colors[c[1]], colors[c[2]]] # Create figure for plot fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlim(-1, 2) ax.set_ylim(-1, 2) ax.set_zlim(-1, 2) ax.set_facecolor(bg_color) ax.axis('off') # Will create square of appropriate color at appropriate coordinate for cubie in perm_colors: if cubie[0] != 0: ax.plot_surface(Y + cubie[2], Z + cubie[0] * 1.5, X + cubie[1], edgecolors=gap_color, linewidth=gap_width, color=perm_colors[cubie][0]) if cubie[1] != 0: ax.plot_surface(Y + cubie[2], X + cubie[0], Z + cubie[1] * 1.5, edgecolors=gap_color, linewidth=gap_width, color=perm_colors[cubie][1]) if cubie[2] != 0: ax.plot_surface(Z + cubie[2] * 1.5, X + cubie[0], Y + cubie[1], edgecolors=gap_color, linewidth=gap_width, color=perm_colors[cubie][2]) plt.show()
import numpy as np def cubic(shape, spacing=1, connectivity=6, node_prefix='node', edge_prefix='edge'): r""" Generate a simple cubic lattice Parameters ---------- shape : array_like The number of unit cells in each direction. A unit cell has 1 vertex at its center. spacing : array_like or float The size of a unit cell in each direction. If an scalar is given it is applied in all 3 directions. Returns ------- network : dict A dictionary containing ``coords`` and ``conns`` of a cubic network with the specified spacing and connectivity. """ # Take care of 1D/2D networks shape = np.array(shape, ndmin=1) shape = np.concatenate((shape, [1] * (3 - shape.size))).astype(int) arr = np.atleast_3d(np.empty(shape)) spacing = np.float64(spacing) if spacing.size == 2: spacing = np.concatenate((spacing, [1])) spacing = np.ones(3, dtype=float) * np.array(spacing, ndmin=1) z = np.tile(np.arange(shape[2]), shape[0] * shape[1]) y = np.tile(np.repeat(np.arange(shape[1]), shape[2]), shape[0]) x = np.repeat(np.arange(shape[0]), shape[1] * shape[2]) points = (np.vstack([x, y, z]).T).astype(float) + 0.5 idx = np.arange(arr.size).reshape(arr.shape) face_joints = [(idx[:, :, :-1], idx[:, :, 1:]), (idx[:, :-1], idx[:, 1:]), (idx[:-1], idx[1:])] corner_joints = [(idx[:-1, :-1, :-1], idx[1:, 1:, 1:]), (idx[:-1, :-1, 1:], idx[1:, 1:, :-1]), (idx[:-1, 1:, :-1], idx[1:, :-1, 1:]), (idx[1:, :-1, :-1], idx[:-1, 1:, 1:])] edge_joints = [(idx[:, :-1, :-1], idx[:, 1:, 1:]), (idx[:, :-1, 1:], idx[:, 1:, :-1]), (idx[:-1, :, :-1], idx[1:, :, 1:]), (idx[1:, :, :-1], idx[:-1, :, 1:]), (idx[1:, 1:, :], idx[:-1, :-1, :]), (idx[1:, :-1, :], idx[:-1, 1:, :])] if connectivity == 6: joints = face_joints elif connectivity == 6 + 8: joints = face_joints + corner_joints elif connectivity == 6 + 12: joints = face_joints + edge_joints elif connectivity == 12 + 8: joints = edge_joints + corner_joints elif connectivity == 6 + 8 + 12: joints = face_joints + corner_joints + edge_joints else: raise Exception("Invalid connectivity. Must be 6, 14, 18, 20 or 26.") tails, heads = np.array([], dtype=int), np.array([], dtype=int) for T, H in joints: tails = np.concatenate((tails, T.flatten())) heads = np.concatenate((heads, H.flatten())) pairs = np.vstack([tails, heads]).T # NOTE: pairs is already sorted for connectivity = 6 if connectivity != 6: pairs = np.sort(pairs, axis=1) d = {} d[f"{node_prefix}.coords"] = points * spacing d[f"{edge_prefix}.conns"] = pairs return d
""" Basic Math ========== """ import logging import numpy as np logger = logging.getLogger(__name__) __all__ = [ 'blank', 'clip', 'constant', 'difference', 'fraction', 'invert', 'normalize', 'scaled', 'summation', 'product', ] def blank(target): """Blank model used in PNM format, acting as a placeholder""" pass def invert(target, prop): r""" Inverts the given array Parameters ---------- target : Base The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. prop : str Dictionary key pointing the values to invert """ return 1.0/target[prop] def difference(target, props): r""" Subtracts elements 1:N in `props` from element 0 Parameters ---------- target : OpenPNM dict The object to which the model is associated props : list A list of dict keys containing the values to operate on. If the first element is A, and the next are B and C, then the results is A - B - C. """ A = target[props[0]] for B in props[1:]: A = A - target[B] return A def fraction(target, numerator, denominator): r""" Calculates the ratio between two values Parameters ---------- target : Base The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. numerator : str Dictionary key pointing the numerator values denominator : str Dictionary key pointing the denominator values """ x = target[numerator] y = target[denominator] return x/y def summation(target, props=[]): r""" Sums the values in the given arrays Parameters ---------- target : Base The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. props : list of dictionary keys The dictionary keys pointing the arrays whose elements should be summed """ vals = np.zeros_like(target[props[0]]) for item in props: vals += target[item] return vals def normalize(target, prop, xmin=0, xmax=1): r""" Normalizes the given array between the supplied limits Parameters ---------- target : Base The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. xmin : float Lower limit of the re-scaled data xmax : float Upper limit of the re-scaled data """ vals = target[prop] # Scale to 0 to 1 vals = (vals - vals.min())/(vals.max() - vals.min()) vals = vals*(xmax - xmin) + xmin return vals def clip(target, prop, xmax, xmin=0): r""" Clips the given array within the supplied limits Parameters ---------- target : Base The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. xmin : float Values below this limit will be replaced with ``xmin``. xmax : float Values above this limit will be replaced with ``xmax``. """ vals = np.clip(target[prop], xmin, xmax) return vals def constant(target, value): r""" Places the given constant value into the target object Parameters ---------- target : Base The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. value : scalar The numerical value to apply Returns ------- value : ndarray Array containing constant values equal to ``value``. Notes ----- This model is mostly useless and for testing purposes, but might be used to 'reset' an array back to a default value. """ return value def product(target, props): r""" Calculates the product of multiple property values Parameters ---------- target : Base The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. props : list[str] The name of the arguments to be used for the product. Returns ------- value : ndarray Array containing product values of ``target[props[0]]``, ``target[props[1]]``, etc. """ value = np.ones_like(target[props[0]]) for item in props: value *= target[item] return value def scaled(target, prop, factor): r""" Scales an existing value by a factor. Useful for constricting some throat property. Parameters ---------- target : Base The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. prop : str The dictionary key of the array containing the values to be scaled. factor : str The factor by which the values should be scaled. Returns ------- value : ndarray Array containing ``target[prop]`` values scaled by ``factor``. """ value = target[prop]*factor return value
#! /usr/bin/env python3 # vendredi 15 février 2019, 08:21:33 (UTC+0100) # Écrivez un programme qui affiche la température la plus proche de 0 parmi les données d'entrée. Si deux nombres sont aussi proches de zéro, alors l'entier positif sera considéré comme étant le plus proche de zéro (par exemple, si les températures sont -5 et 5, alors afficher 5). # mardi 19 février 2019, 20:30:30 (UTC+0100) # vsn publique, pour que ThomBog en profite bavard = False # messages pour lamise au point n = int(input('nb de données ? ')) print('{} données à lire'.format(n)) assert n > 0 # première val. ppz = int(input('première valeur ? ')) # plus proche de zéro, le résultat, type int pin = ppz < 0 # ppz is negative if bavard: print('ppz = {}'.format(ppz)) print('pin = {}'.format(pin)) print('list(range(1, n)) = {}'.format(list(range(1, n)))) # valeurs suivantes for i in range(1, n): print('i = {}'.format(i)) v = eval(input('valeur no {} (à partir de 0) ? '.format(i))) # eval() mieux que int() if abs(v) > abs(ppz): continue elif abs(v) == abs(ppz): if pin and v > 0: ppz = v else: pass # ? else: ppz = v print('*** ppz = {}'.format(ppz))
import shutil import os.path import os def augmented_move(target_folder, *filenames, verbose=False, **specific): """The first argument is a target folder, and the default behavior is to move all remaining non-keyword argument files into that folder. Then there is a keyword-only argument, verbose, which tells us whether to print information on each file processed. Finally, we can supply a dictionary containing actions to perform on specific filenames; the default behavior is to move the file, but if a valid string action has been specified in the keyword arguments, it can be ignored or copied instead. Notice the ordering of the parameters in the function; first the positional argument is specified, then the *filenames list, then any specific keyword-only arguments, and finally, a **specific dictionary to hold remaining keyword arguments.""" def print_verbose(message, filename): '''print the message only if verbose is enabled''' if verbose: print(message.format(filename)) def to_absolute_path(filename): cwd = os.getcwd() return cwd + '/path1/' + filename for filename in filenames: target_path = os.path.join(target_folder, filename) if filename in specific: if specific[filename] == 'ignore': print_verbose("Ignoring {0}", filename) elif specific[filename] == 'copy': print_verbose("Copying {0}", filename) shutil.copyfile(to_absolute_path(filename), target_path) else: print_verbose("Moving {0}", filename) shutil.move(to_absolute_path(filename), to_absolute_path(target_path)) if __name__ == '__main__': augmented_move("path2", "one", "two") augmented_move("path2", "three", verbose=True) augmented_move("path2", "four", "five", "six", four="copy", five="ignore")
# // Time Complexity : O(n) # // Space Complexity : O(1) # // Did this code successfully run on Leetcode : Yes # // Three line explanation of solution in plain english # first iterate through the array and generate a product from the left hand side of the element # next, generate the product from right hand side and keep multiplying in-place with the product obtained from left hand side array # // Your code here along with comments explaining your approach class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: if not nums or len(nums)==0: return [0] res = [None]*len(nums) prod = 1 # calculate product from left side for x in range(len(nums)): res[x] = prod prod = prod * nums[x] # calculate product from right and multiply with that of existing product from left prod=1 for x in range(len(nums)-1, -1, -1): res[x] *= prod prod *= nums[x] return res
import math class Primes: """Class that generates primes up to specified number Uses Sieve of Eratosthenes to generate the list of primes >>> primes = Primes(20) >>> [prime for prime in primes] [2, 3, 5, 7, 11, 13, 17, 19] """ def __init__(self, up_to: int): """Generates a list of prime numbers up to given number >>> primes = Primes(10) >>> for prime in primes: ... print(prime) 2 3 5 7 """ self._sieve = [True] * (up_to + 1) self._sieve[:2] = [False] * 2 # mark 0 and 1 not prime for index, prime in enumerate(self._sieve): if not prime: continue if index > math.ceil(up_to // 2): break for non_prime in range(index * 2, up_to + 1, index): self._sieve[non_prime] = False self._prime_list = [index for index, prime in enumerate(self._sieve) if prime] self._prime_set = set(self._prime_list) self._len = len(self._prime_set) def __iter__(self): """ Iterate over prime numbers >>> primes = Primes(8) >>> for prime in primes: ... print(prime) 2 3 5 7 """ for prime in self._prime_list: yield prime def __reversed__(self): """ Iterate over primes starting at end >>> primes = Primes(8) >>> for prime in reversed(primes): ... print(prime) 7 5 3 2 """ for prime in reversed(self._prime_list): yield prime def __contains__(self, item: int): """Returns whether given number is prime >>> primes = Primes(50) >>> 7 in primes True >>> 8 in primes False """ return item in self._prime_set def __len__(self): """Gets number of primes in object >>> primes = Primes(50) >>> len(primes) 15 """ return self._len def __getitem__(self, pos): """Gets prime at position >>> primes = Primes(50) >>> primes[0] 2 >>> primes[0:4] [2, 3, 5, 7] """ return self._prime_list[pos] def is_prime(self, potential_prime: int) -> bool: """Checks if a given input number is prime >>> primes = Primes(100) >>> primes.is_prime(11) True >>> primes.is_prime(12) False """ return potential_prime in self def largest_prime(self) -> int: """Returns largest prime number in list of primes >>> primes = Primes(30) >>> primes.largest_prime() 29 """ return self._prime_list[-1]
n = int(input('Insira o número o qual você queira ver o fatorial: ')) c = n-1 f = n while c != 1: f = f*c c = c-1 print('O fatorial de {} é igual a {}'.format(n, f))
import random n = int(input("""========JOKENPÔ======== Escolha a sua opção: [1]Pedra [2]Papel [3]Tesoura """)) ncp = random.randrange(1,3) if n == ncp: print('Empate!') elif n == 1 and ncp == 2: print('Jogador perdeu para o computador: Pedra vs Papel!') elif n == 1 and ncp == 3: print('Jogador ganhou do computador: Pedra vs Tesoura!') elif n == 2 and ncp == 1: print('Jogador ganhou do computador: Papel vs Pedra!') elif n == 2 and ncp == 3: print('Jogador perdeu para o computador: Papel vs Tesoura!') elif n == 3 and ncp == 1: print('Jogador perdeu para o computador: Tesoura vs Pedra!') elif n == 3 and ncp == 2: print('Jogador ganhou do computador: Tesoura vs Papel!')
s = 0 for c in range(0, 6): si = int(input('Digite um valor: ' )) if (si%2) == 0: s += si print('A soma de todos os valores pares é: {}'.format(s))
def leiaInt(n): num = (input(n)) while num.isdigit() != True: print('ERRO! Digite um número inteiro válido') num = input('Digite um número: ') if num.isdigit() == True: break return(num) #Programa Principal n = leiaInt('Digite um número: ') print(f'Você acabou de digitar o número {n}')
import math while True: print("""-------------------- --CAIXA ELETRÔNICO-- --------------------""") v = int(input('Qual é o valor que você quer sacar? ')) vr = v if (v/50) >= 1: print(f'Total de {math.floor((v)/50)} cédulas de R$50') vr = v%50 if ((vr)/20) >= 1: print(f'Total de {math.floor((vr)/20)} cédulas de R$20') vr = vr%20 if ((vr)/10) >= 1: print(f'Total de {math.floor((vr)/10)} cédulas de R$10') vr = vr%10 if ((vr)/5) >= 1: print(f'Total de {math.floor((vr)/5)} cédulas de R$5') vr = vr%5 if ((vr)/1) >= 1: print(f'Total de {math.floor((vr)/1)} cédulas de R$1') fim = str(input('Quer sacar de novo? [S/N]: ')) if fim in ('Nn'): break
n1 = float(input('Insira a primeira nota: ')) n2 = float(input('Insira a segunda nota: ')) m = (n1+n2)/2 if m < 5.0: print('Reprovado') elif m >= 5 and m < 7: print ('Recuperação') else: print('Aprovado')
gols = [] total = 0 jogador = {} jogador['nome'] = str(input('Nome do Jogador: ')) partidas = int(input('Quantas partidas Joelson jogou? ')) for c in range(0, partidas): gols.append(int(input(f'Quantos gols na partida {c}? '))) total += gols[c] jogador['gols'] = gols jogador['total'] = total print('-='*30) print(jogador) print('-='*30) for k, v in jogador.items(): print(f'O campo {k} tem o valor {v}') print('-='*30) print(f'O jogador {jogador["nome"]} jogou {partidas} partidas.') for c in range(0, partidas): print(f' =>Na partida {c}, fez {gols[c]} gols.') print(f'Foi um total de {jogador["total"]} gols.')
pilha = [] conte = 0 contf = 0 exp = str(input('Digite a expressão: ')) for c, v in enumerate(exp): if v == ('('): pilha.append(v) elif v == (')'): pilha.append(v) pa = pilha.count('(') pf = pilha.count(')') for c, v in enumerate(pilha): if c == 0 and v!= ('('): conte += 1 print('Começou errado') break elif v == ('('): for c, v in enumerate(pilha): if v == (')'): contf += 1 pilha.remove(')') break if pa != pf: conte+=1 elif pa != contf: conte += 1 print(pa) print(pf) print(conte) print(contf) if conte == 0: print('Parabéns! Sua expressão está certa') elif conte > 0: print('Sua expressão está errada')
cont = () lista = [] while True: valor = int(input('Insira um valor: ')) lista.append(valor) cont = str(input('Quer continuar [S]/[N]')) if cont in ('Nn'): break lista.sort(reverse=True) print(f'Foram inseridos {len(lista)} valores \n A lista em ordem decrescente: \n {lista}') if 5 in lista: print('O valor 5 está na lista') else: print('O valor 5 está ausente na lista')
#Sanjidah Abdullah #[email protected] template = "If it VERB1 like a NOUN and VERB2 like a NOUN, it probably is a NOUN." noun = input("Enter a noun: ") template = template.replace("NOUN", noun) verb1 = input("Enter a verb: ") template = template.replace("VERB1", verb1) verb2 = input("Enter another verb: ") template = template.replace("VERB2", verb2) print("New sentence: ", template)
#Sanjidah Abdullah #[email protected] import folium import pandas as pd inFile = input('Enter CSV file name: ') outputFile = input('Enter output file: ') #Read in the CSV file into a dataframe: fileName = pd.read_csv(inFile) print(fileName["TIME"]) #Set up a new map object, centered at Hunter College, #zoomed in enough to see city outline. map1 = folium.Map(location=[40.768731, -73.964915], tiles="Cartodb Positron", zoom_start = 10) for index,row in fileName.iterrows(): lat = row["LATITUDE"] lon = row["LONGITUDE"] name = row["TIME"] #Add a marker for our randomly chosen landmark to the map. newMarker = folium.Marker([lat, lon], popup=name) newMarker.add_to(map1) map1.save(outfile = outputFile)
#Sanjidah Abdullah #[email protected] insulin = input("Enter a DNA string: ") #Compute the length length = len(insulin) print("Length is", length) #Compute the GC-content: numC = insulin.count('C') numG = insulin.count('G') gc = (numC + numG) / length print("GC-content is", gc) #Compute the position of first G: positionG = insulin.find('G') print("First G found at position", positionG) #Compute the position of first C: positionC = insulin.find('C') print("First C found at position", positionC)
#Sanjidah Abdullah #[email protected] import matplotlib.pyplot as plt import numpy as np pic = input("Enter file name: ") ca = plt.imread(pic) #Read in image countSnow = 0 #Number of pixels that are almost white t = 0.75 #Threshold for almost white-- can adjust between 0.0 and 1.0 #For every pixel: for i in range(ca.shape[0]): for j in range(ca.shape[1]): #Check if red, green, and blue are > t: if (ca[i,j,0] > t) and (ca[i,j,1] > t) and (ca[i,j,2] > t): countSnow = countSnow + 1 print("Snow count is", countSnow)