text
stringlengths
37
1.41M
import os import argparse def get_location_from_line(line): if not line: return None return int(line.split(',')[0]) def scan_through_line_for_number(alignment_file, start_line_hint, number): alignment_file.seek(start_line_hint) for line in alignment_file: location = get_location_from_line(line) if not location: raise ValueError('There still lines in the alignment file but cannot obtain coordinate location') if location == number: return line, start_line_hint # The lines are sorted so if the current location is already greater than the one # we're searching for we know what we search does not exist. elif location > number: return None start_line_hint += len(bytes(line, 'ascii')) return None def binary_search(low, high, number, file): if low > high: return None # There is only one potential candidate. if low == high: # Always make sure to seek to the actual offset that we want to examine. file.seek(low) line = file.readline() location = get_location_from_line(line) if not location: return None return (line, low) if location == number else None # There are at least two bytes to work with. mid = low + (high - low) // 2 original_mid = mid file.seek(mid) # Move right until the next new line character while file.read(1) != '\n': mid += 1 # However, if we hit the upper bound before hitting a newline character, # we'd know that the line we're searching for could only be in the left half. if mid == high: return binary_search(low, original_mid, number, file) # When we hit the newline character, the mid would not be incremented in the while loop body, # so we have to increment it here to keep it synchronized with the position of the file pointer. mid += 1 line = file.readline() location = get_location_from_line(line) # print(low, original_mid, mid, high, location) if not location: if mid < high: raise ValueError("mid < high but no location can be obtained") return binary_search(low, original_mid, number, file) elif location == number: return line, mid elif location > number: return binary_search(low, original_mid, number, file) else: return binary_search(mid, high, number, file) def search(file, number, file_byte_size): """ Performs binary search on the lines of the file for the line containing the nucleotide coordinate number. WARNING: Assumes there is one header line that ends with a newline. WARNING: Assumes all other lines start with a coordinate number followed by a comma. :param file: a file object that's opened in read mode :param number: the nucleotide coordinate number we're searching for :param filename: the name of the file that's opened that contains the maf sequence e.g. chr2_maf_sequence.csv :return: (line, byte-offset) or None If there is a line containing the number, the function returns a tuple whose first element is the line we are searching for as a string ending with a newline character, and whose second element is the byte offset of the first byte of the line from the beginning of the file. It returns None if there is no line containing the number. """ file.seek(0) # high is the byte offset of the last byte in the file. high = file_byte_size - 1 # Getting rid of the header line. start_index = 0 while file.read(1) != '\n': start_index += 1 if start_index >= high: print('The header line extends onto or beyond the upper bound.') return None # Start at the position after the newline. start_index += 1 # print('binary search in range {} to {}'.format(start_index, high)) return binary_search(start_index, high, number, file) if __name__ == '__main__': parser = argparse.ArgumentParser() # an example filename would be chr2_maf_sequence.csv parser.add_argument('filename') parser.add_argument('number') args = parser.parse_args() byte_size = os.stat(args.filename).st_size with open(args.filename, 'r') as sequence_file: print(search(file=sequence_file, number=int(args.number), file_byte_size=byte_size))
# modified version of 'invert_dict()' function From Section 11.5 of: # Downey, A. (2015). Think Python: How to think like a # computer scientist. Needham, Massachusetts: Green Tree Press. def invert_dict(d): inverse = dict() for key in d: val = d[key] for item in val: inverse[item] = key return inverse # implement method to read from a ".txt" file def readFile(filename): dictOut = dict() # open file in read mode with open(filename, 'r') as inputfile: # iterate over the file for line in inputfile.readlines(): # using "," to split the line line = line.strip().split(',') dictOut[line[0]] = line[1:] # return dictOut as format of dictionary return dictOut # implement method to write to a file def writeFile(inverted_d, filename): # open the file in write mode with open(filename, 'w+') as invertedFile: # iterate over the dictionary for key, value in inverted_d.items(): # write contents to file invertedFile.write(str(key)+':'+str(value)+'\n') if __name__ == "__main__": # read data from file d = readFile('figureskating.txt') # display dictionary print("\n ***Dictionary***\n ", d) # get dictionary from invert_dict method invt_d = invert_dict(d) # display inverted dictionary print('\n ***Inverted Dictionary***\n', invt_d) # write content into a file writeFile(invt_d, 'Invt_FigureSkating_Dict.txt')
""" basicfem.py is the main script to execute the Basicfem solver. """ import sys import os import numpy as np import matplotlib.pyplot as plt from abc import ABCMeta, abstractclassmethod from lib.solvers import * from lib.output_utility import * from lib.solver_input import * def main(): """ Main function to read in command line input, processing directories and run respective solvers. The script takes two argument -- an input directory name and an output directory name. The input directory should locate in the local directory and needs to contain necessary txt files for basicfem solvers. It can also be an xlsx file that contains all the required input. The output directory will be generated if not exists, or being overwritten. """ if len(sys.argv) != 3: print("usage: python basicfem.py <input_directory> <output_directory>") print(" <input_directory> can also be a single xlsx file", "with all required input.") sys.exit(1) input_dir = sys.argv[1] input_dir = input_dir.lstrip('./') if not os.path.exists(input_dir): print("Input directory or file does not exist.") sys.exit(1) if os.path.isfile(input_dir): param = read_param(input_dir) else: param = read_param('./' +sys.argv[1] + '/param.txt') cwd = os.getcwd() output_path = cwd + '/' + sys.argv[2] if not os.path.exists(output_path): os.mkdir(output_path) if param is None: param = {} problem_type, scale_factor = set_param_guide() else: problem_type = param['problem_type'] scale_factor = float(param['deformation_scale_factor']) if problem_type.lower() == "truss": input_ = TrussInput2D(input_dir) result = TrussSolver2D(input_) save_data(result.stress,'element_stresses.txt', dir_name=sys.argv[2]) save_data(result.displacements, 'nodal_displacements.txt', dir_name=sys.argv[2]) plot_deformed_shape_1D(result, scale_factor, output_path) elif problem_type.lower() == "frame": input_ = TrussInput2D(input_dir) result = FrameSolver2D(input_) save_data(result.displacements, 'nodal_displacements.txt', dir_name=sys.argv[2]) plot_deformed_shape_1D(result, scale_factor, output_path) elif problem_type.lower() == '2d': input_ = TriangularElementInput(input_dir) result = TriangularElementSolver(input_) plot_deformation_shape_2D(input_.nodal_data, input_.element_data, result.displacements, scale_factor, output_path) if 'contour_over_deformed_mesh' in param: plot_on_deformed_flag = str(param['contour_over_deformed_mesh']) \ .lower() == 'true' plot_contour_batch(result, scale_factor, output_path, plot_on_deformed=plot_on_deformed_flag) else: plot_contour_batch(result, scale_factor, output_path) save_data(result.displacements, 'nodal_displacements', dir_name=sys.argv[2]) save_data(result.stress, 'element_stresses', dir_name=sys.argv[2]) print("Solver process completed.") def read_param(param_filename): """ Read the param file to set the solver related parameters. The param file will either be an param.txt file inside the input directory, or the Param page inside the input xlsx file. Parameters ---------- param_filename : str The xlsx file name, or the processed path to the param.txt file. Returns ------- dict The dictionary contains solver related paramters. """ if not os.path.isfile(param_filename): return None if param_filename.endswith('.xls') or param_filename.endswith('.xlsx'): from pandas import read_excel arr = read_excel(param_filename, sheet_name = 'Param').values param = {arr[i,0] : arr[i,1] for i in range(len(arr))} else: f = open(param_filename, 'r') param = {} for line in f: line = line.split('#', 1)[0] line = line.rstrip() if line != '': k, v = line.strip().split('=') param[k.strip()] = v.strip() f.close() return param def set_param_guide(): """ Command line prompt to guide the users setting up parameters. In the case when param file does not exist, this function will guide the users to provide the necessary paramters for solver. Note that this guide will keep most of the parameters default, only set those that is needed to be assigned for solver to run. Returns ------- tuple Parameters necessary for the solver. """ print("param file/page does not exists. Please specify:") problem_type = input("Problem type? (`truss`, `frame`, or `2d`): ") while problem_type not in ['truss','frame','2d']: print('Invalid problem type.') problem_type = input("Problem type? (`truss`, `frame`, or `2d`): ") scale_factor = input("Deformation scale factor? (default = 1) ") try: scale_factor = float(scale_factor) except: scale_factor = 1.0 print('No valid input. Deformation scale factor = 1 will be used.') return problem_type, scale_factor def plot_contour_batch(fem_result, scale_factor, output_path, plot_on_deformed=True): """ Generate all the contour plot available. Only used for 2d elements. Parameters ---------- fem_result: BaseSolver A Solver object contains the analysis result. scale_factor : float The deformation scale factor assigned in the param. output_path : str The path to the output directory assigned by the user. plot_on_deformed : bool Flag that determines if the contour is plotted on the deformed structures. Default is True. """ if plot_on_deformed: plot_contour(fem_result, "stress", 'xx', 'sigma_xx', scale_factor, output_path) plot_contour(fem_result, "stress", 'yy', 'sigma_yy', scale_factor, output_path) plot_contour(fem_result, "stress", 'xy', 'sigma_xy', scale_factor, output_path) plot_contour(fem_result, "strain", 'xx', 'strain_xx', scale_factor, output_path) plot_contour(fem_result, "strain", 'yy', 'strain_yy', scale_factor, output_path) plot_contour(fem_result, "strain", 'xy', 'strain_xy', scale_factor, output_path) else: plot_contour(fem_result, "stress", 'xx', 'sigma_xx', scale_factor, output_path, False) plot_contour(fem_result, "stress", 'yy', 'sigma_yy', scale_factor, output_path, False) plot_contour(fem_result, "stress", 'xy', 'sigma_xy', scale_factor, output_path, False) plot_contour(fem_result, "strain", 'xx', 'strain_xx', scale_factor, output_path, False) plot_contour(fem_result, "strain", 'yy', 'strain_yy', scale_factor, output_path, False) plot_contour(fem_result, "strain", 'xy', 'strain_xy', scale_factor, output_path, False) if __name__ == "__main__": main()
import hashlib import random def hash_function(key): """ Returns the low 32 bits of the md5 hash of the key. """ # You don't need to understand this return int(hashlib.md5(str(key).encode()).hexdigest()[-8:],16)&0xffffffff def how_many_before_collision(buckets, loops=1): for i in range(loops): tries = 0 tried = set() while True: random_key = random.random() index = hash_function(random_key) % buckets if index not in tried: tried.add(index) tries += 1 else: break print(f"{buckets} buckets, {tries} before hash collision. ({tries / buckets * 100:.1f}% full)") how_many_before_collision(65536, 10)
class HashTableEntry: """ Linked List hash table key/value pair """ def __init__(self, key, value): self.key = key self.value = value self.next = None self.head = None def find_val(self, value): # start at the head cur = self.head while cur is not None: if cur.value == value: return cur.value cur = cur.next return None def find_key(self, key): cur = self.head while cur is not None: if cur.key == key: return cur.key cur = cur.next return None def insert_at_head(self, node): n = node # new value .next is current head n.next = self.head # current head is now set to n self.head = n def delete(self, value): cur = self.head #Special Case of Deleting Head: if cur.value == value: # are we deleting the head? self.head = self.head.next return cur # General Case prev = cur cur = cur.next while cur is not None: if cur.value == value: prev.next = cur.next # cuts out the node return cur else: prev = prev.next cur = cur.next return None # Hash table can't have fewer than this many slots # MIN_CAPACITY = 8 class HashTable: """ A hash table that with `capacity` buckets that accepts string keys Implement this. """ def __init__(self, capacity): # Your code here def __init__(self, capacity=8): self.capacity = capacity self.storage = [None] * capacity self.elements = 0 def get_num_slots(self): """ Return the length of the list you're using to hold the hash table data. (Not the number of items stored in the hash table, but the number of slots in the main list.) One of the tests relies on this. Implement this. return len(self.storage) def get_load_factor(self): """ Return the load factor for this hash table. Implement this. """ return self.elements / self.capacity def fnv1(self, key): """ FNV-1 Hash, 64-bit Implement this, and/or DJB2.pyy """ # Your code here def djb2(self, key): """ DJB2 hash, 32-bit Implement this, and/or FNV-1. """ # Your code here def hash_index(self, key): """ Take an arbitrary key and return a valid integer index between within the storage capacity of the hash table. """ #return self.fnv1(key) % self.capacity <<<<<<< Updated upstream return self.djb2(key) % self.capacity ======= return self.djb2(key) % len(self.storage) >>>>>>> Stashed changes def put(self, key, value): """ Store the value with the given key. Hash collisions should be handled with Linked List Chaining. Implement this. """ <<<<<<< Updated upstream # Your code here ======= # need to account for if the key value is the same i = self.hash_index(key) if not self.storage[i]: hte = HashTableEntry(key, value) self.storage[i] = hte self.elements += 1 hte.head = HashTableEntry(key, value) elif self.storage[i] and self.storage[i].key != key: self.storage[i].insert_at_head(HashTableEntry(key, value)) >>>>>>> Stashed changes def delete(self, key): """ Remove the value stored with the given key. Print a warning if the key is not found. Implement this. """ <<<<<<< Updated upstream # Your code here ======= i = self.hash_index(key) node = self.storage[i] prev = None if node.key == key: self.storage[i] = node.next return while node != None: if node.key == key: prev.next = node.next self.storage[i].next = None return prev = node node = node.next self.elements -= 1 return >>>>>>> Stashed changes def get(self, key): """ Retrieve the value stored with the given key. Returns None if the key is not found. Implement this. """ <<<<<<< Updated upstream # Your code here ======= # - find the index in the hash table for the key i = self.hash_index(key) # - search the list for that key if not self.storage[i]: return None else: if self.storage[i].find_key(key) == key: return self.storage[i].value >>>>>>> Stashed changes def resize(self, new_capacity): """ Changes the capacity of the hash table and rehashes all key/value pairs. Implement this. """ <<<<<<< Updated upstream # Your code here ======= prev_storage = self.storage self.capacity = new_cap self.storage = [None] * new_cap for i in range(len(prev_storage)): prev = prev_storage[i] if prev: while prev: if prev.key: self.put(prev.key, prev.value) prev = prev.next >>>>>>> Stashed changes if __name__ == "__main__": ht = HashTable(8) ht.put("line_1", "'Twas brillig, and the slithy toves") ht.put("line_2", "Did gyre and gimble in the wabe:") ht.put("line_3", "All mimsy were the borogoves,") ht.put("line_4", "And the mome raths outgrabe.") ht.put("line_5", '"Beware the Jabberwock, my son!') ht.put("line_6", "The jaws that bite, the claws that catch!") ht.put("line_7", "Beware the Jubjub bird, and shun") ht.put("line_8", 'The frumious Bandersnatch!"') ht.put("line_9", "He took his vorpal sword in hand;") ht.put("line_10", "Long time the manxome foe he sought--") ht.put("line_11", "So rested he by the Tumtum tree") ht.put("line_12", "And stood awhile in thought.") print("") # Test storing beyond capacity for i in range(1, 13): print(ht.get(f"line_{i}")) # Test resizing old_capacity = ht.get_num_slots() ht.resize(ht.capacity * 2) new_capacity = ht.get_num_slots() print(f"\nResized from {old_capacity} to {new_capacity}.\n") # Test if data intact after resizing for i in range(1, 13): print(ht.get(f"line_{i}")) print("")
from card import * import random class Deck: def __init__(self): self.cards = [] for suit in [ "clubs","diamond", "hearts", "spades" ]: for rank in range (1,14): new_card = Card(rank, suit) self.cards.append(new_card) def shuffle(self): random.shuffle(self.cards) def deal(self): return self.cards.pop()
limit,moves = input("Enter the char limit:"),input("Enter the moves:") start,goal = [],[] for i in range(limit): start.append(raw_input("Enter the Start:")) for i in range(limit): goal.append(raw_input("Enter the Goal:")) def fn(start,goal,moves): while moves>0:
import os.path as osp import numpy as np def parse_psiblast(path_to_file): """ For a concrete example check example.blastPsiMat format on https://github.com/plopd/ppcs2-project/blob/master/dataset/example.blastPsiMat :param path_to_file: :return: """ # get filename (without extension) - it coincides with the identifier in the fasta format fn = osp.splitext(osp.split(path_to_file)[1])[0] f = open(path_to_file, "r") file = f.readlines() data = file[2:-6] f.close() record, sequence = [], [] # get the first 20 amino acids aa = np.array(data[0].split()[:20]) for line in data[1:]: values = line.split() results = list(map(int, values[22:42])) record.append(results) sequence.append(values[1]) profile = np.array(record) return profile, sequence
class Question: def __init__(self,text,choices,answer): self.text=text self.choices=choices self.answer=answer def checkAnswer(self,answer): return self.answer==answer #print(q1.checkAnswer('Python')) #print(q2.checkAnswer('c')) class Quiz: def __init__(self,questions): self.questions=questions self.score=0 self.questionIndex=0 def getQuestion(self): return self.questions[quiz.questionIndex] def displayQuestion(self): question=self.getQuestion() print(f" Soru {self.questionIndex+1}: {question.text}") for q in question.choices: print('-'+q) answer=input('cevap: ') print(question.checkAnswer(answer)) self.guess(answer) self.loadQuestion() def guess(self,answer): question=self.getQuestion() if question.checkAnswer(answer): self.score+=1 self.questionIndex+=1 self.displayQuestion() def loadQuestion(self): if len(self.questions) ==self.questionIndex: self.showScore() else: self.displayQuestion() def showScore(self): pass q1=Question('en iyi programlama dili hangisidir?',['c#','Python','Javascript','Java'],'Python') q2=Question('en popüler programlama dili hangisidir?',['Python','Javascript','c#','Java'],'Python') q3=Question('en çok kazandıran programlama dili hangisidir?',['Javascript','c#','Java','Python'],'Python') questions=[q1,q2,q3] quiz=Quiz(questions) quiz.displayQuestion()
class User: def __init__(self,username,password,email): self.username=username self.password=password self.email=email class UserRepository: def __init__(self): self.users=[] self.isLoggedIn=False self.currentUser={} #load users from .json file self.loadUser() def loadUser(self): pass def register(self,user:User): self.users.append(user) print("user is created") def login(self): pass def savetoFile(self): pass repository=UserRepository() while True: print("Menü".center(50,'*')) secim=input('1-Register\n2-Login\n3-Logout\n4-Identity\n5-Exit\nYour choice: ') if secim=='5': break else: if secim == '1': username = input('username: ') password = input('password: ') email = input('email: ') user = User(username, password, email) repository.register(user) print(repository.users) elif secim == '2': pass elif secim == '3': pass elif secim == '4': pass else: print("Wrong Choice")
"""def sum_list(items): sum_numbers = 0 for x in items: sum_numbers += x return sum_numbers print(sum_list([1,2,-8])) multiply=1 list=[1,2,3,4] for x in list: multiply*=x print("multiplication is",multiply) list=[7,5,9,3,4,6] max = list[0] for i in list: if i>max: max=i print("the max is ",max) min=[] for i in range(3): x=int(input("bir sayi giriniz: ")) min.append(x) print(min) def find_min(min): minimum=min[0] for i in min: if i<minimum: minimum=i print("the min is ", minimum) find_min(min) def match_words(words): ctr = 0 for word in words: if len(word) > 1 and word[0] == word[-1]: ctr += 1 return ctr print(match_words(['abc', 'xyx', 'aba', '1221'])) l= [1] if not l: print("List is empty") def remove_even(list): for i in list: if i%2==0: continue else: print(i) list=[2,5,77,8] remove_even(list) def printValues(): l = list() for i in range(1,21): l.append(i**2) print(l[:5]) print(l[-6:]) printValues()""" color = [("Black", "#000000", "rgb(0, 0, 0)"), ("Red", "#FF0000", "rgb(255, 0, 0)"), ("Yellow", "#FFFF00", "rgb(255, 255, 0)")] var1, var2, var3 = color print(var1) print(var2) print(var3)
def square(num): return num**2 numbers=[1,3,5,7,10,14] """result=list(map(square,numbers)) print(result) for item in map(square,numbers): print(item) square=lambda num: num**2 result=square(3) print(result)""" def check_even(num): return num%2==0 #result= list(filter(check_even,numbers)) result= list(filter(lambda num: num%2==0,numbers)) print(result)
"""Adi = 'Ali' Soyad = ' Yılmaz' AdSoyad = Adi+Soyad Cinsiyet = True #erkek TcKimlik ='123456789' Dogum=1989 Adresi = 'mersin mezitli' yas = 2021-Dogum print(yas) print(AdSoyad) pi=3.14 r=int(input("yarı çap: ")) alan=pi*(r**2) cevre=2*pi*r print("alan "+str(alan)+" çevre "+str(cevre))"""
import random """result=dir(random) print(result) result=random.random() #0.0-1.0 result=random.uniform(10,100) result=int(random.uniform(10,100)) result=random.randint(1,10) print(result) names=['ali','yagmur','deniz','cenk'] #result=names[random.randint(0,len(names)-1)] result=random.choice(names) print(result) greeting='hello there' result=random.choice(greeting) print(result)""" liste=list(range(10)) random.shuffle(liste) #elemanları karıstırır print(liste) liste=range(100) result=random.sample(liste,3) print(result)
"""import random import os print("Select a random element from a list:") elements = [1, 2, 3, 4, 5] print(random.choice(elements)) print(random.choice(elements)) print(random.choice(elements)) print("\nSelect a random element from a set:") elements = set([1, 2, 3, 4, 5]) # convert to tuple because sets are invalid inputs print(random.choice(tuple(elements))) print(random.choice(tuple(elements))) print(random.choice(tuple(elements))) print("\nSelect a random value from a dictionary:") d = {"a": "naz", "b": "bet", "c": "aynur", "d": "islim", "e": "fehmi "} key = random.choice(list(d)) print(d[key]) key = random.choice(list(d)) print(d[key]) key = random.choice(list(d)) print(d[key]) print("\nSelect a random file from a directory.:") print(random.choice(os.listdir("/")))""" import random """import string print("Generate a random alphabetical character:") print(random.choice(string.ascii_letters)) print("\nGenerate a random alphabetical string:") max_length = 50 str1 = "" for i in range(random.randint(1, max_length)): str1 += random.choice(string.ascii_letters) print(str1) print("\nGenerate a random alphabetical string of a fixed length:") str1 = "" for i in range(10): str1 += random.choice(string.ascii_letters) print(str1)""" import random """import datetime print("Generate a random integer between 0 and 6:") print(random.randrange(5)) print("Generate random integer between 5 and 10, excluding 10:") print(random.randrange(start=5, stop=10)) print("Generate random integer between 0 and 10, with a step of 3:") print(random.randrange(start=0, stop=10, step=3)) print("\nRandom date between two dates:") start_dt = datetime.date(2019, 2, 1) end_dt = datetime.date(2019, 3, 1) time_between_dates = end_dt - start_dt days_between_dates = time_between_dates.days random_number_of_days = random.randrange(days_between_dates) random_date = start_dt + datetime.timedelta(days=random_number_of_days) print(random_date)""" x=random.uniform(0,1) print(x) list=[1,2,3,4] random.shuffle(list) print(list) import types def func(): return 1 print(isinstance(func, types.FunctionType)) print(isinstance(func, types.LambdaType)) print(isinstance(lambda x: x, types.FunctionType)) print(isinstance(lambda x: x, types.LambdaType)) print(isinstance(max, types.FunctionType)) print(isinstance(max, types.LambdaType)) import copy nums_x = [1, [2, 3, 4]] print("Original list: ", nums_x) nums_y = copy.copy(nums_x) print("\nCopy of the said list:") print(nums_y) nums = {"x":1, "y":2, 'zz':{"z":3}} nums_copy = copy.deepcopy(nums) print("\nOriginal dictionary :") print(nums)
"""def sayHello(name = "user"): print("hello",name) sayHello('nazli') sayHello("melis") sayHello() def total(num1,num2): return num1+num2 print("total is",total(10,20))""" def yasHesapla(yil): return 2021-yil def emeklilik(yil,isim): yas=yasHesapla(yil) emeklilik=65-yas if emeklilik>0: print(f"emekliliginize {emeklilik} yıl kaldı.") else: print("emekli oldunuz.") emeklilik(2001,'Fehmi')
import random def guess(): x=int(input("enter a number between 1 and 20: ")) computer_guess=random.randint(1,20) win=True while win: if x>computer_guess: x=int(input("enter smaller number: ")) elif x<computer_guess: x = int(input("enter bigger number: ")) else: print("You win") win=False # guess() def computer_guess(x): low=1 high=x feedback='' while feedback!='c': if low!=high: guess=random.randint(low,high) else: guess=low feedback=input(f"Is {guess} too high(H), too low(L) or correct".lower()) if feedback=='h': high=guess-1 elif feedback=='l': low=guess+1 print(f"Yay! The computer guessed your number, {guess}") computer_guess(10)
''' In this project, you will visualize the feelings and language used in a set of Tweets. This starter code loads the appropriate libraries and the Twitter data you'll need! ''' import json from textblob import TextBlob import matplotlib.pyplot as plt from wordcloud import WordCloud #Search term used for this tweet #We want to filter this out! tweetSearch = "automation" #Get the JSON data tweetFile = open("tweets_small.json", "r") tweetData = json.load(tweetFile) tweetFile.close() # Textblob sample: tb = TextBlob("You are a brilliant computer scientist.") print(tb.polarity) # Part 1 #Create a Sentiment List polarityList = [] #[OPTIONAL] Subjectivity subjectivityList = [] #Get Sentiment Data for tweet in tweetData: tweetblob = TextBlob(tweet["text"]) polarityList.append(tweetblob.polarity) #[OPTIONAL] Subjectivity subjectivityList.append(tweetblob.subjectivity) print(polarityList) print(subjectivityList) #Part 2 #Create the Graph plt.hist(polarityList, bins=[-1.1, -.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1.1]) plt.xlabel('Polarities') plt.ylabel('Number of Tweets') plt.title('Histogram of Tweet Polarity') plt.axis([-1.1, 1.1, 0, 100]) plt.grid(True) plt.show() #[OPTIONAL] Subjectivity plt.plot(polarityList, subjectivityList, 'ro') plt.xlabel('Polarity') plt.ylabel('Subjectivity') plt.title('Tweet Polarity vs Subjectivity') plt.axis([-1.1, 1.1, -0.1, 1.1]) plt.grid(True) plt.show() #Part 3 ''' Use textblob.words to get just the words ''' combinedTweets = "" for tweet in tweetData: combinedTweets += tweet['text'] #Create a Combined Tweet Blob tweetblob = TextBlob(combinedTweets) #Filter Words wordsToFilter = ["about", "https", "in", "the", "thing", "will", "could", tweetSearch] filteredDictionary = dict() for word in tweetblob.words: #skip tiny words if len(word) < 2: continue #skip words with random characters or numbers if not word.isalpha(): continue #skip words in our filter if word.lower() in wordsToFilter: continue #don't want lower case words smaller than 5 letters if len(word) < 5 and word.upper() != word: continue; #Try lower case only, try with upper case! filteredDictionary[word.lower()] = tweetblob.word_counts[word.lower()] #Create the word cloud wordcloud = WordCloud().generate_from_frequencies(filteredDictionary) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
# --- Define your functions below! --- def intro(): print("Welcome to ChatBot!") print("All you have to do is respond to my prompts and hit enter!") name = input("What is you name? ") return name def hello(text): text.lower() if text == "hello" or text == "hi" or text == "yes": print("Salutations!") # --- Put your main program below! --- def main(): name = intro() print("Hello, ", name) #greeting = input("(say hello back?)") #hello(greeting) while True: answer = input("What do you want to talk about?") print("That's cool!") # DON'T TOUCH! Setup code that runs your main() function. if __name__ == "__main__": main()
x=int(input("enter the number:")) a=1 while(X>0): a=a*x x=x-1 print("x of the number is:") print(x)
nn = int(input()) v = str(input()) a=v[::-1] for i in a: if i=="a" or i=="e" or i=="i" or i=="o" or i=="u" or i=="A" or i=="E" or i=="I" or i=="O" or i=="U": continue else: print(i,end="")
class Usuario: #Metodo constructor que se inicia cada vez que se crea una instancia def __init__(self, nombre, apellido): self.nombre = nombre self.apellido = apellido # no es necesaria la palabra 'self', puede ser cualquiera, por ser el primer argumento del método def saludo(self): print('Nombre y Apellido:', self.nombre, self.apellido) #Herencia de la clase Usuario: #HEREDA EL CONSTRUCTOR INIT CON SUS ATRIBUTOS Y TODOS SUS MÉTODOS class Admin(Usuario): def superSaludo(self): print('Me llamo', self.nombre, self.apellido, 'y soy ADMIN xd') # === EXTENDIENDO EL MÉTODO INIT DE LA CLASE PADRE EN LAS CLASES HIJAS: # FORMA 1 class Profesor(Usuario): def __init__(self, nombre, apellido): # Al definir un __init__, se ignorará el __init__ de la clase padre Usuario.__init__(self, nombre, apellido) #Esto para indicar que se quiere ejecutar el __init__ de la clase padre print('Aquí se puede extender el __init__ de la clase padre') # FORMA 2 class Alumno(Usuario): def _init__(self, nombre, apellido): super().__init__(nombre, apellido) # super() hace referencia a la clase padre, no hace falta el self print('Aquí también se puede extender el __init__ de la clase padre') usuario1 = Usuario('Felipe', 'Perez') usuario2 = Usuario('Juan', 'Martinez') usuario1.saludo() usuario2.saludo() usuario2.nombre = 'NombreCambiado' usuario2.saludo() # del usuario2.nombre # del usuario2 admin = Admin('Admin', 'Mamon') admin.saludo() admin.superSaludo() profe = Profesor('Nomb_Profe1', 'Ape_Profe1') profe.saludo()
import unittest from unittest import mock import challenges class T100BeginnerTests(unittest.TestCase): """Tests for beginner challenge""" def setUp(self): self.store1 = challenges.Store(222.2,33333.3,3,True,['item1','item2','item3']) def test_101_variables(self): '''Check init is correct''' self.assertEqual(self.store1.size, 222.2) self.assertEqual(self.store1.item_list, ['item1','item2','item3']) self.assertEqual(self.store1.off_license, True) class T200IntermediateTests(unittest.TestCase): '''Test for intermediate challenges''' def setUp(self): self.store1 = challenges.Store(222.2,33333.3,3,True,['item1','item2','item3']) self.store2 = challenges.Store(232323.3232,32323.3,5,False,['choco','beer','crisps']) def test_201_store_str(self): '''Check the store object prints correctly''' expected = 'Store size: 232323.3232 ¦ Sales of the month: 32323.3 ¦ Different category count: 5 ¦ Off license: False' self.assertEqual(repr(self.store2),expected) def test_202_update_sales(self): '''Check the update sales method''' self.store1.update_monthly(123.4) self.assertEqual(self.store1.sales_month, 123.4) def test_203_update_items(self): '''Check the update items method''' self.store1.add_item('wine') self.assertEqual(self.store1.item_list,['choco','beer','crisps','wine']) class T300AdvancedTests(unittest.TestCase): '''Check for advanced tests''' def setUp(self): self.store1 = challenges.Store(222.2,33333.3,3,True,['item1','item2','item3']) self.store1.update_monthly(900000.0) self.store1.update_monthly(1.0) self.store1.update_monthly(3298.0) self.store1.update_monthly(3.0) def test_301_get_max(self): '''Check the max_sales method''' self.assertEqual(self.store1.max_sales(),900000.0) def test_302_get_min(self): '''Check the min_sales method''' self.assertEqual(self.store1.min_sales(), 1.0) def test_303_get_avg(self): '''Check the avg_sales method''' self.assertEqual(self.store1.avg_sales(), 225825.5)
# for x in range(1, 11): # print("\U0001f600" * x) times = 1 while times != 10: print("\U0001f600" * times) times += 1
# 作业一 # import math # a = float(input('输入a的值')) # b = float(input('输入b的值')) # c = float(input('输入c的值')) # if b**2-4*a*c>0: # x1=(-b+math.sqrt(b**2-4*a*c))/2*a # x2=(-b-math.sqrt(b**2-4*a*c))/2*a # print(x1,x2) # elif b**2-4*a*c==0: # x1=x2 =(-b+math.sqrt(b**2-4*a*c))/2*a # print(x1) # else: # print('很抱歉,方程无解') # 作业二 # import random # correctCount = 0 # count = 0 # number1 = random.randint(0,100) # number2 = random.randint(0,100) # if number1 < number2: # number1,number2 = number2,number1 # answer = eval(input('计算'+str(number1)+"-"+str(number2)+"=")) # if answer == number1 - number2: # print('😀恭喜你,小可爱,你赢了!') # correctCount += 1 # else: # print('😟小智障,你算错了.\n',number1,"-",number2,'is',number1 - number2) # 作业三: # num = float(input('输入今天是一周中的哪一天的数字')) # day = float(input('输入今天之后到未来某天的天数')) # num_ = (num + day)%7 # if num_ == 0: # print('周日') # elif num_ == 1: # print('周一') # elif num_ == 2: # print('周二') # elif num_ == 3: # print('周三') # elif num_ == 4: # print('周四') # elif num_ == 5: # print('周五') # else: # print('周六') # 作业四 # num1,num2,num3=map(int,input('请输入三个整数:').split()) # min = min(num1,num2,num3) # max = max(num1,num2,num3) # print('升序为:%d %d %d' %(min,num1+num2+num3-min-max,max)) # 作业五 # weight1= float(input("Enter weight package 1 :")) # price1 = float(input("Enter price for package 1 :")) # weight2= float(input("Enter weight for package 2 :")) # price2 = float(input("Enter price for package 2 :")) # permj1 = float(price1 / weight1) # permj2 = float(price2 / weight2) # if permj1 > permj2: # print("package 2 has the better price ") # else: # print("package 1 has the better price ") # 作业六 # month = eval(input('输入月份')) # year = eval(input('输入年份')) # leapyear = float(year % 4) # if month == 1 or month ==3 or month ==5 or month ==7 or month ==8 or month ==10 or month ==12: # month1 = 31 # elif month == 4 or month ==6 or month ==9 or month ==11: # month = 30 # elif leapyear == 0 and month == 2: # month = 29 # else: # month =28 # print(year,'年',month,'月','有',month1,'天') # 作业七 # import random # a = input('猜测硬币正反面:') # b = random.randint(0,1) # if b == 1: # print('正面') # else: # print('反面') # if a == b: # print('猜对了') # else: # print('猜错了') # 作业八 # import numpy as np # res = np.random.choice(['0','1','2']) # user = input("请输入你的选择['0','1','2']") # if res == user: # print('平局') # elif res == '1' and user == '0': # print("😟很遗憾,你输了") # elif res == '0' and user == '2': # print("😟你输了") # elif res == '2 'and user == '1': # print("😟你输了") # else: # print('💪恭喜你,再来一局') # 作业九 # month = 0 # cent = 0 # year = 0 # Q = 0 # H = 0 # yearFlug = 1 # monthFlug = 1 # dayFlug = 1 # while(yearFlug): # yearTemp = int(input("Please Enter Year :(eg:2008):")) # if yearTemp > 0 : # yearFlug = 0 # else: # print("Sorry, Enter Wrong Year,try again Please") # cent = yearTemp //100 # year = yearTemp % 100 # while(monthFlug): # monthTemp = int(input("Please Enter month:(eg:10):")) # if monthTemp > 0 and monthTemp <= 12: # monthFlug = 0 # else: # print("Sorry, Enter Wrong month ,Try again Please") # if monthTemp ==1 or monthTemp ==2: # year -= 1 # month = monthTemp + 12 # else:month = monthTemp # while(dayFlug): # dayTemp = int(input("Please Enter day:(eg:21):")) # if dayTemp > 0 and dayTemp <= 28: # dayFlug = 0 # elif (monthTemp == 1 or monthTemp == 3 or monthTemp == 5 \ # or monthTemp == 7 or monthTemp == 8 or monthTemp == 10 \ # or monthTemp == 12) \ # and (dayTemp >28 and dayTemp <= 31): # dayFlug = 0 # elif (monthTemp == 4 or monthTemp == 6 or monthTemp == 9 or monthTemp == 11)\ # and (dayTemp >28 and dayTemp <= 30): # dayFlug = 0 # elif (monthTemp == 2) and (yearTemp %4 ==0 and yearTemp%100 != 0) and(dayTemp == 29): # dayFlug = 0 # else: # print("Sorry ,Enter Wrong day,Try again Please") # Q = dayTemp # H = (Q + ((26 * ( month + 1 ) / 10 ) // 1 ) \ # + (( year / 4 ) // 1) + year \ # + (( cent / 4 ) // 1) \ # + ( 5 * cent) )\ # % 7 # if H == 0: # weekDay = "Sat" # print('今天是星期六') # elif H == 1: # weekDay = "Sun" # print('今天是星期日') # elif H == 2: # weekDay = "Mon" # print('今天是星期一') # elif H == 3: # weekDay = "Tue" # print('今天是星期二') # elif H == 4: # weekDay = "Wed" # print('今天是星期三') # elif H == 5: # weekDay = "Thu" # print('今天是星期四') # elif H == 6: # weekDay = "Fri" # print('今天是星期五') # # 作业十: # import numpy as np # print('扑克牌的大小分别是:1(Area)、2、3、4、5、6、7、8、9、10、11(Jack)、12(Queen)、13(King)') # print('扑克牌的花色:1:梅花、2:红桃、3:方块、4:黑桃') # number = int(input('输入你选择的牌的大小:')) # number1 = np.random.randint(1,14) # if number == 1: # print('你选择的是:Area') # number2 = np.random.randint(1,5) # if number2 ==1: # print('梅花') # elif number2 ==2: # print('红桃') # elif number2 ==3: # print('方块') # else: # print('黑桃') # print('你选择的是:2') # if number2 ==1: # print('梅花') # elif number2 ==2: # print('红桃') # elif number2 ==3: # print('方块') # else: # print('黑桃') # print('你选择的是:Jack') # number2 = np.random.randint(1,5) # if number2 ==1: # print('梅花') # 作业十一: # num = float(input('判断是否是回文数,请输入一个三位整数:')) # num1 = num//100 # num2 = num%100 # if num1 == num2: # print('是一个回文数') # else: # print('不是回文数') # 作业十二: # a = float(input('请输入第一条边长:')) # b = float(input('请输入第一条边长:')) # c = float(input('请输入第一条边长:')) # if a+b>c and a+c>b and b+c>a: # l=a+b+c # print('周长为%d' %(a+b+c)) # else: # print('非法输入,请重新输入') # 作业十三: # def main(): # num_z = 0 # num_f = 0 # sum = 0 # data = 1 # while data != 0: # data = int(input("请输入数字:")) # if data > 0: # num_z += 1 # elif data < 0: # num_f +=1 # sum += data # print("正数个数为:%d"%num_z) # print("负数个数为:%d"%num_f) # aver = sum / (num_z + num_f) # print("平均值为:%2f"%aver) # main() # 作业十四: #money = [1000] # for i in range(10): # x = money[i] * 1.05 # money.append(x) # print("十年后的学费:%.2f"%money[10]) # print("现在及十年后的学费:%.2f"%sum(money)) # 作业十五: # count = 0 # for i in range(100,1000): # if i % 5 == 0 and i % 6 == 0: # print(i,end = ' ') # count += 1 # if count % 10 ==0: # print("\n") # else: # continue # 作业十六: # n2 = 0 # n3 = 0 # while n2 ** 2 < 12000: # n2 += 1 # print(n2)#110 # while n3 ** 3 < 12000: # n3 += 1 # print(n3-1) # 作业十七: # def main(): # sum = 0 # for i in range(1,50001): # sum += 1/i # print(sum) # main() # 作业十八: # def main(): # sum = 0 # for i in range(1,98,2): # sum += i / (i + 2) # print(sum) # main() # 作业十九: # def main(): # sum = 0 # for i in range(1,100000): # sum += 4 * (-1) ** (i + 1) / (2 * i - 1) # print(sum) # main() # 作业二十: # def main(): # for i in range(1,10000): # sum = 0 # for j in range(1,i): # if i % j ==0: # sum += j # if i ==sum: # print(i) # main() # 作业二十一: # def main(): # count = 0 # for i in range(1,8,2): # for j in range(2,8): # if i != j: # print(i,j) # count += 1 # print(count) # main() # 作业二十二: # number = [] # he = 0 # for i in range(10): # data = float(input("请输入10个数字:")) # number.append(data) # average = sum(number) / len(number) # for x in number: # cha = (average - x) ** 2 # he += cha # st = (he / (len(number)-1)) ** 0.5 # print("The mean is %f"%average) # print("The Standard deviation is %f"%st)
import sys def counting(input_file, output_file): drug_counter = get_drug_info(input_file,5,2,1,3,4) #start writing our new output txt using the output name provided with open(output_file, 'w') as output: #header row for output file header = "drug_name,num_prescriber,total_cost \n" output.write(header) #iterate through drugs in dictionary for i in drug_counter: drug_in_question = drug_counter[i] to_write = i + "," + str(drug_in_question['num_prescribers']) + "," + str(drug_in_question['total_cost']) + "\n" output.write(to_write) output.close() def get_drug_info(input_file, row_length, doctor_first_ix, doctor_last_ix, drug_name_ix, drug_cost_ix): #get drug info will open the input file and get the necessary information. #there are several parameters to account for the fact that column names or order may change drug_counter = {} prescription_ids = [] skipped_input_header = False counter = 0 input("i hate everything") with open(input_file, "r") as filestream: for line in filestream: print(counter) if counter%1000==0: print(counter) else: pass counter+=1 if skipped_input_header: line_info = line.split(',') #testing if all of the fields exist if len(line_info)!=row_length or line_info[0] in prescription_ids: pass else: #preventing duplicate prescriptions prescription_ids.append(line_info[0]) #getting the relevant information from the line drug_prescriber = line_info[doctor_first_ix] + " " + line_info[doctor_last_ix] drug_name = line_info[drug_name_ix] drug_cost = line_info[drug_cost_ix].rstrip() #if the drug is already in the dictionary, update values if drug_name in drug_counter: specific_drug = drug_counter[drug_name] if drug_prescriber in specific_drug['prescribers']: pass else: specific_drug['prescribers'].append(drug_prescriber) specific_drug['num_prescribers']+=1 specific_drug['total_cost']+=float(drug_cost) #if the drug does not exist yet, create a new key else: drug_counter[drug_name]={} specific_drug = drug_counter[drug_name] specific_drug['prescribers'] = [drug_prescriber] specific_drug['num_prescribers'] = 1 specific_drug['total_cost'] = float(drug_cost) #not copying the first header row else: skipped_input_header=True return(drug_counter) if __name__ == "__main__": in_file = sys.argv[1] out_file = sys.argv[2] counting(in_file,out_file)
secret = 'swordfish' pw = ' ' count = 0 auth = False max_attaempt = 5 while pw != secret: count += 1 if count > max_attempt: break if count == 3: continue pw = input(f"{count}: What's the secret word ?") else: auth = True print('.Authorized' if auth else "Calling the FBI...")
#Program to calculate multiplication table of any number for n number of times. print("Multiplication table calculator.") x=int(input("Enter a number for multiplication table: ")) y=int(input("Enter a value for the number of multiplication tables: ")) for i in range(1,y+1): print(i,"x",x ,"= ",x*i)
def three_sum(nums): if len(nums) < 3: return [] nums.sort() res = set() for i, v in enumerate(nums[:-2]): if i > 1 and nums[i] == nums[i - 1]: continue d = {} for x in nums[i + 1:]: if x not in d: d[-v - x] = 1 else: res.add((v, -v - x, x)) return map(list, res) map = three_sum([-1, 0, 1, -3, 0, 3]) print(map)
class Count: def __init__(self, func): self.count = 0 self.func = func def __call__(self, *arg, **kwargs): self.count += 1 print( f"{str(self.func)} is called, already called for {self.count} times <including current>" ) return self.func(*arg, **kwargs) @Count def test(num): return 1 + num for i in range(10): print(test(i)) ### Class decorator with args class _Cache(object): def __init__(self, function, max_hits=10, timeout=5): self.function = function self.max_hits = max_hits self.timeout = timeout self.cache = {} def __call__(self, *args): return self.function(*args) def Cache(function=None, max_hits=10, timeout=5): if function: return _Cache(function) else: def wrapper(function): return _Cache(function, max_hits, timeout) return wrapper @Cache(max_hits=100, timeout=50) def double(x): return x * 2 print(double(23))
''' Question 2 Level 1 Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 ''' ''' num = int(raw_input('Enter number for factorial: ')) prod = 1 # # while (num > 1): # prod = num*prod # num = num -1 for i in range(1,num+1): prod = prod*i print prod ''' def factorial(num): prod = 1 for i in range(num,1,-1): prod = prod*i return prod print factorial(8)
''' Question 7 Level 2 Question Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j Note: i=0,1.., X-1; j=0,1,...,Y-1 Example Suppose the following inputs are given to the program: 3,5 Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] ''' rows = int(raw_input('Enter the # of rows for 2d array ')) cols = int(raw_input('Enter the # of cols for 2d array ')) #creating a 2d array (list of lists) with 0 a2d = [[0 for x in range(cols)] for x in range(rows)] for r in range(rows): for c in range(cols): a2d[r][c] = r*c print a2d print type(a2d)
def find_substrings(inpstr): p1_v_list = ['a','an','ana','anan','anana'] #p2_c_list = ['b','n','ba','na','ban','nan','bana','nana','banan','banana'] p2_c_list =['b'] out =[] for i in range(len(inpstr)+1): for j in range(1,len(inpstr)+1): if i < j: out.append(inpstr[i:j]) v_words = find_vowel_words(out) c_words = find_conso_words(out) p1_score = 0 for w in p1_v_list: p1_score = p1_score + v_words.count(w) p2_score = 0 for w in p2_c_list: p2_score = p2_score + c_words.count(w) if p1_score > p2_score: print 'Player 1 (who made vowel words) won with score of %d !' %(p1_score) elif p1_score < p2_score: print 'Player 2 (who made consonant words) won with score of %d !' %(p2_score) else: print 'Its a tie!' return None def find_vowel_words(inplist): vowel_words = [] for word in inplist: if word[0] in 'aeiou': vowel_words.append(word) return vowel_words def find_conso_words(inplist): conso_words = [] for word in inplist: if word[0] in 'aeiou': pass else: conso_words.append(word) return conso_words find_substrings('banana')
''' Let's learn about list comprehensions! You are given three integers X,Y and Z representing the dimensions of a cuboid. You have to print a list of all possible coordinates on a 3D grid where the sum of Xi + Yi + Zi is not equal to N. If X=2, the possible values of Xi can be 0, 1 and 2. The same applies to Y and Z. Input Format Four integers X,Y,Z and N each on four separate lines, respectively. Output Format Print the list in lexicographic increasing order. ''' def cuboid_coord(X,Y,Z,N): li = [[x,y,z] for x in range(X+1) for y in range(Y+1) for z in range(Z+1) if (x+y+z)!=N] return li #print cuboid_coord(1,1,1,2) print cuboid_coord(2,2,2,2)
''' Question 8 Level 2 Question: Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world ''' def word_sort(): inp = raw_input('Enter comma separated words ') inp_li = [x for x in inp.split(',')] inp_li.sort() return inp_li w = word_sort() print ','.join(w)
import fractions import math def mixed_fraction(s): s1,s2 = s.split('/') num,den = int(s1),int(s2) signnum,signden = 1,1 if num < 0: signnum = -1 if den < 0: signden = -1 if den == 0: raise ZeroDivisionError num = abs(num) den = abs(den) q,r = divmod(num,den) d = den g = fractions.gcd(r,d) r,d = r/g, d/g if r == 0: return str(q*signnum*signden) elif q == 0: return '%d/%d' %(r*signden*signnum,d) else: return '%d %d/%d' %(q*signnum*signden,r,d) print mixed_fraction('6011832/-8408661')
import re def unscramble_eggs(word): w = re.sub('egg','',word) return w print unscramble_eggs('FeggUNegg KeggATeggA')
#example anagrams: # dog, god # act, cat # add, dad # rats, arts # NOT: art, rats # NOT: ada, add # NOT: dog, dog # Write a function find_anagrams that returns a list of the strings which # are anagrams of another word in an input list. #Example: #find_anagrams(['bat', 'rats', 'god', 'dog', 'cat', 'arts', 'star']) #=> ['rats', 'god', 'dog', 'arts', 'star'] #get first word from list #do permutations of the word #check if the permutations exist in the list #if yes then append the word to the output list import itertools inp_list = ['bat', 'rats', 'god', 'dog', 'cat', 'arts', 'star'] def find_anagrams(inp_list): out=[] for word in inp_list: perms = [x for x in itertools.permutations(word)] perms2=[''.join(x) for x in perms] for w in perms2: if w in inp_list and w!=word: out.append(w) return list(set(out)) print find_anagrams(inp_list)
''' Question: Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: john@google.com Then, the output of the program should be: john In case of input data being supplied to the question, it should be assumed to be a console input. Pattern: (d\w+)\W(d\w+) d Lowercase letter d. \w+ One or more word characters. \W A non-word character. ''' import re em = raw_input('Enter email address ') pat = "(\w+)@((\w+\.)+(com))" print pat result = re.match(pat,em) print result.group(1) print result.group(2) print result.group(3) ''' emailAddress = raw_input() pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print r2.group(1) '''
''' Question: Define a class, which have a class parameter and have a same instance parameter. Hints: Define a instance parameter, need add it in __init__ method You can init a object with construct parameter or set the value later ''' class Animal: animal_type = 'Animal' def __init__(self, animal_type = None): self.animal_type = animal_type tiger = Animal("Wild") print '%s animal type is %s' %(Animal.animal_type,tiger.animal_type) dog =Animal() dog.animal_type = 'Pet' print '%s animal type is %s' %(Animal.animal_type, dog.animal_type)
#sort the list of lists below based on ascending number of length of each sublist import operator def sort_sublists(): liofli = [['a','b','c'],['d'],['e','f'],['g','h','i','j','k']] out = [] d = dict() for li in liofli: d[tuple(li)] = len(li) sorted_d = sorted(d.items(),key = operator.itemgetter(1)) for k,v in sorted_d: out.append(list(k)) return out print sort_sublists()
# binary search, O(log(m*n)) # we can use binary search to search row first, and then col # but can also use smart index to do binary search only once class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or not matrix[0]: return False m, n = len(matrix), len(matrix[0]) left, right = 0, m*n-1 while left + 1 < right: mid = left + (right - left)//2 t = matrix[mid//n][mid%n] if t == target: return True elif t > target: right = mid else: left = mid return matrix[left//n][left%n] == target or \ matrix[right//n][right%n] == target """ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true """
# method 2, use dictionary # for every word, produce all the possible candidates from word, # do not have to go through all the words, and only # check all the candidates that are no longer than word # note: the pair can either be on the left or on the right # time O(n*k*k), where k is the length of the word, and n is number of words class Solution(object): def palindromePairs(self, words): # input requirement: words are all unique word_dict = {words[i]:i for i in range(len(words))} # lengths can help reduce the number of candidates, but not necessary lengths = list(set(len(word) for word in words)) lengths.sort() res = [] for i, word in enumerate(words): # each word only looks for a pair whose length is no more than word rword = word[::-1] # mistake: word.reverse(), python str has no .reverse() if rword in word_dict and rword != word: # when candidate length is equal to word # word is on the left, because rword can also find word res.append([i, word_dict[rword]]) for length in lengths: # candidate length is less than word if length == len(word): break # word is on the left if self.isPalindrome(rword[:len(word)-length]) \ and rword[len(word)-length:] in word_dict: res.append([i, word_dict[rword[len(word)-length:]]]) # word is on the right if self.isPalindrome(rword[length:]) \ and rword[:length] in word_dict: res.append([word_dict[rword[:length]], i]) return res def isPalindrome(self, word): # or simply use return word == word[::-1] for i in range(len(word)//2): if word[i] != word[len(word)-1-i]: return False return True # method 1: brute force, combine every pair, and then if it is a palindrome # time O(n*n*k), space O(1) class Solution1(object): def palindromePairs(self, words): """ :type words: List[str] :rtype: List[List[int]] """ n = len(words) res = [] for i in range(n): for j in range(n): if j == i: continue s = words[i]+words[j] if self.isPalindrome(s): res.append([i,j]) return res def isPalindrome(self, s): if not s: return True left, right = 0, len(s)-1 while left < right: if s[left] != s[right]: return False else: left += 1 right -= 1 return True
# method 2: union find # the seats of the couple don't matter, # as long as the couple is sitting together # paired seats can be saved into a dictionary class Solution(object): def minSwapsCouples(self, row): """ :type row: List[int] :rtype: int """ d = {} for i in range(0, len(row), 2): d[row[i]] = row[i+1] d[row[i+1]] = row[i] cnt = 0 s = set(d.keys()) while s: x1 = s.pop() y1 = d[x1] if y1 != x1^1: # when a swap is needed # {x1:y1, x2:y2} becomes {x1:x2, y1:y2} cnt += 1 x2 = x1^1 y2 = d[x2] d[y1] = y2 d[y2] = y1 s.remove(x2) else: s.remove(y1) return cnt """ N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1). The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th seat. Example 1: Input: row = [0, 2, 1, 3] Output: 1 Explanation: We only need to swap the second (row[1]) and third (row[2]) person. Example 2: Input: row = [3, 2, 0, 1] Output: 0 Explanation: All couples are already seated side by side. Note: len(row) is even and in the range of [4, 60]. row is guaranteed to be a permutation of 0...len(row)-1. """
# https://leetcode.com/problems/kth-largest-element-in-an-array/submissions/ # method 3: quick selection, time O(n) # quick selection, O(n) time, O(1) space import random class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if k > len(nums) or k <= 0: return float('inf') return self.findKthSmallest(nums, 0, len(nums)-1, len(nums)-k+1) def findKthSmallest(self, nums, left, right, k): mid = self.partition(nums, left, right) if mid-left+1 == k: return nums[mid] if mid-left+1 > k: return self.findKthSmallest(nums, left, mid-1, k) else: return self.findKthSmallest(nums, mid+1, right, k-(mid-left+1)) def partition(self, nums, left, right): guess = random.randint(left, right) # randomly choose a pivot nums[guess], nums[right] = nums[right], nums[guess] pivot = nums[right] end = left # nums[end] >= pivot for i in range(left, right): if nums[i] < pivot: nums[end], nums[i] = nums[i], nums[end] end += 1 nums[end], nums[right] = nums[right], nums[end] return end # method 2: time: O(k+(n-k)*log(k)), space: O(k) of the min heap import heapq class Solution2(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ heap = nums[:k] heapq.heapify(heap) for i in range(k, len(nums)): if nums[i] > heap[0]: heapq.heappushpop(heap, nums[i]) # heapq.heappop(heap) # heapq.heappush(heap, nums[i]) return heap[0] # method 1: use python built-in heapq # and its builtin functions: heapq.nlargest(), heapq.nsmallest(). # time: O(n+k*log(n)), space: O(n) for a heap import heapq class Solution1(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if k > len(nums): return -1 heapq.heapify(nums) # O(n) klargest = heapq.nlargest(k, nums) # O(k*log(n)) return klargest[-1] """ Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤ array's length. """
#!/usr/bin/env python import sys t = float(sys.argv[1]) c = float(sys.argv[2]) print "Temperature is: %s"%t print "Cooling factor is: %s"%c ct = 0 while (t > 1): t=t*c ct = ct + 1 print "Temperature reached 1 after %s iterations"%ct
# SEARCHING (Chapter 15 from programming arcade games) file = open('data/villains.txt', 'r') # open file to read (creates object named file) print(file) for line in file: print(line.strip()) # .strip() method removes spaces and \t \r from beginning and end for line in file: print("Hello", line.strip()) # can't go through twice because it read through the document and is # now at the bottom, need to reset if you want to print again file.close() ''' # you can also open a file to write (overwrites all previous) file = open('data/villains.txt', 'w') # file.write("Lee The Merciless") ''' # open a file to append (adds on to bottom of the file) # file = open("data/villains.txt", "a") # file.write("Lee The Merciless\n") # file.close() # Read the file into an array (list) file = open("data/villains.txt", "r") ''' villains = [] for line in file: villains.append(line.strip()) ''' villains = [x.strip() for x in file] print(villains) # Linear Search key = "The Vindictive Fury" # what we are searching for i = 0 # index for the loop while i < len(villains) - 1 and key != villains[i]: i += 1 if i < len(villains): print("Found", key, "at position", i) # Binary Search key = "The Barbarous Harlot" lower_bound = 0 upper_bound = len(villains) - 1 found = False # loop until we find it while lower_bound <= upper_bound and not found: middle_pos = (upper_bound + lower_bound) // 2 if villains[middle_pos] < key: lower_bound = middle_pos + 1 elif villains[middle_pos] > key: upper_bound = middle_pos - 1 else: found = True if found: print(key, "was found at position", middle_pos) else: print(key, "was not found in the list")
def check(word, longword): while (1): if len(longword) < len(word): return 0 c = longword[len(word)-1] for i in range(len(word))[::-1]: if c == word[i]: print(i,longword[len(word)-1-i:2*len(word)-1-i]) if longword[len(word)-1-i:2*len(word)-1-i] == word: return 1 else: longword = longword[len(word):] import sys sys.stdin = open('sample_input.txt') T = int(input()) for test_case in range(1, T + 1): word = input() longword = input() print(f'#{test_case} {check(word, longword)}')
# ------------- sequence -------------- from datetime import timedelta, date class DateRangeSequence: def __init__(self, start_date, end_date): self.start_date = start_date self.end_date = end_date self._range = self._create_range() def _create_range(self): days = [] current_day = self.start_date while current_day < self.end_date: days.append(current_day) current_day += timedelta(days=1) return days def __getitem__(self, day_no): return self._range[day_no] def __len__(self): return len(self._range) drc = DateRangeSequence(date(2020, 9, 17), date(2020, 9, 20)) print(drc[0]) print(drc[-1]) # ------------- container -------------- # # def mark_coordinate(grid, coord): # if 0 <= coord.x < grid.width and 0 <= coord.y < grid.height: # grid[coord] = 1 class Boundaries: def __init__(self, width, height): self.width = width self.height = height def __contains__(self, coord): x, y = coord return 0 <= x < self.width and 0 <= y < self.height class Grid: def __init__(self, width, height): self.width = width self.height = height self.limits = Boundaries(width, height) def __contains__(self, coord): return coord in self.limits # Grid2도 동작은 하지만 코드를 이해하기 어렵다 # Boundaries를 재사용하긴 하지만 Grid 클래스가 더 낫다고 생각됨 # class Grid2(Boundaries): # def __init__(self, width, height): # super(Grid2, self).__init__(width, height) # self.limits = Boundaries(width, height) def mark_coordinate(grid, coord): if coord in grid: print('Mark:1') else: print('Mark:0') g = Grid(4, 4) mark_coordinate(g, [5, 3]) mark_coordinate(g, [3, 3]) # g = Grid2(4, 4) # mark_coordinate(g, [5, 3]) # mark_coordinate(g, [3, 3]) # ------------- dynamic attributes -------------- class DynamicAttributes: def __init__(self, attribute): self.attribute = attribute def __getattr__(self, attr): if attr.startswith('fallback_'): name = attr.replace("fallback_", "") return f"[fallback resolved] {name}" raise AttributeError(f"{self.__class__.__name__}에는 {attr} 속성이 없음") print() dyn = DynamicAttributes('value') print(dyn.attribute) print(dyn.fallback_test) dyn.__dict__["fallback_new"] = "new value" print(dyn.fallback_new) print(getattr(dyn, 'something', 'default')) # print(dyn.something) print(dyn.__getattr__('fallback_new1')) # ------------- callable -------------- from collections import defaultdict, UserList class CallCount: def __init__(self): self._count = defaultdict(int) def __call__(self, argument): self._count[argument] += 1 return self._count[argument] cc = CallCount() print(cc(1)) print(cc(1)) print(cc(1)) print(cc(2)) print(cc(3)) print(cc(2)) # ------------- Note on Python -------------- class BadList(list): def __getitem__(self, index): print(self.__class__) value = super().__getitem__(index) if index % 2 == 0: prefix = '짝수' else: prefix = '홀수' return f"[{prefix}] {value}" bl = BadList((0, 1, 2, 3, 4, 5)) print(bl) # "".join(bl) class GoodList(UserList): def __getitem__(self, index): print(self.__class__) value = super().__getitem__(index) if index % 2 == 0: prefix = '짝수' else: prefix = '홀수' return f"[{prefix}] {value}" bl = GoodList((0, 1, 2, 3, 4, 5)) print(bl) print(";".join(bl)) # ------------- Design by Contract -------------- import os print(os.getenv('DBHOST'))
from statistics import mean import math def k_means(k_list,elements,no_of_elements,value_of_k): i=j=0 diff=[] copy_list=[] count=0 while True: copy_list=k_list[0].copy() count+=1 for i in range(no_of_elements): diff=[] for j in range(value_of_k): diff.append(abs(k_list[0][j]-elements[i])) indx=diff.index(min(diff)) k_list[indx+1].append(elements[i]) print(count,"iteration:") for i in range(1,(value_of_k+1),1): print("k",(i),":",k_list[i],"=",k_list[0][i-1]) for i in range(value_of_k): k_list[0][i]=mean(k_list[i+1]) if copy_list == k_list[0] : print("Since the clusters consists same elements, the final clusters are:") for i in range(1,(value_of_k+1),1): print("k",(i),":",k_list[i],"=",k_list[0][i-1]) break for i in range(value_of_k): k_list[i+1]=[] #------------------------------------------------------------------------# #print the list no_of_elements=int(input("Enter total number of elements:")) value_of_k=int(input("Enter value of K:")) elements=[] print("Enter the elements:") for i in range(no_of_elements): elements.append(int(input())) k_list = [[] * no_of_elements for p in range(no_of_elements)] for j in range(value_of_k): k_list[0].append(elements[j]) print("elements:",elements) print("random k values:",k_list[0]) k_means(k_list,elements,no_of_elements,value_of_k)
from typing import Tuple from adventure.level import build_level_0, build_level_1 from adventure.scene import Scene def check_level_up_conditions(scene: Scene, level: int) -> Tuple[Scene, int]: # Todo: use set to check level up conditions if scene.score >= scene.level_up_points: if "Key" in [item.name.title() for item in scene.backpack]: level += 1 scene.to_build_level = True else: print("< You get enough scores but you need a key to level up") else: print("< you don't have enough scores to level up") return scene, level def build_level(ready_levels, level): scene, command = ready_levels[level]() scene.to_build_level = False return scene, command def main(): level = 0 ready_levels = [build_level_0, build_level_1] scene, command = build_level(ready_levels, level) while True: if scene.to_build_level: if level >= len(ready_levels): scene.endgame() return else: scene, command = build_level(ready_levels, level) if scene.health <= 0: scene.gameover() return action = input( f"L:{scene.level} S:{scene.score} H:{scene.health} I:{len(scene.backpack)}> " ).lower() if action in command.commands: command.exec(action) elif action == "^": scene, level = check_level_up_conditions(scene, level) else: print("< Unknown action") if __name__ == "__main__": main()
i=lambda:map(int,input().split()) a,b = i() y = 1 while True: if(3*a > 2*b): print(y) break else: y = y+1 a = 3*a b = 2*b
''' # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail ''' inp=lambda:map(int,input().split()) a, b, c, m = inp() p, ans = 0, 0 def binaryExponentiation(b, n, m): if(n==0): return 1 elif n%2 == 0: #n is even return binaryExponentiation((b*b)%m,n//2, m) else: #n is odd return (b*binaryExponentiation((b*b)%m,(n-1)//2, m))%m def modInverse(a, m) : m0 = m y = 0 x = 1 if (m == 1) : return 0 while (a > 1) : # q is quotient q = a // m t = m # m is remainder now, process # same as Euclid's algo m = a % m a = t t = y # Update x and y y = x - q * y x = t # Make x positive if (x < 0) : x = x + m0 return x p = binaryExponentiation(a, b, m) ans = ((p%m) * modInverse(c, m))%m print(int(ans))
#-------------------------题目链接---------------- #https://leetcode-cn.com/problems/find-the-most-competitive-subsequence/ #博客:https://www.cnblogs.com/yeshengCqupt/p/14057027.html #----------------------------------------------- import copy class Solution: def mostCompetitive(self, nums, k): ''' 垃圾dfs ''' self.res = list() vis = [0] * len(nums) r = list() def dfs(nums, u, r, vis): if u == k: self.res.append(copy.deepcopy(r)) return for i in range(0, len(nums)): if vis[i] == 0: r.append(nums[i]) vis[i] = 1 dfs(nums[i + 1:], u + 1, r, vis[i+1:]) vis[i] = 0 r.pop() dfs(nums, 0, r, vis) self.res.sort() return self.res[0] def mostCompetitive1(self, nums, k): ''' 单调栈 ''' stack = list() count = len(nums) - k for i in range(0, len(nums)): if not stack or nums[i] >= stack[-1]: stack.append(nums[i]) else: while stack and nums[i] < stack[-1] and count != 0: stack.pop() count -= 1 stack.append(nums[i]) while count != 0: stack.pop() count -= 1 return stack s = Solution() # nums = [2,4,3,3,5,4,9,6] nums = [3,5,2,6] k = 4 k = 2 res = s.mostCompetitive1(nums, k) print(res)
#---------------------题目链接----------------- #https://leetcode-cn.com/problems/smallest-string-with-a-given-numeric-value/ #-------------------------------------------- class Solution: def getSmallestString(self, n: int, k: int) -> str: k -= n con = k // 25 sur = k % 25 return 'a' * (n-con-1) + chr(97 + sur) + 'z' * con
from datetime import date current_date = date.today() print(str(current_date)) User_file = open('user.txt', 'r+') user_login = {} for line in User_file: user_details = line.split(", ") user_login[user_details[0]] = str(user_details[1]).replace("\n", "")#strip away user.txt line by line print("LOG ON BELOW")#log in screen start User_name = "" User_password = "" while True:#log in loop begin User_name = input("Enter your Username: ") if user_login.get(User_name):#finds user name in dictionary print("welcome"+ " "+ User_name) break else: print("Wrong user id ") while True: User_password = input("Enter your password: ") if User_password == user_login[User_name]: print("Correct password ") break else: print("Wrong user password ")#log in loop end #at this point user should be able to log in #admin vs other user menu selection here if User_name == ("admin"): print("Please select one of the following options:\n", "r - register user\n", "a - add task\n", "va - view all task\n", "vm - view my task\n","St - view statistics\n" , "e - exit\n") else: print("Please select one of the following options:\n", "a - add task\n", "va - view all task\n", "vm - view my task\n", "e - exit\n") User_selection = input(" Enter your selection here: ")#user selection input if User_selection == str("r") and User_name == ("admin"): New_passwordS = open('user.txt', 'r+') New_passwordS.read() print("Register a new user ID and password ") New_userId = input("Enter your new user Id here: ") while New_userId == New_passwordS: print("that user exists ") New_userId = input("Enter your new user Id here: ") new_passwordreg = input("Enter your new password here: ") Confirmation = input("Confirm your password: ") while new_passwordreg != Confirmation: print("Passwords don't match: ") new_passwordreg = input("Enter your new password here: ") Confirmation = input("Confirm your password: ") New_passwordS.read() New_passwordS.write("\n" + New_userId + ", " + new_passwordreg) New_passwordS.close() elif User_selection == str("a"): add_tasks = open('tasks.txt', 'r+') Task_user = input("Task user name: ") task_title1 = input("Task title: ") task_description1 = input("Task description: ") task_due1 = input("Task due date: ") task_compl = "No" add_tasks.read() add_tasks.write("\n" + Task_user + ", " + task_title1 + ", " + task_description1 + ", " + str(current_date) + ", " + task_due1 + ", " + task_compl) add_tasks.close() elif User_selection == str("va"):#formatting on screen task_display_open = open('tasks.txt', 'r') for task_display in task_display_open: line_task = task_display.split(", ") print("Task assigned to User: " + "\t" + line_task[0] + "\n" + "Task title: " + "\t" + line_task[1] +"\n" + "Task description: " + line_task[2] +"\n" + "Task assigned date: " + "\t" + line_task[3]+"\n" + "Task due date: " + "\t" + line_task[4]+"\n" + "task Completed: " + line_task[5]) task_display_open.close() elif User_selection == str("vm"): task_view_open = open('tasks.txt', 'r') for line in task_view_open: user = line.split(", ") if User_name == user[0]: print("Task assigned to User: " + "\t" + user[0] + "\n" + "Task title: " + "\t" + user[1] +"\n" + "Task description: " + user[2] +"\n" + "Task assigned date: " + "\t" + user[3]+"\n"+ "Task due date: " + "\t" + user[4]+"\n"+ "task completed: " + user[5])#formatting on screen task_view_open.close() elif User_selection.lower() == str("st") and User_name == ("admin"): task_display_open1 = open('tasks.txt', 'r') User_file1 = open('user.txt', 'r') total_user = 0 total_tasks = 0 for line in task_display_open1: total_tasks += 1 for line in User_file1: total_user +=1 print("The total number of tasks: " + str(total_tasks))#user display " " print("The total number of users: "+ str(total_user))#user display " " # elif User_selection == str("e"): exit(0)
import random print("Random Number Generator!") count = input("How many numbers would you like to generate?") count = int(count) for p in range(count): number = random print(random.randint(random.randint(0,100), random.randint(101,1000))) print("Enjoy your numbers!")
import pygame, math, sys, time iterations = int(sys.argv[1]) # No. of iterations to run the fractal generating algorithm. pygame.init() # Create a new surface and window to display the fractal tree pattern. surface_height, surface_width = 1200, 1000 main_surface = pygame.display.set_mode((surface_height,surface_width)) pygame.display.set_caption("My Fractal Tree Pattern") def draw_tree(order, theta, sz, posn, heading, color=(0,0,0), depth=0): """ Function to draw the fractal tree pattern. :param order: integer, No. pf divisions from the tree :param theta: float, Angle by which to rotate the next fractal pattern :param sz: integer, Size of new fractal pattern :param posn: float, Position for the new pattern :param heading: float, width of the pattern :param color: integer, color of the new patter :param depth: integer, depth of the fractal """ trunk_ratio = 0.3 # The relative ratio of the trunk to the whole tree. # Length of the trunk trunk = sz * trunk_ratio delta_x = trunk * math.cos(heading) delta_y = trunk * math.sin(heading) (u, v) = posn newpos = (u + delta_x, v + delta_y) pygame.draw.line(main_surface, color, posn, newpos) if order > 0: """ Make 2 halfs for the fractal tree symmetrical around the trunk. """ if depth == 0: color1 = (255, 0, 0) color2 = (0, 0, 255) else: color1 = color color2 = color # make the recursive calls, which can be considered as zooming into the fractal pattern. newsz = sz*(1 - trunk_ratio) draw_tree(order-1, theta, newsz, newpos, heading-theta, color1, depth+1) draw_tree(order-1, theta, newsz, newpos, heading+theta, color2, depth+1) def main(): theta = 0 for _ in range(iterations): theta += 0.01 # Update the angle main_surface.fill((255, 255, 0)) draw_tree(9, theta, surface_height*0.9, (surface_width//2, surface_width-50), -math.pi/2) pygame.display.flip() time.sleep(20) # Makes the fractal tree visible for 20 sec. main() # Calling the main function
def fuel(mass): fuel_mass = mass // 3 - 2 if fuel_mass <= 0: return 0 return fuel_mass + fuel(fuel_mass) with open("in.txt", "r") as f: components = f.read().splitlines() components = map(int, components) fuel_per_component = map(fuel, components) print(sum(fuel_per_component))
# Assignment: Checkerboard # Write a program that prints a 'checkerboard' pattern to the console. # Your program should require no input and produce console output that looks like so: # * * * * # * * * * # * * * * # * * * * # * * * * # * * * * # * * * * # * * * * # Copy # Each star or space represents a square. On a traditional checkerboard you'll see alternating squares of red or black. # In our case we will alternate stars and spaces. The goal is to repeat a process several times. This should make you think of looping. def checkers(pattern1, pattern2): for i in range(0, 100): if i % 2 != 0: print(pattern1) else: print(pattern2) checkers('* * * *', ' * * * *')
# Assignment: Fun with Functions # Create a series of functions based on the below descriptions. # Odd/Even: # Create a function called odd_even that counts from 1 to 2000. # As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number. # Your program output should look like below: # Number is 1. This is an odd number. # Number is 2. This is an even number. # Number is 3. This is an odd number. # ... # Number is 2000. This is an even number. # Copy # Multiply: # Create a function called 'multiply' that iterates through each value in a list # (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5. # The function should multiply each value in the list by the second argument. For example, let's say: # a = [2,4,10,16] # Copy # Then: # b = multiply(a, 5) # print b # Copy # Should print [10, 20, 50, 80 ]. # Hacker Challenge: # Write a function that takes the multiply function call as an argument. # Your new function should return the multiplied list as a two-dimensional list. # Each internal list should contain the number of 1's as the number in the original list. Here's an example: # def layered_multiples(arr) # # your code here # return new_array # x = layered_multiples(multiply([2,4,5],3)) # print x # # output # >>>[[1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]] def oddeven(myrange): for i in myrange: if i % 2 == 0: print (i, 'even') else: print (i, 'odd') oddeven(range(1, 2001)) def multiply(mylist): newlist = [] for i in mylist: newlist += [i*5] print(newlist) multiply([1,2,3,4,5]) def layered(mylist): newlist = [] for i in mylist: glue = [] for x in range(0, i): glue.append(1) newlist += [glue] print (newlist) layered([1,2,3,4,5])
def table(): count = 0 x = 1 while count < 13: if count < 2: x = 1 count += 1 print (x * 1, x * 2, x * 3, x * 4, x * 5, x * 6, x * 7, x * 8, x * 9, x * 10, x * 11, x * 12) elif count > 1: x += 1 count += 1 print (x * 1, x * 2, x * 3, x * 4, x * 5, x * 6, x * 7, x * 8, x * 9, x * 10, x * 11, x * 12) table()
# Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. # # The following variables contain values as described below: # # balance - the outstanding balance on the credit card # # annualInterestRate - annual interest rate as a decimal # # monthlyPaymentRate - minimum monthly payment rate as a decimal # # For each month, calculate statements on the monthly payment and remaining balance. # At the end of 12 months, print out the remaining balance. # Be sure to print out no more than two decimal digits of accuracy - so print # # Remaining balance: 813.41 # instead of # # Remaining balance: 813.4141998135 # So your program only prints out one thing: # the remaining balance at the end of the year in the format: # # Remaining balance: 4784.0 # A summary of the required math is found below: # # Monthly interest rate= (Annual interest rate) / 12.0 # Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance) # Monthly unpaid balance = (Previous balance) - (Minimum monthly payment) # Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) # # We provide sample test cases below. # We suggest you develop your code on your own machine, # and make sure your code passes the sample test cases, # before you paste it into the box below. # # Test Cases to Test Your Code With. # Be sure to test these on your own machine - # and that you get the same output! - # before running your code on this webpage! # always start with importing unittest TestCase because this is test driven development! from unittest import TestCase def CreditCardBalance(balance, annualInterestRate, monthlyPaymentRate): """ :param balance: float of starting balance for credit card :param annualInterestRate: float of annualised interest rate :param monthlyPaymentRate: float of monthly payment :return: remaining balance after 12 months of payments accounting for interest """ # iterate over 12 months across a year for months in range(1, 12+1): # calculate interest payment interest = balance * (annualInterestRate/12) # add interest to balance balance += interest # calculate minimum payment with interest already included payment = balance * monthlyPaymentRate # take payment away from balance balance -= payment problem_one = round(balance, 2) print("Remaining balance: " + str(problem_one)) return round(balance, 2) # define tests class TestCreditCardBalance(TestCase): def test_balance_42_interest_02_monthly_payments_0_04(self): balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 response = CreditCardBalance(balance, annualInterestRate, monthlyPaymentRate) self.assertEqual(31.38, response) def test_balance_484_interest_02_monthly_payments_0_04(self): balance = 484 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 response = CreditCardBalance(balance, annualInterestRate, monthlyPaymentRate) self.assertEqual(361.61, response)
# The greatest common divisor of two positive integers is the # largest integer that divides each of them without remainder. # # For example, # # gcd(2, 12) = 2 # # gcd(6, 12) = 6 # # gcd(9, 12) = 3 # # gcd(17, 12) = 1 # # Write an iterative function, gcdIter(a, b), # that implements this idea. # # One easy way to do this is to begin with a test value equal to the smaller of the two input arguments, # and iteratively reduce this test value by 1 until you either reach a case # where the test divides both a and b without remainder, # or you reach 1. import unittest from unittest import TestCase def gcdIter(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' # Your code here testValue = min(a, b) # loop until testValue divides both a and b evenly while a % testValue != 0 or b % testValue != 0: testValue -= 1 return testValue class TestGcdIter(TestCase): def test_2_and_12(self): a = 2 b = 12 response = gcdIter(a, b) self.assertEqual(response, 2) def test_6_and_12(self): a = 6 b = 12 response = gcdIter(a, b) self.assertEqual(response, 6) def test_9_and_12(self): a = 9 b = 12 response = gcdIter(a, b) self.assertEqual(response, 3) def test_17_and_12(self): a = 17 b = 12 response = gcdIter(a, b) self.assertEqual(response, 1)
import funciones import argparse import pandas as pd import matplotlib import matplotlib.pyplot as plt def parser(): parser = argparse.ArgumentParser(description='Selecciona los datos que quieres ver') parser.add_argument('x', type=str, help='Moneda Seleccionada') parser.add_argument('y', type=str,help='Fecha') args = parser.parse_args() return args def main(): args = parser() x,y = args.x, args.y df = pd.read_csv("OUTPUT/final_table.csv") info(df,x,y) #Historical graphic - Shows all the 'Close Prices' from 2013 to 2019 funciones.graphic(df) #S. Desviation graphic - Shows the variation rate for each day. funciones.variation(df).plot.bar() plt.gcf().set_size_inches(10,10) plt.show() def info(table,x,y): print('-------------------------------------------------------------') print('\n') print(f"Características moneda {x} a fecha {y}") print('\n') filter_table=monedaFecha(table,x,y) print(filter_table) print('\n') print('-------------------------------------------------------------') print('\n') print(f'CAPITALIZACION BURSATIL: Media Historica de {x} (Desde 2013 a 2019)') print('\n') print(table.groupby(['Currency']).get_group(x).mean()[3:4]) print('\n') print('-------------------------------------------------------------') print('\n') print('PRECIO DE CIERRE DE TODAS MONEDAS EN MEDIAS, D.STA, GAUSS..') print('\n') print(funciones.describe(table)) return filter_table def monedaFecha(final_table,x,y): filter_table=funciones.descriptions(final_table, x, y) return filter_table if __name__ == '__main__': main()
""" Errores sintácticos y lógicos Modificaremos el problema del concepto anterior y agregaremos adrede una serie de errores tipográficos. Este tipo de errores siempre son detectados por el intérprete de Python, antes de ejecutar el programa. A los errores tipográficos, como por ejemplo indicar el nombre incorrecto de la función, nombres de variables incorrectas, falta de paréntesis, palabras claves mal escritas, etc. los llamamos errores SINTACTICOS. Un programa no se puede ejecutar por completo sin corregir absolutamente todos los errores sintácticos. Existe otro tipo de errores llamados ERRORES LOGICOS. Este tipo de errores en programas grandes (miles de líneas) son más difíciles de localizar. Por ejemplo un programa que permite hacer la facturación pero la salida de datos por impresora es incorrecta. """ # Hallar la superficie de un cuadrado conociendo el valor de un lado. '''Ejempos funciones internas input y print Ejempos funcion interna int() numeros enteros''' lado=input("Ingrese la medida del lado del cuadrado:") lado=int(lado) superficie=lado*lado print("La superficie del cuadra es:", superficie) #Programa con error sintactico ''' lado=int(input("Ingrese la medida del lado del cuadrado:")) superficie=lado*lado print("La superficie del cuadrado es") print(Superficie) ''' # Programa con error logico ''' print("Programa con error logico") lado=int(input("Ingrese la medida del lado del cuadrado:")) superficie=lado*lado*lado print("La superficie del cuadrado es") print(superficie) '''
''' Estructura condicional compuesta. Cuando se presenta la elección tenemos la opción de realizar una actividad u otra. Es decir tenemos actividades por el verdadero y por el falso de la condición. Lo más importante que hay que tener en cuenta que se realizan las actividades de la rama del verdadero o las del falso, NUNCA se realizan las actividades de las dos ramas. ''' # Realizar un programa que solicite ingresar dos números distintos y muestre por pantalla el mayor de ellos. num1=int(input("Ingrese primer valor:")) num2=int(input("ingrese segundo valor:")) print("El valor mayor es") if num1>num2: print(num1) else: print(num2) # Utilizando == if num1==num2: print("Son iguales") else: print("Son distintos")
""" Estructura de programación secuencial Cuando en un problema sólo participan operaciones, entradas y salidas se la denomina una estructura secuencial.""" # Realizar la carga del precio de un producto y la cantidad a llevar. Mostrar cuanto se debe pagar (se ingresa un valor entero en el precio del producto) precio=int(input("Ingrese el precio del producto:")) cantidad=int(input("Ingrese la cantidad de productos a llevar:")) importe=precio*cantidad print("El importe a pagar es") print(importe) ''' print('-------------------') print("El importe a pagar es" , importe) '''
from random import randint from random import random import math class sim_Anl: def search(self, problem): visited = 0 expanded = 0 current = problem.state_initialization() neighbors = [] threshold = 10 # counter = 1 T = 1 T_min = .001 while True: T = sim_Anl.schedule(self, T) if T < T_min: print("visited", visited) print("expanded", expanded) return current for action in problem.actions(current): neighbor = problem.result(current, action) visited += 1 neighbors.append(neighbor) index = randint(0, len(neighbors) - 1) nextState = neighbors[index] ap = sim_Anl.acceptance_probability(self, current, nextState, T) if ap > random(): current = nextState # counter += 1 expanded += 1 def schedule(self, T): alpha = .8 T *= alpha return T def acceptance_probability(self, current, nextState, T): if current.cost > nextState.cost: return 1 else: return math.e ** ((current.cost - nextState.cost) / T) class Hill: visited = 0 expanded = 0 def standard_search(self, problem): current = problem.state_initialization() best_cost = current.cost best_node = current while not problem.goal_test(current): Hill.expanded += 1 for action in problem.actions(current): neighbor = problem.result(current, action) Hill.visited += 1 neighbor_cost = neighbor.cost if neighbor_cost < best_cost: best_cost = neighbor_cost best_node = neighbor current = best_node return current def random_search(self, problem): Hill.expanded = 0 Hill.visited = 0 current = problem.state_initialization() best_cost = current.cost while not problem.goal_test(current): Hill.expanded += 1 increase_list = [] for action in problem.actions(current): neighbor = problem.result(current, action) neighbor_cost = neighbor.cost Hill.visited += 1 if neighbor_cost < best_cost: increase_list.append(neighbor) index = randint(0, len(increase_list) - 1) print("index", index) current = increase_list[index] return current def first_choise_search(self, problem): Hill.expanded = 0 Hill.visited = 0 current = problem.state_initialization() while not problem.goal_test(current): Hill.expanded += 1 for action in problem.actions(current): neighbor = problem.result(current, action) neighbor_cost = neighbor.cost Hill.visited += 1 if neighbor_cost < current.cost: current = neighbor break return current def random_reset_search(self, problem): h = Hill() best = 0 result = [] for i in range(0, 5): result.append(h.standard_search(problem)) temp = 0 for i in range(0, 5): pcost = problem.path_cost(result[i], result[i]) if pcost > temp: temp = pcost best = result[i] return best class Genetic: N = 200 def search(self, problem): generationNum = 1 population = [] populationFitness = [] for i in range(0, Genetic.N): population.append(problem.state_initialization()) while True: best_possible = problem.best_value() for indiv in population: populationFitness.append(problem.fitness(indiv)) if problem.fitness(indiv) > .9 * best_possible: print("generationNum", generationNum) return indiv populationFitness.sort() print("generationNum", generationNum) print("average", sum(populationFitness) / max(len(populationFitness), 1)) print("best", populationFitness.pop()) print("worst", populationFitness.pop(0)) newPopulation = [] for i in range(0, Genetic.N): x = Genetic.randomSelection(self, population) y = Genetic.randomSelection(self, population) child = Genetic.produce(self, x, y) if (1 / (len(newPopulation) + 1)*2) > random(): child = Genetic.mutate(self, child) newPopulation.append(child) population = newPopulation generationNum += 1 def randomSelection(self, population): index = randint(0, len(population) - 1) return population[index] def produce(self, x, y): child = [] c = randint(0, len(x) - 1) for i in range(0, len(x)): if i < c: child.append(x[i]) else: child.append(y[i]) return child def mutate(self, child): n = randint(0, len(child) - 1) if child[n] == 0: child[n] = 1 else: child[n] = 0 return child
# Classe de Venda de Carros class Venda(): # Método contrutor def __init__(self, carro, cliente, vendedor, desconto,preco, data, forma_pagamento): self.carro = carro self.cliente = cliente self.vendedor = vendedor self.desconto = desconto self.preco = preco self.preco_final = float(self.preco) - ((float(self.preco) * float(self.desconto))/100) self.data = data self.forma_pagamento = forma_pagamento # Imprimir a nota fiscal def print_nota_fiscal(self): print('== Nota Fiscal ==\n\n' f'Cliente: {self.cliente}\n' f'Vendedor: {self.vendedor}\n' f'Carro vendido: {self.carro}\n' f'Preço Original: R${self.preco}\n' f'Desconto: {self.desconto}%\n' f'Preço Final: R${self.preco_final}\n' f'Data da Venda: {self.data}\n' f'Forma de Pagamento: {self.forma_pagamento}\n' '== // ==\n\n') # Método para converter a classe em texto (string) def to_string(self): return self.cliente + ';' + self.vendedor + ';' + self.carro + ';' \ + str(self.preco) + ';' + str(self.desconto) + ';' \ + str(self.preco_final) + ';' + self.data + ';' \ + self.forma_pagamento
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- """ Example of controlling temporary file and directory """ from tempfile import TemporaryFile, NamedTemporaryFile, TemporaryDirectory # Example-1) Create a nonamed temp file. write a text and read it with TemporaryFile('w+t') as f: f.write('Hello, World!') f.seek(0) print(f.read()) # Example-2) Create a named temp file, write a text and read it with NamedTemporaryFile('w+t') as f: f.write("Hello, World!!!") f.seek(0) print(f.read()) # Example-3) Same as 'Example-2'. but disable the 'delete' option with NamedTemporaryFile('w+t', delete=False) as f: f.write("Hello, World!!!") f.seek(0) print(f.read()) # Example-4) Create a named temp file in a specific location. with NamedTemporaryFile('w+t', prefix="example", suffix=".txt", dir="/tmp") as f: print(f.name) # Example-5) Create a nonamed temp directory with TemporaryDirectory() as tmpdir: print(tmpdir)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import Optional class BSTNode(object): def __init__(self, data: int, parent: Optional['BSTNode'] = None, left: Optional['BSTNode'] = None, right: Optional['BSTNode'] = None) -> None: self.data = data self.parent = parent self.left = left self.right = right def __str__(self) -> str: return str(self.__dict__) def __repr__(self) -> str: return str(self) @staticmethod def deepcopy(node: 'BSTNode') -> 'BSTNode': parent = BSTNode.deepcopy(node.parent) if node.parent else None left = BSTNode.deepcopy(node.left) if node.left else None right = BSTNode.deepcopy(node.right) if node.right else None return BSTNode(data=node.data, parent=parent, left=left, right=right) def find(self, data: int) -> Optional['BSTNode']: node = self while node is not None: if data < node.data: node = node.left elif data > node.data: node = node.right else: return node return None def minimum(self) -> 'BSTNode': node = self while node.left is not None: node = node.left return node def maximum(self) -> 'BSTNode': node = self while node.right is not None: node = node.right return node def insert(self, data: int) -> bool: node = self while node is not None: if data < node.data: if node.left is None: node.left = BSTNode(data=data, parent=node) return True node = node.left elif data > node.data: if node.right is None: node.right = BSTNode(data=data, parent=node) return True node = node.right else: # NOTE: Invalid case because data already exists return False return True def delete(self, data: int) -> bool: node = self.find(data) if node is None: return False if node.left and node.right: node.data = node.left.maximum().data return node.left.delete(node.data) elif node.left: node.parent.right = node.left elif node.right: node.parent.left = node.right del node return True class BST: def __init__(self): self.root: Optional['BSTNode'] = None def find(self, data: int) -> Optional['BSTNode']: if self.root is None: return None return self.root.find(data) def insert(self, data: int) -> bool: if self.root is None: self.root = BSTNode(data=data) return True return self.root.insert(data) def delete(self, data: int) -> bool: if self.root is None: return False return self.root.delete(data)
""" File: word_guess.py ------------------- My project is an improved version of the Word Guessing Game. It allows a multiplayer mode (up to 4 players) """ import random LEXICON_FILE = "Lexicon.txt" # File to read word list from INITIAL_GUESSES = 8 # Initial number of guesses player starts with NUM_OF_PLAYERS = 3 DEFAULT_FILE = 'word-guessing-banner.jpg' def play_game(secret_word): secret_word_length = len(secret_word) hidden_string = "" new_list = [] guesses = INITIAL_GUESSES correct_guesses = 0 score = 100 for i in range(secret_word_length): new_list.append("-") new_string = "" for elem in new_list: new_string += str(elem) print("The word now looks like this: " + new_string) print("You have " + str(INITIAL_GUESSES) + " guesses left") while guesses != 0 and str(new_list) != secret_word: # do not allow user to enter more than one character user_guess = input("Type a single letter here, then press enter: ") new_string = "" found = False for i in range(secret_word_length): if secret_word[i] == user_guess.upper(): new_list[i] = user_guess.upper() found = True if found: print("That guess is correct.") correct_guesses += 1 for elem in new_list: new_string += str(elem) if secret_word.find(user_guess.upper()) == -1: guesses -= 1 print("There are no "+ user_guess.upper() + "'s in the word") score = score - (score * 0.2) #with each incorrect guess, we remove 20% of the score if new_string == secret_word: print("Congratulations, the word is: " + new_string) break; else: if guesses == 0: print("Sorry, you lost. The secret word was: " + secret_word) else: print("The word now looks like this: " + new_string) print("You have " + str(guesses) + " guesses left") return score def open_lexicon_file(filename): cs_words = [] with open(filename) as f: for line in f: cs_words.append(line.strip()) return cs_words def get_word(): """ This function returns a secret word that the player is trying to guess in the game. This function initially has a very small list of words that it can select from to make it easier for you to write and debug the main game playing program. In Part II of writing this program, you will re-implement this function to select a word from a much larger list by reading a list of words from the file specified by the constant LEXICON_FILE. """ cs_words = open_lexicon_file(LEXICON_FILE) random_choice = random.choice(cs_words) return random_choice def return_highest_scoring_player(score_list): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v = list(score_list.values()) max_val = max(v) min_val = min(v) k = list(score_list.keys()) if max_val != min_val: return k[v.index(max(v))] + " wins!" else: return "It's a tie!" def output_game_intro(): print("WELCOME TO MY WORD GUESSING GAME!") print("-----------------------------------") print("-------- -------") print("------------ -----------") print("-------------- -------------") print("-------- -------") print("-----------------------------------") print("Rules are simple: the computer will generate a random word for you to guess. Enter one character at a time, until you guess the final word. The player who guesses more words, or in less steps wins the round.") print("Each player has a maximum of " + str(INITIAL_GUESSES) + " guesses.") print("Ready?? Let's get started!!") print("-----------------------------------") def main(): """ To play the game, we first select the secret word for the player to guess and then play the game using that secret word. """ output_game_intro() score_list = {} for i in range(NUM_OF_PLAYERS): print("This is Player " + str(i+1) + "'s turn.") secret_word = get_word() current_player = "Player " + str(i+1) score_list[current_player] = play_game(secret_word) print(str(current_player) + " scored: " + str(score_list[current_player])) print("-----------------------------------") print("At the end of this round, here are the results: ") print(return_highest_scoring_player(score_list)) # This provided line is required at the end of a Python file # to call the main() function. if __name__ == "__main__": main()
from words import words import random word = list(random.choice([x for x in words if len(x) < 4])) ans = [] guessed = [] print(len(word)) def play(): life = 5 while word != ans: if life != 0: print("guess a letter: ") a = input() guessed.append(a) if a in word: ans.append(a) else: life -= 1 if life == 1: print("last life!") else: print(f"{life} lifes left.") print(" ".join([x.capitalize() if x in guessed else "_" for x in word])) else: print(f"you lost, the ans way {word}") return print("yey, you won") play()
#Answer to CIS 122 #1 Simple Printing - https://www.codewars.com/kata/cis-122-number-1-simple-printing print "Hello World!" course = "CIS 122" name = "Intro to Software Design" print "Welcome to " + course + ": " + name a = 1.1 b = 3 c = a + b print "The sum of " + str(a) + " and " + str(b) + " is " + str(c) x_print("Hello World!") language = "Python" adjective = "Fun" x_print("Learning",language,"is",adjective) pizzas = 10 slices_per_pizza = 8 total_slices = pizzas * slices_per_pizza x_print("There are",total_slices,"slices in",pizzas,"pizzas.") x_print(total_slices, ": It must be dinner time!",sep = "")
#Answer to Return Negative - https://www.codewars.com/kata/return-negative/train/python def make_negative( number ): return number*-1 if number > 0 else number
""" How many letter of the Alphabet? So I wanted to write a function to find out how many letters of the alphabet would appear in a given text. I've learned that Python has made some optimizations to string manipulations to the point where creating functions to match C-style programming is not needed. """ import time def check_alphabets_v1(words): """ This was my first attempt. Comming from a C-programming background, my approach was to create as much from scratch as possible. """ alphabets = [0] * 26 a = ord('a') z = ord('z') for x in words.lower(): char = ord(x) if a <= char and char <= z: alphabets[char - a] = 1 results = 0 for x in alphabets: results += x return results def check_alphabets_v2(words): """ This was my optimization of the first approach. """ alphabets = [True] * 26 a = ord('a') z = ord('z') results = 0 for x in words.lower(): char = ord(x) if a <= char and char <= z: pos = char - a if alphabets[pos]: alphabets[pos] = False results += 1 if results == 26: return results return results def check_alphabets_v3(words): """ This is an approach that utilizes python for what it is. The stats on this seems to look pretty good. """ alphabet = "abcdefghijklmnopqrstuvwxyz" results = 0 for letter in alphabet: if letter not in words: break results += 1 return results def debug(text, func): start_time = time.time() characters = func(text) end_time = time.time() print("========= Start Test ===============") print("text: {0}".format(text)) print("function: {0}".format(func)) print("contains {0} letters of the alphabet".format(characters)) print("time: {0}".format(end_time - start_time)) print("========= End Test ===============\n\n") sample = "Hello World" debug(sample, check_alphabets_v1) debug(sample, check_alphabets_v2) sample = "the quick brown fox jumps over the lazy dog" * 100 debug(sample, check_alphabets_v1) debug(sample, check_alphabets_v2) debug(sample, check_alphabets_v3)
from dataclasses import dataclass from typing import Union, List from game.model.entity.item.item import Item @dataclass class Inventory: capacity: int items: List[Item] selected_item: Union[int, None] def __init__(self, capacity: int, items: List[Item] = None): self.capacity = capacity if items is None: self.items = [] else: self.items = items self.selected_item = None def open(self) -> None: """ Opens inventory and sets cursor to the default position (no item is selected) """ self.selected_item = -1 def is_opened(self) -> bool: """ Returns true if inventory is already opened; false otherwise """ return self.selected_item is not None def get_selected_item(self) -> Union[Item, None]: """ Returns an item under a cursor, i.e. selected one """ if self.selected_item is None or self.selected_item == -1: return None return self.items[self.selected_item] def get_selected_item_position(self) -> Union[int, None]: """ Returns position of the selected item in the inventory """ return self.selected_item def no_item_selected(self) -> bool: """ Returns true if no item selected; false otherwise """ return self.selected_item is None or self.selected_item == -1 def select_next_item(self) -> int: """ Moves cursor to the next item if exists; either sets cursor to the default position (no item is selected) :return: new position of cursor """ if not self.is_opened(): self.open() self.selected_item += 1 if self.selected_item == len(self.items): self.selected_item = -1 return self.selected_item def select_previous_item(self) -> int: """ Moves cursor to the previous item if exists; either sets cursor to the default position (no item is selected) :return: new position of cursor """ if not self.is_opened(): self.open() self.selected_item -= 1 if self.selected_item < -1: self.selected_item = len(self.items) - 1 return self.selected_item def remove_item(self, item: Item) -> Union[Item, None]: """ Removes specified item from the inventory. Returns removed item. """ try: self.items.remove(item) except ValueError: return None return item def remove_item_by_position(self, position: int) -> Union[Item, None]: """ Removes item from the inventory by its position in it. Returns removed item. """ if 0 <= position < len(self.items): return self.remove_item(self.items[position]) return None def add_item(self, item: Item) -> bool: """ Adds an item to the inventory. Returns true if succeeded; false otherwise. """ if len(self.items) < self.capacity: self.items.append(item) return True return False def size(self): """ Returns size of the inventory, i.e. number of items in it """ return len(self.items) def close(self) -> None: """ Closes inventory """ self.selected_item = None
from abc import ABC, abstractmethod from game.model.entity.item.item import Item class InventoryKeeper(ABC): """ Enables ability to keep items. """ def __init__(self, limit): self.inventory = [] self.limit = limit def pick_item(self, item: Item): """ Try to add an item to inventory. :param item: item """ if len(self.inventory) + 1 <= self.limit: self.inventory.append(item) def remove_item(self, item: Item): self.inventory.remove(item) @abstractmethod def use_item(self, item: Item): """ Try to add an item to inventory. :param item: item """ pass
''' This Python exam will involve implementing a bank program that manages bank accounts and allows for deposits, withdrawals, and purchases. ''' def init_bank_accounts(accounts, deposits, withdrawals): ''' Loads the given 3 files, stores the information for individual bank accounts in a dictionary, and calculates the account balance. Accounts file contains information about bank accounts. Each row contains an account number, a first name, and a last name, separated by vertical pipe (|). Example: 1|Brandon|Krakowsky Deposits file contains a list of deposits for a given account number. Each row contains an account number, and a list of deposit amounts, separated by a comma (,). Example: 1,234.5,6352.89,1,97.60 Withdrawals file contains a list of withdrawals for a given account number. Each row contains an account number, and a list of withdrawal amounts, separated by a comma (,). Example: 1,56.3,72.1 Stores all of the account information in a dictionary named 'bank_accounts', where the account number is the key, and the value is a nested dictionary. The keys in the nested dictionary are first_name, last_name, and balance, with the corresponding values. Example: {'1': {'first_name': 'Brandon', 'last_name': 'Krakowsky', 'balance': 6557.59}} This function calculates the total balance for each account by taking the total deposit amount and subtracting the total withdrawal amount. ''' bank_accounts = {} #insert code return bank_accounts def round_balance(bank_accounts, account_number): '''Rounds the given account balance.''' pass def get_account_info(bank_accounts, account_number): '''Returns the account information for the given account_number as a dictionary. Example: {'first_name': 'Brandon', 'last_name': 'Krakowsky', 'balance': 6557.59} If the account doesn't exist, returns None. ''' pass def withdraw(bank_accounts, account_number, amount): '''Withdraws the given amount from the account with the given account_number. Raises a RuntimeError if the given amount is greater than the available balance. If the account doesn't exist, prints a friendly message. Rounds and prints the new balance. ''' pass def deposit(bank_accounts, account_number, amount): '''Deposits the given amount into the account with the given account_number. If the account doesn't exist, prints a friendly message. Rounds and prints the new balance. ''' pass def purchase(bank_accounts, account_number, amounts): '''Makes a purchase with the total of the given amounts from the account with the given account_number. Raises a RuntimeError if the total purchase, plus the sales tax (6%), is greater than the available balance. If the account doesn't exist, prints a friendly message. Rounds and prints the new balance. ''' pass def calculate_sales_tax(amount): '''Calculates and returns a 6% sales tax for the given amount.''' pass def main(): #load and get all account info bank_accounts = init_bank_accounts('accounts.txt', 'deposits.csv', 'withdrawals.csv') #for testing #print(bank_accounts) while True: #print welcome and options print('\nWelcome to the bank! What would you like to do?') print('1: Get account info') print('2: Make a deposit') print('3: Make a withdrawal') print('4: Make a purchase') print('0: Leave the bank') # get user input option_input = input('\n') # try to cast to int try: option = int(option_input) # catch ValueError except ValueError: print("Invalid option.") else: #check options if (option == 1): #get account number and print account info account_number = input('Account number? ') print(get_account_info(bank_accounts, account_number)) elif (option == 2): # get account number and amount and make deposit account_number = input('Account number? ') # input cast to float amount = float(input('Amount? ')) deposit(bank_accounts, account_number, amount) elif (option == 3): # get account number and amount and make withdrawal account_number = input('Account number? ') #input cast to float amount = float(input('Amount? ')) withdraw(bank_accounts, account_number, amount) elif (option == 4): # get account number and amounts and make purchase account_number = input('Account number? ') amounts = input('Amounts (as comma separated list)? ') # convert given amounts to list amount_list = amounts.split(',') amount_list = [float(i) for i in amount_list] purchase(bank_accounts, account_number, amount_list) elif (option == 0): # print message and leave the bank print('Goodbye!') break if __name__ == "__main__": main()
import math r = int(input()) h = int(input()) print(math.pi*(r**2)*h/3)
""" Problem description: A plus B, but you can't use '+'. """ class Solution: """ @param a: An integer @param b: An integer @return: The sum of a and b """ def aplusb(self, a, b): # write your code here if a==0: return b elif b==0: return a sum=a&b b=a^b a=sum<<1 while a: sum=a&b b=a^b a=sum<<1 return b
def isprime(n, p): for e in p: if n % e == 0: return False; return True def primos(): p = set() for e in range(2, 100): if isprime(e, p): p.add(e) return p print(primos())
'''Rasterizador''' import numpy as np import collections def clearscreen(screen): return screen.fill(0) def changepixel(imagen, fila, columna , valor): '''f,c,v es....''' imagen[fila][columna] = valor Point = collections.namedtuple("Point",["x","y"]) Rectangle = collections.namedtuple("Rectangle",["min","max"]) def inRectangle (r,x,y): return r.min.x <= x <= r.max.x and r.min.y <= y <= r.max.y def rasterice(screen,rect,value): f,c=screen.shape for i in range(f): for j in range(c): if inRectangle(rect,j,i): screen[i][j]=value screen = np.zeros((10,10)) print (screen) '''changepixel(screen,2,3,4) print(screen) clearscreen(screen) print (screen)''' p = Point(0, 0) q = Point(2,3) r = Rectangle(p, q) print (p) print (p[0]) print (p.x) print (r) print (r[0][0]) print (r.min) rasterice(screen,r,2) print (screen)
# coding=utf-8 import math #- Crear una función que dada una altura, pinte un rombo def rombo(altura): for i in range(altura): print(" " * (altura - i) + "*" * (2 * i + 1)) for i in range(altura - 2, -1, -1): print(" " * (altura - i) + "*" * (2 * i + 1)) rombo(input("Introduzca una altura: ")) #– Crear una función que devuelva el área de un rectángulo. def area (base,altura): areaaux=base*altura print("El area del rectangulo es: ",areaaux) area(input("Introduzca una base: "), input("Introduzca una altura: ")) #– Crear una función que devuelva el perímetro de una circunferencia (utilizando math). def perimetro (radio): print("El perimetro es: ",2*math.pi*radio) perimetro(2) #– Crear una función que resuelve una ecuación de segundo grado recibiendo a, b, c. def grado(a,b,c): print("La funcion de segundo grado es: ",(-b)+ math.sqrt((b**2+(4*a*c)/2*a))) grado(1 ,1 ,1) #– Crear una función que calcule el factorial de n. #math.factorial(numero) #hacer una funcion que te devuleva una tupla con las dos soluciones de la ecuacion de segundo grado. def grado(a,b,c): t=(((-b)+ math.sqrt((b**2+(4*a*c)/2*a))),((-b)- math.sqrt((b**2+(4*a*c)/2*a)))) for i in t: print("La funcion de segundo grado es: ", i) grado(1,1,1) #lista de primos hoja 36 #lista de primos lista=range(2,100) def primos (lista): for i in lista: if i % 2 != 0: print i #lista de posicion pares def pares (lista): for i in range(0,len(lista),2): print(lista[i]) pares(list(range(10))) def perfecto(n): sum=0 for i in range(1,n): if n% i==n: sum+=i return sum==n def list2tupla(lista): l=[] for e in lista: t=(e,e**2,e**3) l.append(t) return l print (primos(lista)) print(perfecto(25)) print(list2tupla(primos()))
from datetime import datetime def get_time_at(hour: int, minute: int) -> datetime: """ Helper which generate the datetime for the current day at a given hour and given minute """ now = datetime.now() return now.replace(hour=hour, minute=minute, second=0, microsecond=0)
#Find the nth fibonacci from numpy import empty def Fib(iEnd): iCnt=3 arr=empty(iEnd+1) arr[0]=0 print(int(arr[0]),end=" ") arr[1]=1 while iCnt != iEnd+1: arr[iCnt]=arr[iCnt-1]+arr[iCnt-2] print(int(arr[iCnt]),end=" ") iCnt +=1 def main(): print("Enter the no till which you want fibonacci series") iEnd=int(input()) if iEnd < 0: print("Enter the valid number") Fib(iEnd) if __name__=="__main__": main()
def main(): name=input("Enter the file name that you want to create") fobj=open(name,"w") #create new file str=input("Enter the data that you want to write in the file") fobj.write(str) if __name__=="__main__": main()
class Base: def __init__(self): self.i=11 self.j=21 print("Inside Base constructor") #class Derived: public Base cpp #class Derived extends Base java class Derived1(Base): def __init__(self): Base.__init__(self) self.x=31 self.y=41 print("Inside Derived1 constructor") class Derived2(Derived1): def __init__(self): Derived1.__init__(self) self.a=51 self.b=61 print("Inside Derived2 constructor") def main(): dObj=Derived2() print(dObj.i) print(dObj.j) print(dObj.x) print(dObj.y) print(dObj.a) print(dObj.b) if __name__=="__main__": main()
def DisplayF(Value): print("Output of for loop") iCnt=0 for iCnt in range(0,Value): print("Jay Ganesh") def DisplayW(Value): print("Output of while loop") iCnt=0; while iCnt < Value: print("Jay Ganesh") iCnt=iCnt+1 def main(): print("Enter the no of iterations") no=int(input()) DisplayF(no) DisplayW(no) if __name__=="__main__": main()
import threading Amount=1000 def ATM(func,kulup): print("Inside ATM") func(kulup) def Deposit(kulup): kulup.acquire() print("Inside Deposit") iValue=int(input("Enter the amount to deposit")) global Amount Amount=Amount+iValue print("Deposit successful - Balance is:",Amount) kulup.release() def Withdraw(kulup): kulup.acquire() print("Inside Withdraw") iValue=int(input("Enter the amount to withdraw")) global Amount if iValue > Amount: print("There is no sufficient balance") else: Amount=Amount-iValue print("Withdraw successful - Balance is:",Amount) kulup.release() def main(): print("Inside main") kulup=threading.Lock() t1=threading.Thread(target=ATM, args=(Deposit,kulup,)) t2=threading.Thread(target=ATM, args=(Withdraw,kulup,)) t1.start() t2.start() t1.join() t2.join() print("ATM application closed") if __name__=="__main__": main()
#named function def Addition(iNo1,iNo2): return iNo1+iNo2 #lambda function Sum=lambda iNo1,iNo2 : iNo1+iNo2 def fun(name): iRet=name(10,20) print("Value form fun is:",iRet) def main(): print("Enter first number") iNo1=int(input()) print("Enter second number") iNo2=int(input()) iRet=Addition(iNo1,iNo2) print("Addition is:",iRet) iRet=Sum(iNo1,iNo2) print("Addition with lambda is:",iRet) fun(Sum) if __name__=="__main__": main()
def main(): Employee={11:{"Name":"Piyush","Age":30},21:{"Name":"Kiran","Age":25},51:{"Name":"Prshant","Age":29}} for eid,einformation in Employee.items(): print("Employee id is:",eid) for key in einformation: print(key,einformation[key]) #OR for eid,einformation in Employee.items(): print("Employee id is:",eid) for ename,eage in einformation.items(): print(ename,eage) if __name__=="__main__": main()
import pandas as pd import numpy as np def exponential_weighted_average(data, alpha=0.001): """ Function: Using exponential weighted average to perform normalization of data. The exponential weighted average is calculated recursively given: y<0> = x<0> y<t> = (1 - alpha)*y<t-1> + alpha*x<t> Arguments: data: numpy array of shape (samples, channels) alpha: float. value of alpha as in equation above Returns: normalized: numpy array of shape (samples, channels). Which is the normalized version of input data >>> import numpy as np >>> data = np.array([[1],[2],[3]]) >>> alpha = 0.1 >>> exponential_weighted_average(data, alpha, eps) array([[1. ], [1.1 ], [1.29]]) """ # Check validity of input assert_check_ewa(data, alpha) df = pd.DataFrame(data) mean = df.ewm(alpha=alpha, adjust=False).mean() mean = np.array(mean) return mean def assert_check_ewa(data, alpha): # Check validity of data # type assert type(data)==np.ndarray, 'data must be type numpy.ndarray' # shape assert len(data.shape)==2, 'data must have shape (time, ch)' # Check validity of alpha # type assert type(alpha) == float, 'alpha must be of type float' if __name__ == '__main__': import doctest doctest.testmod()
class Planet(object): def __init__(self, x, y): self.height = int(y) + 1 self.width = int(x) + 1 self.grid = self.build() self.rovers = [] def build(self): # Creating a matrix that represents the grid on mars. # Array of rows with 0 representig no occupied spaces and 1 the ones with a rover. w, h = self.width, self.height return [[0 for x in range(h)] for y in range(w)] def add_rover(self, rover): self.rovers.append(rover) def update_grid(self): for rover in self.rovers: position = rover.get_position() self.grid[position[0]][position[1]] = 1 def paint_grid(self): drawn_grid = '' for y in range(self.height ,0, -1): for x in range(self.width): if self.grid[x][y-1] == 0: drawn_grid += '| |' else: rover = self.get_rover_on_position(x,y-1) if rover != None: string = '| {} |' rover_direction = rover.get_direction() if rover_direction == 'N': char = '^' elif rover_direction == 'E': char = '>' elif rover_direction == 'S': char = 'v' else: char = '<' drawn_grid += string.format(char) drawn_grid += '\n' print drawn_grid def get_rover_on_position(self, x, y): for rover in self.rovers: position = rover.get_position() if position[0] == x and position[1] == y: return rover return None
class FizzBuzz: def Say(self, number): result = '{}'.format(number) isDivisible3 = number % 3 == 0 isDivisible5 = number % 5 == 0 if isDivisible3 and isDivisible5: result = 'FizzBuzz' elif isDivisible3: result = 'Fizz' elif isDivisible5: result = 'Buzz' return result
def do_bubble_sort(input_list): for i in range(len(input_list)-1): for j in range(len(input_list)-1): if input_list[j] > input_list[j+1]: input_list[j], input_list[j+1] = input_list[j+1], input_list[j] return input_list if __name__ == '__main__': lists = [3, 1, 5, 2, 6 ,2] result = do_bubble_sort(lists) print(result)
#层「节点」的概念 #每当你在某个输入上调用一个层时,都将创建一个新的张量(层的输出),并且为该层添加一个「节点」,将输入张量连接到输出张量。当多次调用同一个图层时,该图层将拥有多个节点索引 (0, 1, 2...)。 # #在之前版本的 Keras 中,可以通过 layer.get_output() 来获得层实例的输出张量,或者通过 layer.output_shape 来获取其输出形状。现在你依然可以这么做(除了 get_output() 已经被 output 属性替代)。但是如果一个层与多个输入连接呢? # #只要一个层只连接到一个输入,就不会有困惑,.output 会返回层的唯一输出: import keras from keras.layers import Input, LSTM, Dense,Conv2D from keras.models import Model a = Input(shape=(140, 256)) lstm = LSTM(32) encoded_a = lstm(a) assert lstm.output == encoded_a #但是如果该层有多个输入,那就会出现问题: a = Input(shape=(140, 256)) b = Input(shape=(140, 256)) lstm = LSTM(32) encoded_a = lstm(a) encoded_b = lstm(b) # #lstm.output #>> AttributeError: Layer lstm_1 has multiple inbound nodes, #hence the notion of "layer output" is ill-defined. #Use `get_output_at(node_index)` instead. #好吧,通过下面的方法可以解决: assert lstm.get_output_at(0) == encoded_a assert lstm.get_output_at(1) == encoded_b #够简单,对吧? # #input_shape 和 output_shape 这两个属性也是如此:只要该层只有一个节点,或者只要所有节点具有相同的输入/输出尺寸,那么「层输出/输入尺寸」的概念就被很好地定义,并且将由 layer.output_shape / layer.input_shape 返回。但是比如说,如果将一个 Conv2D 层先应用于尺寸为 (32,32,3) 的输入,再应用于尺寸为 (64, 64, 3) 的输入,那么这个层就会有多个输入/输出尺寸,你将不得不通过指定它们所属节点的索引来获取它们: a = Input(shape=(32, 32, 3)) b = Input(shape=(64, 64, 3)) conv = Conv2D(16, (3, 3), padding='same') conved_a = conv(a) # 到目前为止只有一个输入,以下可行: assert conv.input_shape == (None, 32, 32, 3) conved_b = conv(b) # 现在 `.input_shape` 属性不可行,但是这样可以: assert conv.get_input_shape_at(0) == (None, 32, 32, 3) assert conv.get_input_shape_at(1) == (None, 64, 64, 3) #show import matplotlib.pyplot as plt import matplotlib.image as mpimg from keras.utils import plot_model plot_model(model,to_file='example.png') lena = mpimg.imread('example.png') # 读取和代码处于同一目录下的 lena.png # 此时 lena 就已经是一个 np.array 了,可以对它进行任意处理 lena.shape #(512, 512, 3) plt.imshow(lena) # 显示图片 plt.axis('off') # 不显示坐标轴 #plt.show()
''' 题目:画椭圆。  程序分析:使用 Tkinter。 ''' from tkinter import * x = 360 y = 160 top = y - 30 bottom = y - 30 canvas = Canvas(width = 400,height = 600,bg = 'white') for i in range(20): canvas.create_oval(250 - top,250 - bottom,250 + top,250 + bottom) top -= 5 bottom += 5 canvas.pack() mainloop()
''' 题目:输出一个随机数。 程序分析:使用 random 模块。 ''' import random #生成 10 到 20 之间的随机数 print (random.uniform(10, 20)) print(random.gauss(0,1))