text
stringlengths
37
1.41M
#!/usr/bin/env python #the above just indicates to use python to intepret this file # --------------------------------------------------------------- #This mapper code will input a line of text and output <word, 1> # # --------------------------------------------------------------- import sys #a python module with system functions for this OS # ------------------------------------------------------------ # this 'for loop' will set 'line' to an input line from system # standard input file # ------------------------------------------------------------ for line in sys.stdin: #----------------------------------- #sys.stdin call 'sys' to read a line from standard input, # note that 'line' is a string object, ie variable, and it has methods that you can apply to it, # as in the next line # --------------------------------- line = line.strip() #strip is a method, ie function, associated # with string variable, it will strip # the carriage return (by default) keys = line.split() #split line at blanks (by default), # and return a list of keys for key in keys: #a for loop through the list of keys value = 1 print('{0}\t{1}'.format(key, value) ) #the {} is replaced by 0th,1st items in format list #also, note that the Hadoop default is 'tab' separates key from the value
from collections import deque def main(): d = deque() for _ in range(int(input())): num_cubes = int(input()) cubes = input().split() smol = int(cubes[0]) for cube in cubes: d.append(int(cube)) if int(cube) < smol: smol = int(cube) smol_pos = d.index(smol) ret = "Yes" last = d[0] for i in range(smol_pos): current = d.popleft() if current > last: ret = "No" break last = current last = d[-1] for i in range(len(d)-1): current = d.pop() if current > last: ret = "No" break last = current d.clear() print(ret) print(*d) if __name__ == "__main__": # execute only if run as a script main()
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import OrderedDict def main(): occurence = OrderedDict() for _ in range(int(input())): word = input() if word in occurence: occurence[word] += 1 continue occurence[word] = 1 print(len(occurence)) print(*occurence.values()) if __name__ == "__main__": # execute only if run as a script main()
# map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 # map()传入的第一个参数是func,即函数对象本身。由于结果a是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。 def func(x): return x*x l = [1,2,3,4,5,6,7] a = map(func, l) print(list(a))
''' An event is a simple synchronization object; the event represents an internal flag, and threads can wait for the flag to be set, or set or clear the flag themselves. event = threading.Event() # a client thread can wait for the flag to be set event.wait() # a server thread can set or reset it event.set() event.clear() If the flag is set, the wait method doesn’t do anything. 标志位设定了,代表绿灯,直接通行 If the flag is cleared, wait will block until it becomes set again. 标志位被清空,代表红灯,wait等待变绿灯 Any number of threads may wait for the same event. ''' import threading import time event = threading.Event() def lighter(): count = 0 event.set() while True: if count > 5 and count < 10: # 改成红灯 event.clear() # 清空标志位 print("\033[41;1m红灯亮了\033[0m") elif count > 10: event.set() # 设置标志位 count = 0 else: print("\033[42;1m绿灯亮了\033[0m") time.sleep(1) count += 1 a = 0 def car(name): while True: if event.is_set(): print("[%s] is running..." % name) time.sleep(1) else: print("[%s] sees red light, waiting..." % name) event.wait() print("\033[34;1m[%s] green light is on, start going...\033[0m" % name) light = threading.Thread(target=lighter,) light.start() car1 = threading.Thread(target=car, args=("Tesla",)) car1.start()
import queue q = queue.Queue(maxsize=3) # 先进先出 q1 = queue.LifoQueue() # 后进先出 q2 = queue.PriorityQueue() # 存储时可设置优先级 q.put("d1") q.put("d2") q.put("d3") # q.put("d4", block=False, timeout=5) #放多了就会卡住 print(q.qsize()) print(q.get()) print(q.get()) print(q.get()) # print(q.get()) 如果取空了,这里就会等待 # print(q.get(block=False)) # print(q.get_nowait()) q2.put((10, "alex")) # 存储时设置了优先级 q2.put((100, "zx")) q2.put((-1, "aaa")) print(q2.get()) print(q2.get()) print(q2.get())
""" implementing code to filter csv file based on requested columns """ import pandas as pd import os def filter_csv(return_as="json"): """ Filter down our data to something displayable based on parameters from the main page. :param return_as: json or numpy (default json) :returns: the filtered dataset """ my_path = os.path.split(os.path.realpath(__file__))[0] csv_path = os.path.join(my_path, "..", "..", "..", "data", "merged_data.csv") data = pd.read_csv(csv_path) columns = [] columns.extend("new_column_name") data = data.loc[:, columns] if return_as == "json": return data.to_json(orient="records") elif return_as == "numpy": return data else: raise ValueError("return_as must be json or numpy, not " + str(return_as)) if __name__ == "__main__": filter_csv()
import os import csv election_data_csv = os.path.join("..", "PyPoll", "election_data.csv") print ("Election Results") print ("-----------------------------------------") # This function will RETURN A LIST that contains the UNIQUE VALUES that appeared in the CANDIDATES COLUMN of the CSV def unique(candidates_list): # Initialize a list unique_list = [] x = "Khan" # traverse for all elements for x in candidates_list: # Check if NAME already exists in 'unique_list' OR not if x not in unique_list: unique_list.append(x) return unique_list voters = [] counties = [] listOfCandidates = [] with open(election_data_csv, newline="") as f: reader = csv.reader(f) next(reader) for column in reader: voters.append(column[0]) counties.append(column[1]) listOfCandidates.append(column[2]) #print ("----------------------------------------- ") print ("Election Results") print ("----------------------------------------- ") totalVotesCast = len(voters) print("There were a total of", totalVotesCast, "voters.") print ("----------------------------------------- ") candidateNames = unique(listOfCandidates) electionResults = {} for x in range(0, len(candidateNames)): nameOfCandidate = candidateNames[x] numVotesForCandidate = listOfCandidates.count(nameOfCandidate) proportionOfVoteWon = round(100*numVotesForCandidate/totalVotesCast, 2) print(nameOfCandidate, "had", numVotesForCandidate, "votes (won", proportionOfVoteWon, "% of all votes cast).") electionResults[nameOfCandidate] = numVotesForCandidate # This line will find the DICTIONARY KEY that corresponds to the LARGEST VALUE in the DICTIONARY print ("----------------------------------------- ") print(max(electionResults, key=electionResults.get), "won the POPULAR VOTE") print ("----------------------------------------- ")
import random from phrase import Phrase import sys class Game: def __init__(self): self.missed = 0 self.phrases = [Phrase('My dog ate my homework'), Phrase('I love sushi'), Phrase('Coding is hard'), Phrase('Carell Baskin killed her husband'), Phrase('No pain no gain') ] self.active_phrase = self.get_random_phrase() self.guesses = [" "] def start(self): self.welcome() while self.missed < 5 and self.active_phrase.check_complete(self.guesses) == False: lives = 5 - self.missed print("\nYou missed ", self.missed, " letters. You have ", lives, " lives remaining.") self.active_phrase.display(self.guesses) user_guess = self.get_guess() self.guesses.append(user_guess) self.active_phrase.check_letter(user_guess) if not self.active_phrase.check_letter(user_guess): self.missed += 1 self.game_over() def get_random_phrase(self): return random.choice(self.phrases) def welcome(self): print("\n####################################") print("Welcome to the phrase guessing game!") print("####################################\n") def get_guess(self): while True: try: guess = input('\nGuess a letter: ') # .isalpha returns True if all input characters are part of the alphabet if not guess.isalpha(): raise ValueError("\nMake sure you only input letters") elif len(guess) > 1: raise ValueError("\nPlease enter only one letter!") elif guess in self.guesses: raise ValueError("\nYou already tried this letter!") except ValueError as err: print(err) print("Sorry, this ain't it, chief! Try again!") else: return guess def game_over(self): if self.missed == 5: print("\nYou've had ", self.missed, " incorrect guesses.") print("\nThe correct phrase was: {}".format(self.active_phrase.phrase.capitalize())) print("\nCome back to play again!") else: print("\n{}!".format(self.active_phrase.phrase.capitalize())) print("\nYeah, you won! You guesses the phrase correclty and beat me!") sys.exit() if __name__ == "__main__": game = Game() game.start()
def first_not_repeating_character(s): hashtable = {} non_repeating = [] for char in s: if char in hashtable: hashtable[char] += 1 if char in non_repeating: non_repeating.remove(char) else: hashtable[char] = 1 non_repeating.append(char) if len(non_repeating) == 0: return '_' else: return non_repeating[0]
def main(): number = int(input("Insert a number:\t")) if(is_prime(number)): print(f"{number} is a prime number.") else: print(f"{number} isn't a prime number.") def is_prime(num): if(num < 2): return 0 #all numbers < 2 are not prime numbers count = num - 1 while(count > 1): if(num % count == 0): return 0 #is not a prime number count -= 1 return 1 #is a prime number if __name__ == "__main__": main()
import csv import re import sqlite3 import json def isfloat(value): """Check if provided argument is float. Parameters: value - value to check """ try: float(value) return True except ValueError: return False def read_data_from_file(file_path): """Read data from source csv file and return an array of rows. Parameters: file_path - path to csv file """ print "Reading csv file" records = [] with open(file_path, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',', skipinitialspace=True) # Skip headers next(reader, None) for row in reader: records.append(row) if not isfloat(row[7]): print len(records), row[7] raw_input("Press Enter to continue...") return records def save_json(object, path): """Save object to json file. Parameters: object - object to save path - name of json file """ print 'Saving to json' with open(path, 'w') as f: json.dump(object, f) def create_tables(db_name): """Create tables in sqlite database. Parameters: db_name - name of the database file """ # Create connection to DB print "Creating database" conn = sqlite3.connect(db_name) c = conn.cursor() c.execute('CREATE TABLE sex (id INTEGER PRIMARY KEY, name TEXT)') c.execute('''CREATE TABLE patient ( id INTEGER PRIMARY KEY, patient_id TEXT, birth_date TEXT, death_date TEXT, sex INTEGER, FOREIGN KEY(sex) REFERENCES sex(id))''' ) c.execute('''CREATE TABLE prescription ( id INTEGER PRIMARY KEY, date TEXT, patient INT, international_medicine_name TEXT, polish_medicine_name TEXT, dose TEXT, FOREIGN KEY(patient) REFERENCES patient(id))''') c.execute('''CREATE TABLE prescription_heart ( id INTEGER PRIMARY KEY, date TEXT, patient INT, international_medicine_name TEXT, polish_medicine_name TEXT, dose TEXT, FOREIGN KEY(patient) REFERENCES patient(id))''') conn.commit() conn.close() def normalize_date(date): """Normalize date to proper format. Parameters: date - date to normalize """ pattern = re.compile(r'(\d+)-(\d+)-(\d+)') match = re.search(pattern, date) if match: l = [d if len(d) > 1 else '0'+d for d in match.groups()] return '/'.join(l) raise Exception('Cannot convert date: %s', date) def normalizer(data, is_text=True): """Normalize general data to get rid of 'None' and 'brak danych'. Parameters: data - data to normalize is_text - flag wheter provided data is text data """ if data is None or data == 'brak danych' or len(data) == 0: return 'NULL' else: return "'%s'" % data if is_text else data def get_with_add_sex(conn, sex_name): """Get sex id from database. If sex doesn't exist in database then add it. Parameters: conn - database connection object sex_name - text name of the sex """ # Find sex c = conn.cursor() norm_sex = normalizer(sex_name) s = next(c.execute('SELECT id FROM sex WHERE name = %s' % norm_sex), None) if s is None and norm_sex != 'NULL': c.execute('INSERT INTO sex (name) VALUES (%s)' % norm_sex) #conn.commit() s = next(c.execute('SELECT id FROM sex WHERE name = %s' % norm_sex), None) return s[0] if s is not None else None def get_patient(conn, patient_id, non_existing_patients_list): """Get patient id from database. Parameters: conn - database connection object patient_id - text id of the patient obtained from input file non_existing_patients_list - list of patient_ids that were not found in database """ c = conn.cursor() norm_patient_id = normalizer(patient_id) s = next(c.execute('SELECT id FROM patient WHERE patient_id = %s' % norm_patient_id), None) if s is None: print 'No patient with id:', patient_id non_existing_patients_list.append(patient_id) return s[0] if s is not None else None def get_with_add_patient(conn, patient_id, birth_date, death_date, sex): """Get patient id from database. If patient doesn't exist in database then add him. Parameters: conn - database connection object patient_id - text id of the patient obtained from input file birth_date - patient's birth date death_date - patient's death date sex - patient's sex id """ # Find patient c = conn.cursor() norm_patient_id = normalizer(patient_id) s = next(c.execute('SELECT id FROM patient WHERE patient_id = %s' % norm_patient_id), None) if s is None and norm_patient_id != 'NULL': norm_birth = normalizer(birth_date) norm_death = normalizer(death_date) norm_sex = normalizer(sex) if sex is None else sex c.execute('INSERT INTO patient (patient_id, birth_date, death_date, sex) VALUES (%s, %s, %s, %s)' % (norm_patient_id, norm_birth, norm_death, norm_sex)) #conn.commit() s = next(c.execute('SELECT id FROM patient WHERE patient_id = %s' % norm_patient_id), None) return s[0] if s is not None else None def add_prescription(conn, table, date, patient, international_medicine_name, polish_medicine_name, dose): """Add presctiption to database. Parameters: conn - database connection object table - database table name to add presctiption to date - prescription's date patient - patient's id in database international_medicine_name - international name of the medicine polish_medicine_name - polish name of the medicine dose - dose of the medicine """ c = conn.cursor() norm_date = normalizer(normalize_date(date)) norm_patient = normalizer(patient) if patient is None else patient norm_inter_medicine = normalizer(international_medicine_name) norm_polish_medicine = normalizer(polish_medicine_name) norm_dose = normalizer(dose) c.execute('INSERT INTO %s (date, patient, international_medicine_name, polish_medicine_name, dose) VALUES (%s, %s, %s, %s, %s)' % (table, norm_date, norm_patient, norm_inter_medicine, norm_polish_medicine, norm_dose)) #conn.commit() def put_data_to_db(db_name, records, records_heart): """Put data read from csv to database. Parameters: db_name - name of database file records - data read from csv file with neuroleptic prescriptions records_heart - data read from csv file with cardio prescriptions """ # Create connection to DB conn = sqlite3.connect(db_name) c = conn.cursor() i = 0 for r in records: i += 1 if i % 1000 == 0: print "{0}/{1} iterations done".format(i, len(records)) if i % 10000 == 0: conn.commit() sex = get_with_add_sex(conn, r[2]) patient = get_with_add_patient(conn, r[1], r[3], r[4], sex) try: add_prescription(conn, 'prescription', r[0], patient, r[5], r[6], r[7]) except: print r print '' print '################################################' print 'Prescriptions done. Starting heart prescriptions' print '################################################' print '' non_existing_patients_list = [] i = 0 for r in records_heart: i += 1 if i % 1000 == 0: print "{0}/{1} iterations done".format(i, len(records_heart)) if i % 10000 == 0: conn.commit() patient = get_patient(conn, r[1], non_existing_patients_list) if patient is not None: add_prescription(conn, 'prescription_heart', r[0], patient, r[5], r[6], r[7]) save_json(non_existing_patients_list, 'non_existing_patients.json') conn.commit() conn.close() def show_db_content(db_name): """Show last 10 elements of each table in database. Parameters: db_name - name of database file """ print "Result" conn = sqlite3.connect(db_name) c = conn.cursor() for row in c.execute('SELECT * FROM sex ORDER BY id'): print row for row in c.execute('SELECT * FROM patient ORDER BY id DESC LIMIT 10'): print row for row in c.execute('SELECT * FROM prescription ORDER BY id DESC LIMIT 10'): print row for row in c.execute('SELECT * FROM prescription_heart ORDER BY id DESC LIMIT 10'): print row conn.close() if __name__ == '__main__': db_name = '../nasercowe.db' #records = read_data_from_file('neuro_sample.csv') records = read_data_from_file('neuroleptyki_cleared.csv') records_heart = read_data_from_file('nasercowe_cleared.csv') create_tables(db_name) put_data_to_db(db_name, records, records_heart) show_db_content(db_name)
def Printdetail(name): return f"My name is {name}" def add(a, b): return a+b+5 def Printname(name): return f"My name is {name}" def sum1(a, b): return a+b+5 # print(Printdetail("Abhay")) # o = add(5,5) # print(o) if __name__ == '__main__': print(Printname("Abhay")) a = sum1(5,3) print(a)
def searcher(): import time letter1 = "This is the letter for the Abhinav Namdeo" letter2 = "This is the letter for the Ashutosh Namdeo" letter3 = "This is the letter for the Abhishek Namdeo" letter4 = "This is the letter for the Manju Namdeo" time.sleep(3) while True: # text = input("Search here\n") text = (yield ) if text in letter1: print("Your letter is letter1") elif text in letter2: print("Your letter is letter2") elif text in letter3: print("Your letter is letter3") elif text in letter4: print("Your letter is letter4") else: print("There is no letter for you") search = searcher() next(search) search.send("Abhinav Namdeo") input("Press any key") search.send("Abhishek Namdeo")
food = [] for i in range(5): inp = input("Enter the Food Name\n") food.append(inp) print("Reverse by inbuilt python method") foodwithreverse = food foodwithreverse.reverse() print(foodwithreverse) print("----------------------------------------------------") print("Reverse by Slicing") foodwithslicing = food foodwithslicing[::-1] print(foodwithslicing) print("----------------------------------------------------") print("Reverse by using Swapping method") foodwithswapping = food for i in range(len(foodwithswapping)//2): foodwithswapping[i], foodwithswapping[len(foodwithswapping) -i -1] = foodwithswapping[len(foodwithswapping) -i -1], foodwithswapping[i] print(foodwithswapping)
print("Enter Your First Number") num1 = input() print("Enter Your Second Number") num2 = input() sum = int(num1) + int(num2) print("Your Total Sum Is", int(sum))
first=int(input("fill first number:")) second=int(input("fill second number:")) print(first,"+",second,"=",first+second) print(first,"-",second,"=",first-second) print(first,"*",second,"=",first*second) print(first,"/",second,"=",first/second)
import os def main(): continua = True pesos = [] vertice = [] while continua: os.system('clear') print "[*] 1 - Adicionar vertice" print "[*] 2 - Adicionar arestas com os pesos" print "[*] 3 - Rodar algoritmo de Kruskal" print "[*] 4 - Sair\n\n" op = raw_input('Qual a opcao desejada: ') if op == '1': print 'Adicionando vertice. Digite 0 para sair\n\n' ok = True while ok: v = raw_input('Vertice: ') if v == '0': break vertice.append(v) if op == '2': print vertice print 'Adicionando aresta com os pesos. Digite 0 para sair\n\n' print 'Exemplo:\nAresta: A-B\nPeso: 5\n\n' ok = True while ok: a = raw_input('Aresta: ') p = raw_input('Peso: ') print "\n" if a == '0' or p == '0': break dados = {'a': a, 'p': p} pesos.append(dados) if op == '3': print 'Rodando o algoritmo de Kruskal\n\n' pesos = sorted(pesos, key=lambda x: x['p']) for peso in pesos: print peso['a'] + ': ' + str(peso['p']) return 0 if op == '4': print 'Saindo...\n\n' return 0 return 0 if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next_node = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ multiplier1 = 1 sum1 = 0 while l1 is not None: sum1 += l1.val * multiplier1 l1 = l1.next_node multiplier1 *= 10 multiplier2 = 1 sum2 = 0 while l2 is not None: sum2 += l2.val * multiplier2 l2 = l2.next_node multiplier2 *= 10 sum_rst = sum1 + sum2 sum_lst = list(str(sum_rst)) sum_lst = sum_lst[::-1] rst_node1 = ListNode(int(sum_lst[0])) rst_node_last = rst_node1 for idx, item in enumerate(sum_lst): if idx != 0: node = ListNode(int(sum_lst[idx])) rst_node_last.next_node = node rst_node_last = node return rst_node1 if __name__ == '__main__': node1 = ListNode(2) node2 = ListNode(4) node3 = ListNode(3) node1.next_node = node2 node2.next_node = node3 node4 = ListNode(5) node5 = ListNode(6) node6 = ListNode(4) node4.next_node = node5 node5.next_node = node6 solution = Solution() rst_node = solution.addTwoNumbers(node1, node4) # while rst_node is not None: # print rst_node.val # rst_node = rst_node.next_node
import time import platform t1 = time.time() print('time t1:{}'.format(t1)) time.sleep(1) # for i in range(1, 10): # system = platform.system() # time.sleep(100) # print(system + str(i)) t2 = time.time() print('time t2:{}'.format(t2)) print('time consumed:{}'.format(t2 - t1)) t1 = time.time() print('time t1:{}'.format(t1)) time.sleep(2) t2 = time.time() print('time t2:{}'.format(t2)) print('time consumed:{}'.format(t2 - t1)) t1 = time.time() print('time t1:{}'.format(t1)) time.sleep(3) t2 = time.time() print('time t2:{}'.format(t2)) print('time consumed:{}'.format(t2 - t1))
from random import shuffle, random, randint from math import floor # constants GENERATION_COUNT = 1000 POPULATION_COUNT = 1000 SATURATION_PERCENTAGE = 0.8 MUTATION_PROBABILITY = 0.9 # Cities cities = ["Brighton", "Bristol", "Cambridge", "Glasgow", "Liverpool", "London", "Manchester", "Oxford"] distances = [ [0,172,145,607,329,72,312,120], [172,0,192,494,209,158,216,92], [145,192,0,490,237,75,205,100], [607,494,490,0,286,545,296,489], [329,209,237,286,0,421,49,208], [72,158,75,545,421,0,249,75], [312,216,205,296,49,249,0,194], [120,92,100,489,208,75,194,0] ] # Creating a path object class Path: def __init__(self, sequence): self.sequence = sequence self.distance = 0 self.fitness = 0 def __repr__(self): return "{ " + f"Path: {self.sequence}, Fitness: {self.fitness}" + " }" # initialization # Create an initial population. This population is usually randomly generated and can be any desired size, from only a few individuals to thousands. def initialization(path, populationCount): population = [path] for i in range(populationCount - 1): newPath = path.sequence[:] while pathExists(newPath, population): shuffle(newPath) population.append(Path(newPath)) return population # Returns true if the path exists and false otherwise def pathExists(path, population): for item in population: if item.sequence == path: return True return False # evaluation # Each member of the population is then evaluated and we calculate a 'fitness' for that individual. The fitness value is calculated by how well it fits with our desired requirements. These requirements could be simple, 'faster algorithms are better', or more complex, 'stronger materials are better but they shouldn't be too heavy' def calculateDistance(path): total = 0 for i in range(len(path.sequence)): if i == len(path.sequence) - 1: distance = distances[path.sequence[i]][path.sequence[0]] total += distance else: distance = distances[path.sequence[i]][path.sequence[i+1]] total += distance path.distance = total return total def calculateFitness(population): sum = 0 for path in population: distance = calculateDistance(path) sum += 1/distance path.fitness = 1/distance for path in population: path.fitness /= sum return sorted(population, key=lambda x: x.fitness, reverse=True) # Selection # We want to be constantly improving our populations overall fitness. Selection helps us to do this by discarding the bad designs and only keeping the best individuals in the population. There are a few different selection methods but the basic idea is the same, make it more likely that fitter individuals will be selected for our next generation. def select(population): randomNumber = random() third = floor(0.3 * len(population)) randomIndex = randint(0, third) if randomNumber <= 0.7: return population[randomIndex] else: return population[randint(third+1, len(population) - 1)] # Crossover # During crossover we create new individuals by combining aspects of ourselected individuals. from two or more individuals we will create an even 'fitter' offspring which will inherit the best traits from We can think of this as mimicking how sex works in nature. The hope is that by combining certain traits each of its parents. def crossOver(population): father = select(population) mother = select(population) while(mother == father): mother = select(population) startIndex = randint(0, len(mother.sequence) - 2) endIndex = randint(startIndex + 1, len(mother.sequence) - 1) childSequence = [None] * len(population[0].sequence) for i in range(startIndex, endIndex + 1): childSequence[i] = mother.sequence[i] for i in range(len(childSequence)): if childSequence[i] is None: for j in range(0, len(childSequence)): if father.sequence[j] not in childSequence: childSequence[i] = father.sequence[j] break return Path(childSequence) def crossOverTwoHalfandHalf(population): father = select(population) mother = select(population) while(mother == father): mother = select(population) mid = len(mother.sequence) // 2 childSequence = [None] * len(mother.sequence) for i in range(mid): childSequence[i] = mother.sequence[i] for i in range(mid, len(father.sequence)): for k in range(len(father.sequence)): if father.sequence[k] not in childSequence: childSequence[i] = father.sequence[k] break return Path(childSequence) # Mutation # We need to add a little bit randomness into our populations' genetics otherwise every combination of solutions we can create would be in our initial population. Mutation typically works by making very small changes at random to an individual’s genome. def mutation(path): firstIndex = randint(0, len(path.sequence) - 1) secondIndex = randint(0, len(path.sequence) - 1) while secondIndex == firstIndex: secondIndex = randint(0, len(path.sequence) - 1) probability = random() if probability < MUTATION_PROBABILITY: temp = path.sequence[firstIndex] path.sequence[firstIndex] = path.sequence[secondIndex] path.sequence[secondIndex] = temp return path def mutationTwoInsertion(path): firstIndex = randint(0, len(path.sequence) - 1) secondIndex = randint(0, len(path.sequence) - 1) while secondIndex == firstIndex: secondIndex = randint(0, len(path.sequence) - 1) probability = random() if probability < MUTATION_PROBABILITY: city = path.sequence[firstIndex] path.sequence.remove(path.sequence[firstIndex]) path.sequence.insert(secondIndex, city) return path # Repeat # Now we have our next generation we can start again from step two until we reach a termination condition def geneticAlgorithm(path, populationCount, generationCount): path = Path(path) population = initialization(path, populationCount) population = calculateFitness(population) best = population[0] print(f"Generation 1: {best.fitness}, distance: {round(best.distance, 2)}") saturation = 0 for i in range(2, generationCount + 1): print( f"Generation {i}: {best.fitness}, distance: {round(best.distance, 2)}") newGeneration = [] for _ in range(populationCount): # child = crossOver(population) child = crossOverTwoHalfandHalf(population) # newGeneration.append(mutation(child)) newGeneration.append(mutationTwoInsertion(child)) population = calculateFitness(newGeneration) if population[0].fitness > best.fitness: best = population[0] saturation = 0 else: saturation += 1 if saturation > (SATURATION_PERCENTAGE * GENERATION_COUNT): break return best # program entry point if __name__ == "__main__": path = list(range(len(cities))) best = geneticAlgorithm(path, POPULATION_COUNT, GENERATION_COUNT) pathCities = [None] * len(cities) for i in range(len(pathCities)): pathCities[i] = cities[best.sequence[i]] print(pathCities)
largest = None print('Before:', largest) for i in [3, 41, 41, 9, 74, 15]: if largest is None or i > largest: largest = i print('Largest:', largest)
smallest = None print('Before:', smallest) for i in [3, 41, 41, 9, 74, 15]: if smallest is None or i < smallest: smallest = i print('Largest:', smallest)
cel = input("Enter Celsius Temperature: ") far = float(cel)*(9/5) + 32 print("Fahrenheit Temperature:", far)
def main_menu(): print("1. List of Elements") print("2. Learn about Elements") print("3. Add Elements") print("4. Combine Elements") print("5. Exit Program") a = True while a: selection = int(input("Enter a # corresponding to what you would like to do:")) if selection == 1: list() a = False elif selection == 2: learn() a = False elif selection == 3: add() a = False elif selection == 4: combine() a = False elif selection == 5: a = False else: print("Option not yet available. Enter 1-4") main_menu() exit() def list(): print("Hydrogen, Helium, Boron, Carbon, Nitrogen, Oxygen") anykey = input("Enter anything to return to main menu") main_menu() def learn(): b = True while b: element_list = ["Hydrogen", "Helium", "Boron", "Carbon", "Nitrogen", "Oxygen"] print(element_list) element_select = int(input("Enter a number from 0-5 corresponding the element on the list:")) if element_select == 0: print("Hydrogen: Atomic number = 1 , Atomic mass = 1.0078 , Symbol = H") b = False elif element_select == 1: print("Helium: Atomic number = 2 , Atomic mass = 4.003 , Symbol = He") b = False elif element_select == 2: print("Boron: Atomic number = 5 , Atomic mass = 10.811 , Symbol = B") b = False elif element_select == 3: print("Carbon: Atomic number = 6 , Atomic mass = 12.0107 , Symbol = H") b = False elif element_select == 4: print("Nitrogen: Atomic number = 7 , Atomic mass = 14.0067 , Symbol = N") b = False elif element_select == 5: print("Oxygen: Atomic number = 8 , Atomic mass = 15.999 , Symbol = O") b = False else: print("Invalid choice. Enter 1-4:") anykey = input("Enter anything to return to main menu:") main_menu() exit() def add(): element_list = ["Hydrogen", "Helium", "Boron", "Carbon", "Nitrogen", "Oxygen"] element1 = int(input("Enter a number from 0-5 corresponding the element from the list:")) element2 = int(input("Enter another element:")) element_list[0] = 1.0078 element_list[1] = 4.003 element_list[2] = 10.811 element_list[3] = 12.0107 element_list[4] = 14.0067 element_list[5] = 15.999 print(element_list) print(format(element_list[element1] + element_list[element2], ".2f")) anykey = input("Enter anything to return to main menu:") main_menu() def combine(): element_list = ["Hydrogen", "Carbon", "Oxygen", "Copper", "Tin"] print(element_list) c = True while c: element1 = int(input("Enter a number from 0-4 corresponding to the element list:")) element2 = int(input("Enter another element number:")) if ((element1 == 0) and (element2 == 1)) or ((element1 == 1) and (element2 == 0)): print("Butane, Propane, and Methane all contain Hydrocarbon atoms!") c = False elif ((element1 == 0) and (element2 == 2)) or ((element1 == 2) and (element2 == 0)): print("Water, Carbon Monoxide, and Hydroxide are all composed of Hydrogen and Oxygen molecules!") c = False elif ((element1 == 1) and (element2 == 2)) or ((element1 == 2) and (element2 == 1)): print("Ozone, Perozide, and most common acids contain Carbon and Oxygen molecules.") c = False elif ((element1 == 0) and (element2 == 3)) or ((element1 == 3) and (element2 ==0)): print("Copper oxide, Chloride, and Sulfuric acid are all compounds that contain Hydrogen and Copper!") c = False elif ((element1 == 0) and (element2 == 4)) or ((element1 == 4) and (element2 == 0)): print("Hydrochloric acid and Sulfide are compounds that contain Hydrogen and Tin.") c = False elif ((element1 == 1) and (element2 == 3)) or ((element1 == 3) and (element2 == 1)): print("Cyanide and Copper salts are known as Organocopper compounds in organometallic chemistry!") c = False elif ((element1 == 1) and (element2 == 4)) or ((element1 == 4) and (element2 == 1)): print("Organotin compounds are highly toxic and have been used as biocides.") c = False elif ((element1 == 2) and (element2 == 3)) or ((element1 == 3) and (element2 == 2)): print("If Copper encounters itself with Oxygen then it begins to receive some physical reactions.") c = False elif ((element1 == 2) and (element2 == 4)) or ((element1 == 4) and (element2 == 2)): print("When tin reacts with oxygen it forms tin oxide which is white and insoluble in water.") c = False elif ((element1 == 3) and (element2 == 4)) or ((element1 == 4) and (element2 == 3)): print("When tin and copper are mixed together, they form a stronger metal called Bronze.") c = False else: print("Invalid Choice, choose from 0-4:") anykey = input("Enter anything to return to main menu:") main_menu() exit() # main routine main_menu()
import random min = 0 max = 12 no_of_tries = 3 t = 1 secret = random.choice(range(min, max+1)) print("can you guess my number" + "\n") while True: guess = input("try: ") try: guess = int(guess) except: print("try a number instead") break if guess == secret: print("score! you guessed my number.") print("tries:", t) break elif t == no_of_tries: print("run out of tries, did you") print("my number was", secret) break elif guess > secret: print("a little bit lower\n") t += 1 elif guess < secret: print("a tad higher\n") t += 1
# print("你好 中国!") # print("你好 世界!") # print("你好 博文!") '''a = 2 b = 3 print(a+b)''' # user = 924823387 # password = 111111 # print(user,password) # name ="小明" # age = 18 # sex = True # hight = 1.75 # weinht = 75 # a = int(input("请输入单价:")) # a = 25 # b = 10 # print("%d元,%f" % (a,b)) # name = str(input("输入你的名字:")) # student_no = int(input("输入你的学号:")) # print("我的名字叫 %s,请多多关照,输出:%06d" % (name,student_no)) # price = float(input("输入价格:")) # weight = float(input("重量:")) # money = price*weight # print("苹果单价:%.02f,重量:%.02f,money:%.02f" % (price,weight,money)) # scale = float(input("数据比例是:")) # print("%0.2f%%" % scale) # age = int(input("年龄")) # if age>=18: # print("去找女朋友!") # else: # print("回家写作业去吧!") # age =int(input("输入年龄:")) # if age> 0 and age < 120: # print("你好") # else: # print("不好") # python_score = int(input("输入python成绩")) # c_score = int(input("输入c成绩")) # if python_score > 60 or c_score >60: # print("合格") # else: # print("不合格") # fenshu = int(input("输入分数:")) # if fenshu > 0 and fenshu < 60: # print("不及格") # elif fenshu >=60 and fenshu < 70: # print("及格") # elif fenshu >=70 and fenshu < 90: # print("一般") # elif fenshu >=90 and fenshu <=100: # print("优秀") # else: # print("请重新输入") # a = int(input("输入")) # if a % 2 == 0: # if a % 3 == 0: # print("hello world") # a = 1 # b = 2 # a += b # print(a) # while 1 : # a = int(input("输入:")) # b = 1 # if a == 1 and b == 1: # print("平局") # elif a == 2 and b == 1: # print("b,赢") # elif a == 3 and b == 1: # print("a,赢") # import random # a = int(input("输入:")) # b = # if (a == 3 and b == 1) or (a == 1 and b == 2) or (a == 2 and b == 3): # print("玩家赢") # elif a == b: # print("平局") # else: # print("电脑赢") # a = int(input("请出示车票:")) # if a == 1: # # 是否有票 1 代表有票 , # print("请通过安检") # b = int(input("刀的长度:")) # # 刀有多长,大于20 不允许上车 # if b >= 20: # print("不允许上车 %d" % b) # else: # print("请买车票") # 如果没票 请买票 # a = [30,28,77,16,98] # for i in range(len(a) - 1): # for b in range(len(a)-1): # if a[b] < a[b + 1]: # a[b],a[b+1] = a[b+1],a[b] # print(a) # print(len(a)) # a = [30,28,77,16,98] # for i in range(len(a) - 1): # for b in range(i+1,len(a)): # if a[i] < a[b]: # a[i],a[b] = a[b],a[i] # print(a) # print(len(a)) # 输出1~100偶数和 # b = 0 # for i in range(1,100): # if i % 2 == 0: # b += i # print(b) #!/usr/bin/python # -*-coding:utf8-*- from time import * import smtplib #负责构建文本 from email.mime.image import MIMEImage #负责将多个对象集合起来 from email.mime.multipart import MIMEMultipart #负责构建文本 from email.mime.text import MIMEText '''2,设置邮箱域名,发件人邮箱,收件人邮箱, 发件人授权码''' # for i in range(10): #设置邮箱域名,smtp服务器,这里使用的163邮箱 mail_host = 'smtp.163.com' #发件人邮箱 mail_sender = '[email protected]' #邮箱授权码。注意这里不是邮箱密码 licence:许可证 mail_licence = 'zwxywy242698' #收件人邮箱,可以为多个收件人 mail_receivers ='[email protected]' '''3,创建一个空邮箱,这里面可以添加文本,图片,附件''' message = MIMEMultipart() '''4,设置邮件头部内容''' #设置邮件主题 message['subject'] = '这是我测试的第一封邮件' #设置发送者 message['from'] = mail_sender #设置邮件接收者 message['to'] = str(mail_receivers) '''5,添加正文文本''' #邮件正文内容 text = '你个小狗,xiaoxiaogou' #处理文本 info_text = MIMEText(text) #向MIMEMultipart对象中添加文本对象 message.attach(info_text) '''6,添加图片''' #使用open读取图片 image_data= open(r'C:\Users\biao\Desktop\图片\长发初音未来公主殿下 miku 抱着书本 4k竖屏手机壁纸_彼岸图网.jpg','rb') #处理图片 info_image = MIMEImage(image_data.read()) #关闭打开的图片文件 image_data.close() #添加图片文件到邮件信息当中去 message.attach(info_image) ''',发送邮件''' #创建smtp对象,设置发件人邮箱的域名和端口,端口地址为25 stp = smtplib.SMTP_SSL(mail_host,465) #登录邮箱 stp.login(mail_sender,mail_licence) #发送邮件,修改数据类型 stp.sendmail(mail_sender,mail_receivers,message.as_string()) print('邮件发送成功') #关闭smtp对象 stp.close() # sleep(60)
#program for formating dates from datetime import datetime import re#library for regular expression import fileinput for line in fileinput.input(): n = re.split("[\/\- ]", line.strip())#to split the input #first check if the input has three values for day, month and year if(len(n)!=3): print(n,"invalid input") #to give the proper index for year, month and day else: y = n[2] m = n[1] d = n[0] #in case the month is not a number months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] m = m.lower() #If the year is written with only two digits, the date lies between 1950 and 2049, so #65 means 1965 and 42 means 2042 def check_year(y): if y.isdigit(): if(len(y)==2) and int(y) != 0: if(int(y)>=50): y = "19"+y else: y = "20"+y else: if(len(y) == 4): y = y else: print(y,"invalid year") return -1 ##Getting the format right for the month def check_month(m): mdict = {28: 'feb', 29: 'feb',31: 'jan', 31: 'mar',30: 'apr', 31: 'may', 31: 'aug', 30: 'sep', 31: 'oct', 30:'nov',31:'dec'} if m.isdigit(): if(len(m) == 1): m = "0" + m elif(len(m)==2): m = m else: print(d,m,y,"invalid input for month") return -1 else: if m not in months: print(d,m,y,"invalid input for month") return -1 else: for i in range(len(months)): if months[i] == m: m=(i+1) m = str(m) if(len(m) == 1): m = "0" + m elif(len(m)==2): m = m return -1 #checking the day def check_day(d): if(len(d) > 2): print(d,m,y,"invalid entry for day") return -1 else: if len(d) == 1: d = "0"+d else: d = d def validdays(m,d): if int(m) == 1 or 3 or 5 or 7 or 8 or 10 or 12: print(m) if int(d) > 31: print(d) print(d,m,y, "onvalid days with more thatn 30 days") return -1; elif int(m) == 4 or 6 or 9 or 11: if int(d) > 30: print(d,m,y,"invalid month with more than 30 days") return -1 ##whether or not input is a valid date between the years 1753 and 3000,the month 1 and 12 and days 1 and 31. def valid_date(d,m,y): #print(y) if(int(y) >=1753 and int(y) <= 3000): #print(y) if(0 < int(m) < 13): if(0 < int(d) < 32): if (int(y) % 4 == 0) or (int(y) % 4 == 0) and (int(y) % 100 != 0): # Every 4 year "Leap" year occures so checking... if int(m) != 2: #if it is a leap year and is not the month of february that is where you made the changes if int(m) in [1,3,5,7,8,10,12]: if int(d) <= 31: oldformat = d+m+y oldformat = datetime.strptime(oldformat,'%d%m%Y').strftime('%d %b %Y') print(oldformat) else: print("Invalid days for the month") elif int(m) == [4,6,9,11]: if int(d) <= 30: oldformat = d+m+y oldformat = datetime.strptime(oldformat,'%d%m%Y').strftime('%d %b %Y') print(oldformat) else: print("Invalid days for the month") if int(m) == 2: # In "Leap" year February has 29 days if int(d) < 30: oldformat = d+m+y oldformat = datetime.strptime(oldformat,'%d%m%Y').strftime('%d %b %Y') print(oldformat) else: print(d,m,y, "- INVALID: Days out of range for February") return -1 elif int(m) == 2: # But if it's not "Leap" year February will have 28 days if(int(d) <29): oldformat = d+m+y oldformat = datetime.strptime(oldformat,'%d%m%Y').strftime('%d %b %Y') print(oldformat) else: print(d,m,y, "- INVALID: Days out of range for February") return -1 elif int(y)% 4 != 0 and m != 2:#if it is not a leap year and is not the month of Februar oldformat = d+m+y oldformat = datetime.strptime(oldformat,'%d%m%Y').strftime('%d %b %Y') print(oldformat) else: print(d,m,y, "- INVALID: Days out of range") return -1 else: print(d,m,y, "- INVALID: Month out of range") return -1 else: print(d,m,y," - INVALID: Year out of range.") return -1 check = check_year(y) if check == -1: continue check = check_month(m) if check == -1: continue check = check_day(d) if check == -1: continue check = validdays(d,m) if check == -1: continue check = valid_date(d,m,y) if check == -1: continue
from random import choice from string import ascii_uppercase def make_grid(height, width): return {(row, col): choice(ascii_uppercase) for row in range(height) for col in range(width)} def neighbours_of_position(row, col): return ((row - 1, col - 1), (row - 1,col), (row - 1, col + 1), (row, col - 1), (row, col + 1), (row + 1, col - 1), (row + 1, col), (row + 1, col + 2)) def get_dictionary(dictionary_file): with open(dictionary_file) as f: return [w.strip().upper() for w in f] def search(grid, dictionary): neighbours = all_grid_neighbours(grid) paths = [] def do_search(path): word = path_to_word(grid, path) if word in dictionary: paths.append(path) for next_pos in neighbours[path[-1]]: if next_pos not in path: do_search(path + [next_pos]) for position in grid: do_search([position]) words = [] for path in paths: words.append(path_to_word(grid, path)) return set (words) def all_grid_neighbours(grid): neighbours = {} for position in grid: position_neighbours = neighbours_of_position(position[0], position[1]) neighbours[position] = [p for p in position_neighbours if p in grid] return neighbours def path_to_word(grid, path): return ''.join([grid[p] for p in path]) def main(): grid = make_grid(3, 3) dictionary = get_dictionary('words.txt') words = search(grid, dictionary) for word in words: print word print "Found {0} words".format(len(words)) if __name__ == '__main__': main()
import math from sympy import Point, Circle, intersection import matplotlib.pyplot as plt def signal_strength_to_distance(signal, freq): """ Calculates the distance in meters, given the signal strength in decibels and frequency in Ghz Arguments: signal {float} -- [Signal strength in decibals] Keyword Arguments: freq {number} -- [frequency of the signal] (default: {2.4}) """ distance = 10 ** ((27.55 + abs(signal) - (20 * math.log10(freq*1000)))/20.0) distance = distance * 3.28084 #converting into foot return distance def intersection_of_three_circel(x1, y1, r1, x2, y2, r2, x3, y3, r3): # Todo handle edge cases if any c1 = Circle(Point(x1,y1), r1) c2 = Circle(Point(x2,y2), r2) c3 = Circle(Point(x3,y3), r3) ans = intersection(c1,c2,c3) if len(ans)!=0: ans = [(p.x, p.y) for p in ans] return ans else: return None
#!/usr/bin/env python """ Shape related functions. """ __author__ = "Song Huang" import numpy as np from scipy.spatial import Delaunay from scipy.spatial import ConvexHull __all__ = ['alpha_shape', 'convex_hull', 'concave_hull'] def alpha_shape(points, alpha, only_outer=True): '''Compute the alpha shape (concave hull) of a set of points. Parameters ---------- points: np.array of shape (n,2) points Coordinates of the points. alpha: float Alpha parameter to control the behaviour of the concave hull. only_outer: bool, optional If we keep only the outer border or also the inner edges. Default: True Returns ------- boundary_lst: list List of indices for boundary points. Notes ----- From a StackOverflow answer by Iddo Hanniel: https://stackoverflow.com/questions/23073170/calculate-bounding-polygon-of-alpha-shape-from-the-delaunay-triangulation ''' assert points.shape[0] > 3, "Need at least four points" def add_edge(edges, i, j): """ Add a line between the i-th and j-th points, if not in the list already """ if (i, j) in edges or (j, i) in edges: # Already added assert (j, i) in edges, "Can't go twice over same directed edge right?" if only_outer: # If both neighboring triangles are in shape, it's not a boundary edge edges.remove((j, i)) return edges.add((i, j)) tri = Delaunay(points) edges = set() # Loop over triangles: # ia, ib, ic = indices of corner points of the triangle for ia, ib, ic in tri.vertices: pa = points[ia] pb = points[ib] pc = points[ic] # Computing radius of triangle circumcircle a = np.sqrt((pa[0] - pb[0]) ** 2 + (pa[1] - pb[1]) ** 2) b = np.sqrt((pb[0] - pc[0]) ** 2 + (pb[1] - pc[1]) ** 2) c = np.sqrt((pc[0] - pa[0]) ** 2 + (pc[1] - pa[1]) ** 2) s = (a + b + c) / 2.0 area = np.sqrt(s * (s - a) * (s - b) * (s - c)) circum_r = a * b * c / (4.0 * area) if circum_r < alpha: add_edge(edges, ia, ib) add_edge(edges, ib, ic) add_edge(edges, ic, ia) return _stitch_boundaries(edges) def concave_hull(points, **kwargs): ''' Get the concave hull edges for a set of points. Parameters ---------- points: `np.array` of shape (n,2) points Coordinates of the points. Returns ------- edges: `np.array` of shape (n,2) points List of indices for boundary points. ''' edges = np.asarray(alpha_shape(points, **kwargs)[0]) return np.vstack([points[edges[:, 0], 0], points[edges[:, 1], 1]]).T def convex_hull(points): ''' Get the convex hull edges for a set of points. Parameters ---------- points: `np.array` of shape (n,2) points Coordinates of the points. Returns ------- edges: `np.array` of shape (n,2) points List of indices for boundary points. ''' hull = ConvexHull(points) return np.vstack([points[hull.vertices, 0], points[hull.vertices, 1]]).T def _stitch_boundaries(edges): """Stitches the output edge set into sequences of consecutive edges. Parameters ---------- edges: set Set of (i,j) pairs representing edges of the alpha-shape. (i,j) are the indices in the points array. Returns ------- boundary_lst: list List of indices for boundary points. Notes ----- From a StackOverflow answer by Iddo Hanniel: https://stackoverflow.com/questions/50549128/boundary-enclosing-a-given-set-of-points """ edge_set = edges.copy() boundary_lst = [] while edge_set: boundary = [] edge0 = edge_set.pop() boundary.append(edge0) last_edge = edge0 while edge_set: _, j = last_edge j_first, j_second = _find_edges_with(j, edge_set) if j_first: edge_set.remove((j, j_first[0])) edge_with_j = (j, j_first[0]) boundary.append(edge_with_j) last_edge = edge_with_j elif j_second: edge_set.remove((j_second[0], j)) edge_with_j = (j, j_second[0]) # flip edge rep boundary.append(edge_with_j) last_edge = edge_with_j if edge0[0] == last_edge[1]: break boundary_lst.append(boundary) return boundary_lst def _find_edges_with(i, edge_set): i_first = [j for (x, j) in edge_set if x==i] i_second = [j for (j, x) in edge_set if x==i] return i_first, i_second
number , asalMi = int(input("Sayı giriniz: ")), True for i in range(2,number): if number%i == 0: asalMi = False, print(str(number)+" sayısı Asal Değil, " + str(i) +" sayısına bölünüyor.") ; break if asalMi == True: print(str(number)+" Sayı Asal")
# -*- coding: utf-8 -*- sayi = int(input("Sayı giriniz: ")) if sayi > 0: print("Girdiğiniz sayı Pozitifir.") elif sayi < 0: print("Girdiğiniz sayı Negatifir.") else: print("Girdiğiniz sayı Sıfırdır.")
import sys from typing_extensions import final liste = [7,'gurkan',0,3,"6"] for x in liste: try: print("Number: " + str(x)) result = 1/int(x) print("Result: " + str(result)) except ValueError: print(str(x) + " bir sayı değil") except ZeroDivisionError: print(str(x)+ " için sıfıra bölme hatası") except: print(str(x) + " hesaplanamadı" ) print("System says: "+ str(sys.exc_info()[0])) finally: print("İşlemler Bitti")
import random win_num = random.randint(1,100) print("Enter Your Number between 1 - 100") coins = input("Enter Your Coins : ") print("You Earned A Free Coin ;)") ask = input("Enter your Guessing Number : ") guess = 1 if "." in coins or "." in ask: print("You Losed all of your Coins,who said that to you Huh?") else: if ask and coins: coins = int(coins) ask = int(ask) for i in range(0,coins): if ask == win_num: print(f"You Win!! & You Guessed it {guess} times") break elif ask < 0: print("\nPlease Don't Enter Negative Numbers") print("Don't Waste Your Coins\n") elif ask >= 100: print("\nPlease Don't Enter Numbers Above Hunderd") print("You Are Wasting You Coins\n") else: if ask < win_num: print("too Low") else: print("too High") guess +=1 ask = int(input("Enter You Guess Again : ")) print(f"\nYou have {1+coins-guess}-Coins left") else: print("From your mistake, you lose all of your Coins ") exit = input("Press any key from a to z and then Enter for Exit : ")
import re passwordChanged = False while passwordChanged == False: print('Please type a strong pasword') uInput = input() #check length if len(uInput) < 8: print ('A strong password has at least 8 chracters') else: pass #check for a capital capitalRegex = re.compile(r'[ABCDEFGHIJKLMNOPQRSTUVWXYZ]') mo = capitalRegex.findall(uInput) if mo == []: print('A strong password includes both capital and lowercase letters') else: pass #check for a digit digitRegex = re.compile(r'[0123456789]') mo = digitRegex.findall(uInput) if mo == []: print('A strong password includes at least one number') else: passwordChanged = True password = uInput print('Please type your new password to unlock the secret message.') passInput = input() unlocked = False while unlocked == False: if passInput == password: print ('SECRET MESSAGE: I love you!') unlocked = True else: print('That is not the correct password.') unlocked = False x = input()
def estCondicional01 (): #Definir variables y otros print ( "Ejemplo estructura Condicional en Python" ) montoP = 0 #Datos de entrada cantidadX = int ( input ( "Ingrese la cantidad de lapices:" )) #Proceso si cantidadX > = 1000 : montoP = cantidadX * 0.80 otra cosa : montoP = cantidadX * 0.90 #Datos de salida print ( "El monto a pagar es:" , montoP ) def estCondicional02 (): #Definir variables y otros print ( "Ejercicio 02 Est. Condicional" ) montoP = 0 #Datos de entrada cantidadX = int ( input ( "Ingrese la cantidad de personas invitadas:" )) #Proceso si cantidadX < 200 : montoP = cantidadX * 95 elif cantidadX > 200 y cantidadX <= 300 : montoP = cantidadX * 85 otra cosa : montoP = cantidadX * 75 #Datos de salida print ( "La cantidad a pagar es:" , montoP ) def votoElecciones (): print ( "Como saber si puedes votar por tu edad" ) mensaje = "" edadP = int ( input ( "ingrese la edad que tiene:" )) si edadP > = 18 : mensaje = "Usted tiene la edad necesaria para votar" otra cosa : mensaje = "Usted no cumple con la edad mínima para votar" imprimir ( mensaje ) def pagoSemanaBase40horas (): print ( "Pago semanal del trabajador" ) sueldoPagarSem = 0.0 #Datos de entrada horasTra = int ( input ( "Ingrese horas trabajadas a la semana:" )) horasPago = int ( input ( "Ingrese el pago por hora:" )) #Proceso si horasTra > 40 : sueldoPagarSem = 40 * horasPago + ( horasTra - 40 ) * 2 * horasPago otra cosa : sueldoPagarSem = horasTra * horasPago #Datos de salida print ( "El sueldo a pagar al trabajador es:" , sueldoPagarSem ) def notaPostulanteEstMultiple (): #Definir Variables notaFinal = 0 #Datos de entrada areaCarrera = input ( "Introduce el area a la que corresponde tu carrera: \ n B = Biomedicas \ n I = Ingenieria \ n S = Sociales" ) notaEP = float ( input ( "Ingrese la nota de EP:" )) notaRM = float ( input ( "Ingrese la nota de RM:" )) notaRV = float ( input ( "Ingrese la nota de RV:" )) notaAB = float ( input ( "Ingrese la nota de AB:" )) #Proceso si areaCarrera == "B" : notaFinal = ( notaEP * 0.40 ) + ( notaRM * 0.10 ) + ( notaRV * 0.20 ) + ( notaAB * 0.30 ) areaCarrera = "Biomedicas" elif areaCarrera == "I" : notaFinal = ( notaEP * 0.40 ) + ( notaRM * 0.30 ) + ( notaRV * 0.15 ) + ( notaAB * 0.15 ) areaCarrera = "Ingenierias" elif areaCarrera == "S" : notaFinal = ( notaEP * 0.40 ) + ( notaRM * 0.10 ) + ( notaRV * 0.30 ) + ( notaAB * 0.20 ) areaCarrera = "Sociales" otra cosa : print ( "La opcion que ingreso no es valida ... intente nuevamente !." ) print ( "El postulante obtuvo una nota de:" , notaFinal , " \ n Y su carrera corresponde al area de:" , areaCarrera ) # estCondicional01 () # estCondicional02 () #votoElecciones () # pagoSemanaBase40horas () notaPostulanteEstMultiple ()
#!/usr/bin/python3.4 import string def to_rot13(dat_in) : maj_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" min_chars = "abcdefghijklmnopqrstuvwxyz" dat_out = "" # Analise and replace MAJ chars z = int(0) # Select char[n] from the input for a in dat_in : y = int(0) base_placement = -1 placement = 0 # Select char[n] from maj_chars (base) while (y < 27) : if (y < 26) : base_placement = int(dat_in[z].find(maj_chars[y])) # Compare input and base char if (base_placement != -1) : # Shift char of 13 placement = y + 13 # If char is out of alphabet, subtract 26 and add char to output if placement > 26 : placement = placement - 26 dat_out = dat_out + maj_chars[placement] break # If not, add char to output else : dat_out = dat_out + maj_chars[placement] break # If the char in not reconise, add it to output else : # Select char[n] from the input w = int(0) base_placement = -1 placement = 0 # Select char[n] from min_chars (base) while (w < 27) : if (w < 26) : base_placement = int(dat_in[z].find(min_chars[w])) # Compare input and base char if (base_placement != -1) : # Shift char of 13 placement = w + 13 # If char is out of alphabet, subtract 26 and add char to output if placement > 26 : placement = placement - 26 dat_out = dat_out + min_chars[placement] break # If not, add char to output else : dat_out = dat_out + min_chars[placement] break # If the char in not reconise, add it to output else : dat_out = dat_out + dat_in[z] w = w + 1 y = y + 1 z = z + 1 return dat_out while True : dat_input = input(" -> ") if dat_input == "" : exit() dat_output = to_rot13(dat_input) print(dat_output)
''' def is_phone_number(text): #415-554 if len(text) != 12: return False # correct size check for i in range(0, 3): if not text[i].isdecimal(): return False # area code check if text[3] != '-': return False # dash check if i in range(4, 7): if not text[i].isdecimal(): return False # 1st 3 digits check if text[7] != '-': return False for i in range(8, 12): if not text[i].isdecimal(): return False return True message = 'Call me @ 832-555-6789 tomorrow or 281-555-6789' found_number = False for i in range(len(message)): chunk = message[i:i + 12] if is_phone_number(chunk): print("Phone number found: %s" % (chunk)) found_number = True if not found_number: print('Couldn\'t find any phone numbers...') ''' import re message = 'Call me at 713-555-9000 or 718-555-6000' phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') phone_num_regex2 = re.compile(r'\d{3}-\d{3}-\d{4}') # alternative mo = phone_num_regex.findall(message) print(mo)
import math class Circle: def __init__ (self, centerX = 0.0, centerY = 0.0, radius = 0.0): self.centerX = centerX self.centerY = centerY self.radius = radius def getCenter(self): return (self.centerX, self.centerY) def setCenter(self, x, y): self.centerX = x self.centerY = y def getRadius(self): return self.radius def move(self, xChange, yChange): self.centerX = self.centerX + xChange self.centerY = self.centerY + yChange def isBigger(self, otherCircle): return self.radius > otherCircle.getRadius() def __lt__(self, otherCircle): return otherCircle.isBigger(self) def area(self): return math.pi * self.radius * self.radius def circumference(self): return math.pi * 2 * self.radius def distanceBetweenCenters(self, otherCircle): return math.sqrt((otherCircle.centerY-self.centerY)**2 + (otherCircle.centerX - self.centerX)**2) def intersects(self, otherCircle): distanceBetweenCenters = self.distanceBetweenCenters(otherCircle) return(distanceBetweenCenters <= (self.radius + otherCircle.getRadius())) def __repr__(self): return '< circle with radius {} centered at ({},{}) >'.format(self.radius, self.centerX, self.centerY) def testCircle(): circle1 = Circle(0.0, 0.0, 1.0) print("Circle 1:", circle1) print("Circle1 has circumference:", circle1.circumference()) print("Circle1 has area:", circle1.area()) circle2 = Circle(0.0, 0.0, 2.0) print("Circle 2:", circle2) print("Result of circle1.intersects(circle2) is: {}".format(circle1.intersects(circle2))) circle2.move(3.0, 0.0) print("Moved circle 1 to (3,0)") print("Result of circle1.intersects(circle2) is: {}".format(circle1.intersects(circle2))) circle2.move(.001, 0.0) print("Moved circle 1 to (3.001,0)") print("Result of circle1.intersects(circle2) is: {}".format(circle1.intersects(circle2))) circle3 = Circle(1.0, 1.0, 1.0) print("Circle 3:", circle3) print("Result of circle1.intersects(circle3) is: {}".format(circle1.intersects(circle3))) circle3.move(1.0,1.0) print("Moved circle 3 by (1,1). Now:", circle3) print("Result of circle1.intersects(circle3) is: {}".format(circle1.intersects(circle3))) circle4 = Circle(1.0, 23.0, 1.5) circle5 = Circle(1.0, 23.0, 0.1) print("Sorted circles: ", sorted([circle1, circle2, circle3, circle4, circle5]))
from basicgraph import * from bfs import * # return True if there should be an edge between nodes for word1 and word2 # in the word graph. Return False otherwise # def shouldHaveEdge(word1, word2): result = False # Step 1: make this function correct if len(word1) == len(word2): indexDif = 0 for i in range(0, len(word1)): if word1[i] != word2[i]: indexDif += 1 if indexDif == 1: result = True return result # Give a file of words, return a graph with # - one node for each word # - an edge for every pair of words, w1 and w2, # where shouldHaveEdge(w1, w2) is True. # def buildWordGraph(wordsFile): wordGraph = Graph() instream = open(wordsFile,"r") for line in instream: lineStrip = line.strip() newNode = Node(lineStrip) wordGraph.addNode(newNode) # At this point, wordGraph should have a Node for each word but no edges for node in wordGraph.nodes: for node2 in wordGraph.nodes: nodeName = node.getName() node2Name = node2.getName() edge = shouldHaveEdge(nodeName, node2Name) if edge: if node not in wordGraph.adjacencyLists[node2]: wordGraph.addEdge(node, node2) return wordGraph # Assumption: (modified) breadth first search has already been executed. # # Thus, parent values have been set in all nodes reached by bfs. # Now, work backwards from endNode (end word) to build a list of words # representing a ladder between the start word and end word. # # For example, if the start word was "cat" and the end word was "dog", after bfs # we might find that "dog"'s parent was "dot" and then that "dot"'s parent was # "cot" and finally that "cot"'s parent was "cat" (which has no parent). Thus, # a ladder from "cat" to "dog" is ["cat", "cot", "dot", "dog"] # # Return [] if the endNode has no parent. If the end node has no parent, the # the breadth first search could not reach it from the start node. Thus, there # is no word ladder between the start and end words. # def extractWordLadder(endNode): ladder = [] ladder.append(endNode.getName()) upTheL = endNode.getParent() while upTheL != None: ladder = [upTheL.getName()] + ladder upTheL = upTheL.getParent() return ladder def wordLadders(wordsFile): global wordGraph # this is useful for debugging - you can "look" at wordGraph # in the Python shell to determine if it's correct # 1. read the words file and build a graph based on the words file wordGraph = buildWordGraph(wordsFile) print("Created word graph with {} nodes and {} edges".format( len(wordGraph.nodes), sum(len(adjList) for adjList in wordGraph.adjacencyLists.values())//2)) # - check that the give word or words are in the dictionary # - execute breadth first search from the start word's node # (Note: you need to slightly modify the original bfs in bfs.py # to set and update distance and parent properties of Nodes. This also # requires modification of the Node class in basicgraph.py to add # those properties.) # - if an end word was given, extract word ladder from # start to that endword # - if an end word was not given, find the node in the graph # with the largest distance value and extract the ladder between # the start node and that node. # - print appropriate information - the extracted ladder and its length # 2. user interaction loop: userInput = input("Enter start and end words OR start word OR 'q' to quit: ") words = userInput.split() while (words[0] != 'q'): # make sure word or words are in the wordsFile (and thus now in graph) startNode = wordGraph.getNode(words[0]) if (startNode is None): print("The start word is not in the dictionary. Please try again.") elif (len(words) == 2) and (wordGraph.getNode(words[1]) is None): print("The end word is not in the dictionary. Please try again.") elif (len(words) == 2) and (words[0] == words[1]): print("The start and end words must be different. Please try again.") else: # Execute bread-first search from the startNode. This # should set distance properties of all words reachable from start # word, and also set "parent" properties appropriately. bfs(wordGraph, startNode) # If only one word was given, look through all nodes in the graph # to find one with max distance property. That word is the one with # the maximal "shortest distance" from start word. if (len(words) == 1): maxDistance = -1 for node in wordGraph.nodes: dist = node.getDistance() if dist is not None and dist >= maxDistance: endNode = node maxDistance = node.getDistance() print("{} is maximally distant ({} steps) from {}:".format(endNode.getName(), maxDistance, words[0])) # If two words were given, execute extractWordLadder from node for # second word, yielding a list of words representing the shortest # path between start and end words. else: endNode = wordGraph.getNode(words[1]) if endNode.getParent() == None: print("There is no word ladder from ", startNode.getName(), " to ", endNode.getName()) else: print("Shortest ladder from {} to {} is length {}:".format(words[0], words[1], endNode.distance)) ladder = extractWordLadder(endNode) for word in ladder: print(word, end=" ") print() # Finally, ask for new start/end or start words or 'q' userInput = input("Enter start and end words OR start word OR 'q' to quit: ") words = userInput.split()
from basicgraph import * # CS1210 Spring 2020. Discussion section 8. April 15-17, 2020 # # Complete steps 1, 2.1, 2.2, and 2.3 so that # buildWordGraph(somefilename) will return a graph with words from somefilename as Nodes # and an edge between each pair of Nodes that represents two words that differ in exactly # one position. # # Test on a small file first - wordsTest.txt # You should draw the graph for wordsTest.txt on paper by hand, and then look at the result # of buildWordGraph("wordsTest.txt") to see if they match # # Test also on large file - words5.txt. # The file contains 2415 words. It should take several seconds to build this # graph (but not several minutes) # # return True if there should be an edge between nodes for word1 and word2 # in the word graph. That is, if the two words are the same length and differ # at exactly one position. Return False otherwise (including when the two words # don't differ at all!) # def shouldHaveEdge(word1, word2): result = False # Step 1: make this function correct if len(word1) == len(word2): indexDif = 0 for i in range(0, len(word1)): if word1[i] != word2[i]: indexDif += 1 if indexDif == 1: result = True # Test it carefully by calling it with various words in the Python # shell. Don't do step 2 until you are confident this fn is correct. return result # Give a file of words, return a graph with # - one node for each word # - an edge for every pair of words, w1 and w2, # where shouldHaveEdge(w1, w2) is True. # def buildWordGraph(wordsFile): # Steps 2.1, 2.2, 2.3 wordGraph = Graph() instream = open(wordsFile,"r") for line in instream: # Step 2.2 # Each line of the input file will contain a single word lineStrip = line.strip() # First use line.strip() to get the word (so the "\n" end of line # is not included. # Then, create a Node for each word and add that Node to the graph newNode = Node(lineStrip) wordGraph.addNode(newNode) # At this point, wordGraph should have a Node for each word but no edges # Step 2.3 Check every relevant pair of Nodes to see whether the graph # should have an edge between those Nodes (based on whether the function # shouldHaveEdge returns True/False on the Nodes' words) # Notes: for node in wordGraph.nodes: for node2 in wordGraph.nodes: nodeName = node.getName() node2Name = node2.getName() edge = shouldHaveEdge(nodeName, node2Name) if edge: if node not in wordGraph.adjacencyLists[node2]: wordGraph.addEdge(node, node2) # 1) DO NOT pass Nodes to shouldHaveEdge. shouldHaveEdge works on # *strings*/words, not Nodes) # 2) DO NOT try to add the same edge twice. For instance, if Node n1 has # name 'black' and Node n2 has name 'blank', # shouldHaveEdge(n1.getName(), n2.getName) and # shouldHaveEdge(n2.getName(),n2.getName() will both return True. Make # sure you don't call both wordGraph.addEdge(n1,n2) and wordGraph.addEdge(n2,n1) # because addEdge will generate an error if an edge between the given nodes already # exists # # Add code here. Recommended: use nested loops. return wordGraph
class Solution: def naive_isPerfectSquare(self, num: int) -> bool: if num == 1: return True else: digits = len(str(num)) biggest_number = int('9' * ((digits // 2) + 1)) if digits > 1 else num // 2 for i in range(biggest_number, 0, -1): if i * i == num: return True elif i * i < num: return False return False def isPerfectSquare(self, num: int) -> bool: return self.naive_isPerfectSquare(num)
import random import sys import math class DECK(): def __init__(self): self.new_deck() def new_deck(self): self.cards = [] for val in ['A','2','3','4','5','6','7','8','9','T','J','Q','K']: for suit in ['H','D','S','C']: self.cards.append(val+suit) random.shuffle(self.cards) def get_card(self): return self.cards.pop() def cards_remaining(self): return len(self.cards) class TABLE(): def __init__(self, player_algo, do_log=False): self.deck = DECK() # a deck class self.dealer_hand = [] # a list of cards self.player_hand = [] # a list of cards self.discard_pile = [] # used for discarded cards after each game self.player_algo = player_algo # function that's passed (dealer_card, player_hand, discard_pile) and returns hit or stay self.games_played = 0 self.games_won = 0 self.valid_game = True self.do_log = do_log def new_deck(self): # reset everything, usually called mid-game when cards run out, and need to ditch the whole game state self.dealer_hand = [] self.player_hand = [] self.discard_pile = [] self.deck.new_deck() #print '>>>>>\n SHUFFLING NEW DECK \n>>>>>' def setup_next_game(self): # deal new hands # move hands to discard pile and reset hand self.discard_pile += self.dealer_hand + self.player_hand self.dealer_hand = [] self.player_hand = [] # verify deck has enough cards to deal before starting if self.deck.cards_remaining() < 4: self.new_deck() # deal next game self.deal( self.dealer_hand ) self.deal( self.dealer_hand ) self.deal( self.player_hand ) self.deal( self.player_hand ) def deal(self, hand): hand.append( self.deck.get_card() ) def check_player_win(self): d = get_hand_value(self.dealer_hand) p = get_hand_value(self.player_hand) if p <= 21 and d > 21: return True if p <= 21 and p > d: return True return False def record_game(self): self.games_played += 1 if self.check_player_win(): self.games_won += 1 self.generate_machine_learning_log2() def play_game(self): # may fail to record game if cards run out self.setup_next_game() # multiple break conditions easier to read in structure below while True: # first, verify we didn't run out of cards if self.deck.cards_remaining() == 0: # ran out of cards self.new_deck() # break without calling record_game() break # second, determine if player wants more cards elif self.player_algo(self.dealer_visible_card(), self.player_hand, self.discard_pile) == 'hit': self.deal( self.player_hand ) # third, determine if dealer wants more cards elif self.dealer_algo() == 'hit': self.deal( self.dealer_hand ) # fourth, reaching this else, means both players are done else: self.record_game() break def dealer_algo(self): if get_hand_value(self.dealer_hand) < 16: return 'hit' else: return 'stay' def dealer_visible_card(self): return self.dealer_hand[0] def generate_machine_learning_log(self): # 0 : unknown (dealer hand or in deck) # 1 : dealers card # 2 : discard pile # 3 : player hand if self.check_player_win() and self.do_log: # only create reconds on win # default array to unknown : 0 card_dict = {'ACTION':1} card_order = ['ACTION'] for val in ['A','2','3','4','5','6','7','8','9','T','J','Q','K']: for suit in ['H','D','S','C']: card_dict[val+suit] = 0 card_order.append(val+suit) # insert in dealer card : 1 card_dict[self.dealer_visible_card()] = 1 # insert discard plile : 2 for c in self.discard_pile: card_dict[c] = 2 # seed starting hand card_dict[ self.player_hand[0] ] = 3 card_dict[ self.player_hand[1] ] = 3 i = 2 while i < len(self.player_hand): # record a hit : 1 write(card_dict, card_order) card_dict[ self.player_hand[i] ] = 3 i += 1 # record a stay : 0 card_dict['ACTION'] = 0 write(card_dict, card_order) def generate_machine_learning_log2(self): if self.check_player_win() and self.do_log: # only create reconds on win i = 2 while i < len(self.player_hand): # record a hit : 1 d = get_hand_value([ self.dealer_visible_card() ]) p = get_hand_value( self.player_hand[:i]) s = '{},{},{}\n'.format(d,p,1) #print s f.write(s) i += 1 # record a stay : 0 d = get_hand_value([ self.dealer_visible_card() ]) p = get_hand_value( self.player_hand[:i]) s = '{},{},{}\n'.format(d,p,0) #print s f.write(s) def print_game(self): # print player, hand_value, hand, win print 'games played :', self.games_played print 'games won :', self.games_won print 'dealer hand :', self.dealer_hand, get_hand_value(self.dealer_hand) print 'player hand :', self.player_hand, get_hand_value(self.player_hand) print 'player wins :', self.check_player_win() print 'cards left :', self.deck.cards_remaining() print '#'*30 def get_hand_value(hand): card_values = {'A':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'T':10,'J':10,'Q':10,'K':10} hand_values = [card_values[c[0]] for c in hand] total = sum(hand_values) # use ace as 11 unless bust if 1 in hand_values and total + 10 <=21: return total + 10 else: return total ###################### ## PLAYER ALGOS ###################### def sigmoid(z): return 1 / (1 + math.e**(-z)) def player_lr1(dealer_card, player_hand, discard): # logistical regression machine learning # 2k examples, inputs of hand size and dealer card # win rate = 42% (out of 100k games) theta0 = 3.883246 theta1 = 0.000017 theta2 = -0.270047 x1 = get_hand_value([dealer_card]) x2 = get_hand_value( player_hand ) predict = sigmoid(theta0 + theta1*x1 + theta2*x2) if predict > .5: return 'hit' else: return 'stay' def player_random(dealer_card, player_hand, discard): # random player # win rate = 19% (out of 100k games) return random.choice( ['hit', 'stay'] ) def player_stay(dealer_card, player_hand, discard): # never hits # return 'stay' def player_hit16_algo(dealer_card, player_hand, discard): if get_hand_value(player_hand) < 16: return 'hit' else: return 'stay' def write(d, a): s = ','.join( [str(d[k]) for k in a] ) f.write(s+'\n') f = open('bj_data.txt','a+') T = TABLE(player_stay) while T.games_played < 100000: T.play_game() #T.print_game() print '! {} Played, {} Won, {}% '.format(T.games_played, T.games_won, 100.0 * T.games_won / T.games_played)
#print(20 / 3) #print(20 % 3) #print (20 // 3) def required_boxes(a,b): answer=a//b remainder=a%b if remainder>0: return answer+1 else: return answer boxes_needed1 = required_boxes (20,25) boxes_needed2 = required_boxes (20,3) print("1.", "Boxes:", boxes_needed1) print("2.", "Boxes:", boxes_needed2)
# Group of friends from all over the country are planning a trip # together in New york. They will all arrive on the same day and # leave on the same day and they would like to share transportation # to and from the airport so as to minimize the cost for the trip. import time import random import math from datetime import datetime from datetime import timedelta # person <--> origin dataset = [('Arnold', 'BOS'), ('Genie', 'DAL'), ('Elvin', 'CAK'), ('Phoenix', 'MIA'), ('Tesla', 'ORD'), ('John', 'OMA')] # final destination. destination = 'LGA' flights = {} # parse file for flight details. file = open('schedule.txt', 'r') lines = [line for line in file] for line in lines: origin,dest,depart,arrive,price = line.strip().split(',') flights.setdefault((origin, dest), []) flights[(origin,dest)].append((depart,arrive,int(price))) # get time in minutes in a day. def getminutes(t): x = time.strptime(t,'%H:%M') return x[3]*60 + x[4] # get difference between two times in minutes. def getdifference(t1,t2): tdiff = datetime.strptime(t2,'%H:%M') - datetime.strptime(t1,'%H:%M') if tdiff.days < 0: tdiff = timedelta(days = 0, seconds = tdiff.seconds, microseconds = tdiff.microseconds) return ((tdiff.seconds)/60) # solution is in a form [1,4,3,2,7,3,6,3,2,4,5,3] i.e # Arnold has taken 2nd flight in a day for way to New york. # and took 5th flight return journey home. def printschedule(sol): for idx in range(int(len(sol)/2)): name = dataset[idx][0] origin = dataset[idx][1] out = flights[(origin,destination)][sol[idx]] ret = flights[(destination,origin)][sol[idx+1]] print ('%10s%10s %5s-%5s $%3s %5s-%5s $%3s' % (name,origin, out[0],out[1],out[2], ret[0],ret[1],ret[2])) # cost function for evaluating the cost of schedule. # parameters chosen are :- # 1) total cost of flight tickets. # 2) total time spent on flights. # 3) total wait time at airport for every person. # 4) whether to rent a car for an extra day. def schedulecost(sol): totalprice = 0 totaltime = 0 latestarrival = 0 earliestdep = 24*60 for idx in range(int(len(sol)/2)): # get inbound and outbound flights. origin = dataset[idx][1] outbound = flights[(origin,destination)][sol[idx]] returnf = flights[(destination,origin)][sol[idx+1]] # calculate total amount spent on flight tickets. totalprice += outbound[2] totalprice += returnf[2] # calculate total time spent on flights during journey. totaltime += getdifference(outbound[0], outbound[1]) totaltime += getdifference(returnf[0], returnf[1]) # get lastest arrival and earliest departure. if latestarrival < getminutes(outbound[1]): latestarrival = getminutes(outbound[1]) if earliestdep > getminutes(returnf[0]): earliestdep = getminutes(returnf[0]) # calculate total time spent waiting for flights. totalwait = 0 for idx in range(int(len(sol)/2)): origin = dataset[idx][1] outbound = flights[(origin,destination)][sol[idx]] returnf = flights[(destination,origin)][sol[idx+1]] totalwait += latestarrival - getminutes(outbound[1]) totalwait += getminutes(returnf[0]) - earliestdep # if car needs to be rented for an extra day. if latestarrival > earliestdep: totalprice += 50 return totalprice + totalwait + totaltime
# 1. Update Values in Dictionaries and Lists: x = [[5, 2, 3], [10, 8, 9]] students = [ {'first_name': 'Michael', 'last_name': 'Jordan'}, {'first_name': 'John', 'last_name': 'Rosales'} ] sports_directory = { 'basketball': ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer': ['Messi', 'Ronaldo', 'Rooney'] } z = [{'x': 10, 'y': 20}] # 1-1. Change the value 10 in x to 15. Once you're done, x should now be [ [5,2,3], [15,8,9] ]. def swapTen(): for y in range(len(x)): for z in range(len(x[y])): if x[y][z] == 10: x[y][z] = 15 return x print(swapTen()) # 1-2. Change the last_name of the first student from 'Jordan' to 'Bryant'. def swapName(): for x in range(len(students)): if students[x]['last_name'] == 'Jordan': students[x]['last_name'] = 'Bryant' return students print(swapName()) # 1-3. In the sports_directory, change 'Messi' to 'Andres'. def swapName(): for x in sports_directory.keys(): for y in range(len(sports_directory[x])): if sports_directory[x][y] == 'Messi': sports_directory[x][y] = 'Andres' return sports_directory print(swapName()) # 1-4. Change the value 20 in z to 30 def swapVal(): for x in range(len(z)): for keys in z[x].keys(): for key in keys: if z[x][key] == 20: z[x][key] = 30 return z print(swapVal()) # 2. Iterate Through a List of Dictionaries: students = [ {'first_name': 'Michael', 'last_name': 'Jordan'}, {'first_name': 'John', 'last_name': 'Rosales'}, {'first_name': 'Mark', 'last_name': 'Guillen'}, {'first_name': 'KB', 'last_name': 'Tonel'} ] def iterateDictionary(): for x in range(len(students)): for entry in students[x]: print(f"{entry} - {students[x][entry]}") iterateDictionary() def iterateDictionary(): for x in range(len(students)): item = "" cnt = 0 for key in students[x].keys(): if cnt < len(students[x])-1: item += f"{key} - {students[x][key]}, " else: item += f"{key} - {students[x][key]}" cnt += 1 print(item) iterateDictionary() # 3. Get Values From a List of Dictionaries: def iterateDictionary2(key, students): for student in students: print(student[key]) iterateDictionary2('last_name', students) # 4. Iterate Through a Dictionary with List Values: dojo = { 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'], 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon'] } def printInfo(dic): for entry in dic: print(f"{len(dic[entry])} {entry.upper()}") for x in range(len(dic[entry])): print(dic[entry][x]) printInfo(dojo)
import tempfile #temp files are looked for in environment variables: TMPDIR, TEMP, TMP #On windows, C:\TEMP, C:\TMP, \TEMP, and \TMP. print("Temp dir location--> ", tempfile.gettempdir()) # if you want to write text data into a temp file, # we need to create the tempfile using the w+t mode # instead of the default. #my_file = tempfile.TemporaryFile('w+t') my_folder = tempfile.TemporaryDirectory(prefix="UC_", suffix="_Python101") my_file = tempfile.NamedTemporaryFile('w+t') my_file = tempfile.NamedTemporaryFile(dir=my_folder.name, prefix="UC_", mode='w+t', suffix="_python101") #my_file.name = "my_temporary_file.thingy" try: #it's not a file yet, it is a temp object onthe filesystem print("The file is-->", my_file.name) my_file.write("Yo, this is what we do...") #go back to the beginning of the file and read data my_file.seek(0) data = my_file.read() print(data) finally: my_file.close() print("Closed. Poof. Gone.") my_folder.cleanup() print("Cleaned Up. Poof. Gone.")
import random as rand import pygame rows, cols = input("Enter X and Y size of board: ").split(' ') boardsize = int(rows)*int(cols) bombAmount= input("Your board has " + str(boardsize) + " cells, how many bombs do you want? ") rows, cols, bombAmount = int(rows), int(cols), int(bombAmount) celldim = 20 margin = 1 winwidth, winheight = rows*celldim, cols*celldim win = pygame.display.set_mode((winwidth, winheight)) pygame.display.set_caption("Grid Example") win.fill((255,255,255)) x, y = 1, 1 celldim = 20 margin = 1 rectWidth, rectHeight = celldim-margin, celldim-margin color = (200,200,200) grey = (200,200,200) ratio = int(winwidth/rectHeight) cellnr = 0, 0 keys = pygame.key.get_pressed() def playboard(y,x): bombs = [] for i in range(x): bombs.append([]) for j in range(y): bombs[i].append(0) for i in range(bombAmount): randx = int(rand.randint(0,x-1)) randy = int(rand.randint(0,y-1)) while True: if bombs[randx][randy] == 9: randx, randy = rand.randint(0,x-1), rand.randint(0,y-1) else: bombs[randx][randy] = 9 break print("") print("THE RANDOMIZED BOMBGRID:") print("") print(bombs) totrow = len(bombs) totcol = len(bombs[0]) for c in range(0,totcol): for r in range(0,totrow): if bombs[c][r] == 9: continue #Øverst til venstre elif c == 0 and r == 0: for y in range(0,2): for x in range(0,2): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 #Øverst til høyre elif c == 0 and r == totrow-1: for y in range(0,2): for x in range(-1,1): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 #nederst til høyre elif c == totcol-1 and r == totrow-1: for y in range(-1,1): for x in range(-1,1): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 #øverst til venstre elif c == totcol-1 and r == 0: for y in range(-1,1): for x in range(0,2): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 #venstre kant elif c == 0: for y in range(0,2): for x in range(-1,2): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 #høyre kant elif c == totcol-1: for y in range(-1,1): for x in range(-1,2): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 #øverste kant elif r == 0: for y in range(-1,2): for x in range(0,2): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 #nederste kant elif r == totrow-1: for y in range(-1,2): for x in range(-1,1): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 else: for y in range(-1,2): for x in range(-1,2): if bombs[c+y][r+x] == 9: bombs[c][r] += 1 print("") print("THE PLAYBOARD WITH COUNTED NEIGHBORS:") print("") print(bombs) return bombs curboard = playboard(cols, rows) pygame.init() pygame.font.init() for c in range(0,ratio): x=1 for r in range(0,ratio): pygame.draw.rect(win, color, (x, y, rectWidth, rectHeight)) x = (x+rectWidth+margin) y = (y+rectHeight+margin) pygame.display.update() run = True while run: pygame.time.delay(50) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == pygame.MOUSEBUTTONDOWN: mousepos = pygame.mouse.get_pos() print(mousepos) x, y = mousepos x, y = x-(x%(winheight/(cols/celldim)))+1, y-(y%(winwidth/(rows/celldim)))+1 print(x,y) pygame.draw.rect(win, grey, (x, y, rectWidth, rectHeight)) cellnr = int(x/celldim), int(y/celldim) c, r = cellnr print(c, r) num = str(curboard[r][c]) pygame.draw.rect(win, (100,100,100), (x, y, rectWidth, rectHeight)) font = pygame.font.SysFont(None, 30) text = font.render(num, True, (255,255,255)) win.blit(text,(x+4, y)) pygame.display.update() pygame.quit()
a = 5 c = a ** 3 # c: 125 b = 'Sangkeun' print(b[0:3:2]) # 'Sn' print(b[1:5]) # 'angk' print(b[:3]) # 'San' print(b + ' Kim') # 'Sangkeun Kim' d = 5.123 e = 987654321123456789123456
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import random from hmap.sockets import AbstractSocket class LocalSocket(AbstractSocket): """ Interacts with other sockets on the same thread and process. LocalSocket is not thread-safe and is intended for testing purposes: spoofing up interactions between nodes """ def __init__(self, ): super().__init__() self._sockets = [] # [(<LocalSocket>, <prob success>), ...] @staticmethod def connect(u, v, **kwargs): """ Connect two components that can use a socket Args: u: component 1 v: component 2 """ sockets = LocalSocket.get_sockets(2, **kwargs) u.use(sockets[0]) v.use(sockets[1]) @staticmethod def get_sockets(size: int, reliability: float = 1.0): """ Creates a fully connected network of local sockets Args: size: number of sockets in inter-connected-socket-network reliability: probability of success that a message sent from one socket gets to another socket, if over 1, there are potentially multiple sends Returns: (list): list of LocalSocket instances all interconnected """ sockets = [LocalSocket() for _ in range(size)] for s_i in sockets: for s_j in sockets: if s_i is not s_j: s_i.add_socket(s_j, reliability) return sockets @property def sockets(): """ Tuple list of sockets and their probability of successful sends """ return self._sockets def add_socket(self, socket: AbstractSocket, prob: float): """ Connects one local socket to another. The connection is one-way. Args: socket: socket connecting to prob: probability that messages sent to the socket will make it, if value is over 1 then there are potentially multiple sends of data """ self._sockets.append((socket, prob)) def broadcast(self, data: bytes): """ Iterates through all sockets and invokes their deliver methods with a probability corresponding to the socket """ for s, prob in self._sockets: attempts = math.ceil(prob) prob = prob/attempts for _ in range(attempts): if random.random() < prob: s.deliver(data)
# name=["n","i","t","i","n"] # rev=1 # x=name # y=[] # while rev<=len(name): # r=(name[-rev]) # y.append(r) # rev=rev+1 # print(y) # if(y==name): # print("palindrome name") # else: # print("not palindrome name") # main_str=["A","B"] # user=int(input("enter the value")) # i=0 # while i<len(main_str): # if main_str==user: # print(main_str[i],end="") # i=i+1
# def calculator(num1,num2,operation): # if operation=="addition": # return(num1+num2) # elif operation=="substration": # return (num1-num2) # elif operation=="multiple": # return(num1*num2) # elif operation=="modolus": # return(num1%num2) # elif operation=="division": # return(num1/num2) # elif operation=="flor_division": # return(num1//num2) # else: # return(not operation) # num_1=calculator(2,4,"addition") # num_2=calculator(5,2,"substration") # num_3=calculator(7,8,"multiple") # num_4=calculator(10,3,"modolus") # print(num_1) # print(num_2) # print(num_3) # print(num_4) # k=int(input("enter the num")) # j=int(input("enter the num")) # def calculator(num1,num2,operation): # if operation=="addition": # return(num1+num2) # elif operation=="substration": # return (num1-num2) # elif operation=="multiple": # return(num1*num2) # elif operation=="modolus": # return(num1%num2) # elif operation=="division": # return(num1/num2) # elif operation=="flor_division": # return(num1//num2) # else: # return(not operation) # add_result=calculator(j,k,"addition") # sub_result=calculator(j,k,"substration") # mul_result=calculator(j,k,"multiple") # divide_result=calculator(j,k,"modolus") # print(add_result) # print(sub_result) # print(mul_result) # print(divide_result) # def list_change(list1,list2): # i=0 # mul=0 # y=[] # while i<len(list1): # b=list1[i]*list2[i] # y.append(b) # i=i+1 # print(y) # list_change([5,10,50,20],[2,20,3,5]) # num=int(input("enter the num")) # num1=int(input("enter the num")) # i=num # while i<=num: # j=num1 # while i<=num1: # print(num,"*",i,"=",num) # j=j+1 # i=i+1 # i=1 # while i<=10: # print(i*2," ",i*3," ",i*4," ",i*5) # i=i+1 # print() # user1=int(input("enter the num")) # user2=int(input("enter the num")) # i=user1 # while i<=user2: # a=i # if a%4==0 or a%400==0 or a%100==0: # print(a,"this is a leap year") # else: # print(a,"not a leap year") # i=i+1 # i=1 # while i<=5: # a=1 # while a<i: # print("",end="") # a=a+1 # j=1 # while j<=(i*2)-1: # print("",end="") # j=j+1 # print() # i=i+1 # # j=1 # while j<=i: # print(j,end="") # j=j+1 # i=i-1 # i=5 # while i>=1: # print(i) # i=i+1 # i=6 # while i>1: # j=1 # while j<i: # print(j,end="") # j=j+1 # print() # i=i-1
# def sum_and_avg(k): # a=int(input("enter the num")) # b=int(input("enter the num")) # c=int(input("enter the num")) # i=0 # sum=0 # while i<k: # sum=sum+a+b+c # a=a+1 # print(sum) # i=i+1 # sum_and_avg(10) # def add_numbers(number_x,number_y): # number_sum=number_x+number_y # return number_sum # sum1=add_numbers(20,40) # print(sum1) # sum2=add_numbers(560,23) # print(sum2) # a=1234 # b=12 # sum3=add_numbers(a,b) # print(sum3) # number_a=add_numbers(20,40)/add_numbers(5,1) # print(number_a)
# def number(a): # i=1 # while i<=a: # if i%2==0: # print(i,"this is even num") # else: # print(i,"this is not even num") # i=i+1 # number(10)
heroes = {} command = input() while not command == 'End': current_command_info = command.split() current_command = current_command_info[0] hero_name = current_command_info[1] if current_command == 'Enroll': if hero_name in heroes.keys(): print(f"{hero_name} is already enrolled.") else: heroes[hero_name] = [] elif current_command == 'Learn': spell_name = current_command_info[2] if hero_name not in heroes.keys(): print(f"{hero_name} doesn't exist.") elif spell_name in heroes[hero_name]: print(f"{hero_name} has already learnt {spell_name}.") else: heroes[hero_name].append(spell_name) elif current_command == 'Unlearn': spell_name = current_command_info[2] if hero_name not in heroes.keys(): print(f"{hero_name} doesn't exist.") elif spell_name not in heroes[hero_name]: print(f"{hero_name} doesn't know {spell_name}.") else: heroes[hero_name].remove(spell_name) command = input() sorted_heroes = sorted(heroes.items(), key=lambda x: (-len(x[1]), x[0])) print('Heroes:') for hero, spells in sorted_heroes: print(f"== {hero}:", end=' ') print(', '.join(spells))
tanks = input().split(', ') commands_count = int(input()) def index_range(index, length): return 0 <= index < length for i in range(commands_count): args = input().split(', ') command = args[0] if command == 'Add': tank_name = args[1] if tank_name in tanks: print('Tank is already bought') continue tanks.append(tank_name) print('Tank successfully bought') elif command == 'Remove': tank_name = args[1] if tank_name not in tanks: print('Tank not found') continue tanks.remove(tank_name) print('Tank successfully sold') elif command == 'Remove At': index = int(args[1]) if not index_range(index, len(tanks)): print('Index out of range') continue tanks.pop(index) print('Tank successfully sold') elif command == 'Insert': index = int(args[1]) tank_name = args[2] if not index_range(index, len(tanks)): print('Index out of range') continue if tank_name in tanks: print('Tank is already bought') continue tanks.insert(index, tank_name) print('Tank successfully bought') print(', '.join(tanks))
number = int(input()) string_text = str(number) string=list(string_text) def sum_even_sum_odd(num): even_sum = 0 odd_sum = 0 for index in string: index = int(index) if index % 2 == 0: even_sum += index elif index % 2 != 0: odd_sum += index return f'Odd sum = {odd_sum}, Even sum = {even_sum}' print(sum_even_sum_odd(number))
text = input() for char in text: new_char = ord(char) + 3 print(chr(new_char), end='')
def repeat(string, n): result = '' for i in range(0, n): result += string return result text = input() count = int(input()) print(repeat(text, count))
file_name = input().split("\\")[-1] name = file_name.split('.')[0] extension = file_name.split('.')[1] print(f"File name: {name}") print(f"File extension: {extension}")
price_ratings = [int(el) for el in input().split()] point = int(input()) item = input() rating = input() left_items = price_ratings[:point] right_items = price_ratings[point + 1:] sum_left = 0 sum_right = 0 if rating == 'positive': sum_left += sum([num for num in left_items if num > 0]) sum_right += sum([num for num in right_items if num > 0]) elif rating == 'negative': sum_left += sum([num for num in left_items if num < 0]) sum_right += sum([num for num in right_items if num < 0]) else: sum_left += sum(left_items) sum_right += sum(right_items) if sum_left < sum_right: print(f"Right - {sum_right}") else: print(f'Left - {sum_left}')
from collections import Counter color_name_ph = dict() # {color: {name : ph} } d = dict() # {color_name : ph} colors = {} in_line = input() while in_line != "Once upon a time": dwarfName, dwarfHatColor, dwarfPhysics = in_line.split(" <:> ") dwarfPhysics = int(dwarfPhysics) if (dwarfHatColor, dwarfName) in d: if dwarfPhysics > d[dwarfHatColor, dwarfName][0]: d[dwarfHatColor, dwarfName] = [dwarfPhysics, dwarfHatColor] else: colors[dwarfHatColor] = colors.get(dwarfHatColor, 0) + 1 d[dwarfHatColor, dwarfName] = [dwarfPhysics, dwarfHatColor] in_line = input() d_sorted = dict(sorted(d.items(), key=lambda x: (-x[1][0], -colors[x[1][1]]))) for key, value in d_sorted.items(): name, [physic, dwarfHatColor] = key[1], value print(f"({dwarfHatColor}) {name} <-> {physic}")
data = input() count = 0 command = input().split() while not command[0] == 'Finish': if command[0] == 'Replace': current_char = command[1] new_char = command[2] data = data.replace(current_char, new_char) print(data) elif command[0] == 'Cut': start = int(command[1]) end = int(command[2]) if start >= 0 and end < len(data): new_data = data.replace(data[start:end+1], '') print(new_data) else: print('Invalid indexes!') elif command[0] == 'Make': if command[1] == 'Upper': data = data.upper() print(data) else: data = data.lower() print(data) elif command[0] == 'Check': string = command[1] if data.find(string) == -1: print(f"Message doesn't contain {string}") else: print(f"Message contains {string}") elif command[0] == 'Sum': start = int(command[1]) end = int(command[2]) if start >= 0 and end < len(data): substring = data[start:end+1] for ch in substring: count += ord(ch) print(count) else: print('Invalid indexes!') command = input().split()
shops = input().split() number_commands = int(input()) for num in range(number_commands): command = input().split() if command[0] == 'Include': shop = command[1] shops.append(shop) elif command[0] == 'Visit': shop_to_remove = command[1] shop_numbers = int(command[2]) if shop_numbers > len(shops): continue if shop_to_remove == 'first': del shops[:shop_numbers] elif shop_to_remove == 'last': del shops[-shop_numbers:] elif command[0] == 'Prefer': idx_1 = int(command[1]) idx_2 = int(command[2]) if idx_1 in range(len(shops)) and idx_2 in range(len(shops)): shops[idx_1], shops[idx_2] = shops[idx_2], shops[idx_1] elif command[0] == 'Place': shop = command[1] index = int(command[2]) if index in range(len(shops)): shops.insert(index+1, shop) print(f"Shops left:") print(' '.join(shops))
data = input() companies = {} while not data == 'End': company, employee = data.split(' -> ') if company not in companies: companies[company] = [] if employee not in companies[company]: companies[company].append(employee) data = input() companies = sorted(companies.items(), key=lambda x: (x[0], x[1])) for k, v in companies: print(k) for id in v: print(f"-- {id}")
store = {} while True: tokens = input().split('->') if tokens[0] == 'END': break else: command = tokens[0] name = tokens[1] if command == 'Add': what = tokens[2].split(',') if name not in store: store[name] = what else: store[name] += what else: if name in store: del store[name] sorted_stores = sorted(store, key=lambda c: (len(store[c]), c), reverse=True) print("Stores list:") for st in sorted_stores: print(f'{st}') for item in store[st]: print(f"<<{item}>>")
health = 100 bitcoins = 0 dungeons_rooms = input().split('|') is_won = True for i in range(len(dungeons_rooms)): room = dungeons_rooms[i] data = room.split() command = data[0] number = int(data[1]) if command == 'potion': temp = health health += number healed = number if health > 100: health = 100 healed = 100 - temp print(f'You healed for {healed} hp.') print(f'Current health: {health} hp.') elif command == 'chest': bitcoins += number print(f'You found {number} bitcoins.') else: health -= number if health > 0: print(f"You slayed {command}.") else: print(f"You died! Killed by {command}.") print(f"Best room: {i+1}") is_won = False break if is_won: print(f"You've made it!") print(f"Bitcoins: {bitcoins}") print(f"Health: {health}")
line = input() courses = {} while line != 'end': args = line.split(' : ') course_name = args[0] student_name = args[1] if course_name not in courses: courses[course_name] = [] courses[course_name].append(student_name) line = input() sorted_courses = dict(sorted(courses.items(), key=lambda x: -len(x[1]))) for k, v in sorted_courses.items(): print(f"{k}: {len(v)}") for student_name in sorted(v): print(f"-- {student_name}")
import hashlib import checkutil filename = input('Input file location: ') checkmd5 = input('Input MD5 to check (Leave blank to ignore):') checksha1 = input('Input SHA1 to check (Leave blank to ignore):') try: file = open(filename, 'rb') except FileNotFoundError as e: print('Cannot find file.') print('Program exit.') else: try: checkutil.checkfile(file, checkmd5, checksha1) print('MD5 & SHA1 verify passed!') except checkutil.MD5NotMatch: print('MD5 not matched!') except checkutil.SHA1NotMatch: print('SHA1 not matched!') except checkutil.BothNotMatch: print('Both MD5 and SHA1 are not matched!')
# A. Словарь синонимов n = int(input()) d1 = {} d2 = {} for _ in range(n): tmp = input().split() d1[tmp[0]] = tmp[1] d2[tmp[1]] = tmp[0] word = input() print(d1[word] if word in d1 else d2[word])
# D. Уравнение с корнем a = int(input()) b = int(input()) c = int(input()) if c < 0: print("NO SOLUTION") else: if a == 0: if c*c == b: print("MANY SOLUTIONS") else: print("NO SOLUTION") else: xtmp = (c*c-b) print(xtmp//a if xtmp%a == 0 else "NO SOLUTION")
# F. Очень легкая задача from math import lcm #def lcm(a, b): # return abs(a*b) // gcd(a, b) N, x, y = tuple(map(int, input().split())) res = min(x,y) # first copy xylcm = lcm(x,y) qnt_of_copies_for_xylcm_sec = xylcm//x + xylcm//y res += (N-1)//qnt_of_copies_for_xylcm_sec*xylcm rest = (N-1)%qnt_of_copies_for_xylcm_sec time_rest = 0 while rest > 0: time_rest += 1 if time_rest%x == 0: rest -= 1 if time_rest%y == 0: rest -= 1 print(res + time_rest)
marks=[1,3,5,2,8,10,1] max_marks=marks[0] for i in range(6): if(max_marks<marks[i+1]): max_marks=marks[i+1] print(max_marks)
def k_largest(arr, k): arr.sort(reverse = True) for i in range(k): print (arr[i]) # Driver program arr = [5, 1, 3, 6, 8, 2, 4, 7] # n = len(arr) k = 3 k_largest(arr, k)
count_items = 0 number_of_items = int(input("Please enter the number of items")) while number_of_items <0: number_of_items = int(input("Invalid number of items. Please enter the number of items")) prices_of_items = [] while number_of_items > count_items: price_of_item = float(input("Please enter the price of each item")) count_items = count_items + 1 prices_of_items.append(price_of_item) print("You have purchased", number_of_items, "items.") for price in (prices_of_items): print("Your item cost $" + str(price)) total = sum(prices_of_items) if total > 100: total = total * 0.9 print("Your total price for", number_of_items, "items is $" + str(total))
#Lab #5 #Due Date: 09/21/2018, 11:59PM ######################################## # # Name:Daniel Melo Cruz # Collaboration Statement: I did not ask for help # ######################################## class SodaMachine: ''' Creates instances of the class SodaMachine. Takes a string and an integer >>> m = SodaMachine('Coke', 10) >>> m.purchase() 'Product out of stock' >>> m.restock(2) 'Current soda stock: 2' >>> m.purchase() 'Please deposit $10' >>> m.deposit(7) 'Balance: $7' >>> m.purchase() 'Please deposit $3' >>> m.deposit(5) 'Balance: $12' >>> m.purchase() 'Coke dispensed, take your $2' >>> m.deposit(10) 'Balance: $10' >>> m.purchase() 'Coke dispensed' >>> m.deposit(15) 'Sorry, out of stock. Take your $15 back' ''' def __init__(self, product, price): #-- start code here --- self.product = product self.price = price self.stock = 0 self.balance = 0 #-- ends here --- def purchase(self): #-- start code here --- if self.stock == 0: return 'Product out of stock' else: if self.balance < self.price: return 'Please deposit $'+ str(self.price - self.balance) elif self.balance == self.price: self.stock -= 1 self.balance = 0 return 'Coke dispensed' elif self.balance > self.price: self.stock -= 1 old_balance = self.balance self.balance = 0 return 'Coke dispensed, take your $'+str(old_balance-self.price) #-- ends here --- def deposit(self, amount): #-- start code here --- if self.stock >= 1: self.balance += amount return 'Balance: $' + str(self.balance) else: return 'Sorry, out of stock. Take your $'+str(amount) + ' back' #-- ends here --- def restock(self, amount): #-- start code here --- self.stock += amount return 'Current soda stock: ' + str(self.stock) #-- ends here --- class Line: ''' Creates objects of the class Line, takes 2 tuples >>> line1=Line((-7,-9),(1,5.6)) >>> line1.distance 16.648 >>> line1.slope 1.825 >>> line2=Line((2,6),(2,3)) >>> line2.distance 3.0 >>> line2.slope 'Infinity' ''' def __init__(self, coord1, coord2): #-- start code here --- self.x1 = coord1[0] self.y1 = coord1[1] self.x2 = coord2[0] self.y2 = coord2[1] #-- ends here --- #PROPERTY METHODS @property def distance(self): #-- start code here --- return round(math.sqrt(pow(self.x2 - self.x1, 2) + pow(self.y2 - self.y1, 2)), 3) round( ( ((self.x2 - self.x1)**2 + (self.y2 - self.y1**2))**(1/2)) , 3) #-- ends here --- @property def slope(self): #-- start code here --- if (self.x2 - self.x1) == 0: return 'Infinity' else: return((self.y2 - self.y1) / (self.x2 - self.x1)) #-- ends here ---
## Uninformed and informed searches ## Mustafa Sadiq ################################# Imports ############################### import random as rand import numpy as np from collections import deque import heapq from math import sqrt ####################### Make maze ############################## def make_maze(dim, p): maze = np.empty([dim, dim], dtype = str) for x in range(dim): for y in range(dim): if(rand.random() <= p): maze[x][y] = 'X' else: maze[x][y] = ' ' maze[0][0] = 'S' maze[dim - 1][dim - 1] = 'G' return maze ################### Print ascii maze ############################## def print_maze(maze): print('-'*(len(maze)*4), end="") print() for x in maze: for y in x: print(f'| {y} ', end="") print("|", end="") print() print('-'*(len(maze)*4), end="") print() #################### Euclidean distance ####################################### def distance(start, end): return sqrt((start[0]-end[0])**2+(start[1]-end[1])**2) ################# Take n steps on maze with given path ################# def take_n_steps(maze, path, steps=None): if steps == None: for point in path: maze[point[0]][point[1]] = '*' elif steps == -1: for point in path: maze[point[0]][point[1]] = ' ' else: for point in path[:steps]: maze[point[0]][point[1]] = '*' ##################### Get neighbours of a given point in a maze #################### def get_neighbours(maze, current): x = current[0] y = current[1] dim = len(maze) neighbours = [] if x-1 >= 0 and maze[x-1][y] != 'X': neighbours.append((x-1, y)) if y-1 >= 0 and maze[x][y-1] != 'X': neighbours.append((x, y-1)) if y+1 <= dim - 1 and maze[x][y+1] != 'X': neighbours.append((x, y+1)) if x+1 <= dim - 1 and maze[x+1][y] != 'X': neighbours.append((x+1, y)) return neighbours def get_nonfire_neighbours(maze, current): x = current[0] y = current[1] dim = len(maze) neighbours = [] if x-1 >= 0 and maze[x-1][y] != 'X' and maze[x-1][y] != 'F': neighbours.append((x-1, y)) if y-1 >= 0 and maze[x][y-1] != 'X' and maze[x][y-1] != 'F': neighbours.append((x, y-1)) if y+1 <= dim - 1 and maze[x][y+1] != 'X' and maze[x][y+1] != 'F': neighbours.append((x, y+1)) if x+1 <= dim - 1 and maze[x+1][y] != 'X' and maze[x+1][y] != 'F': neighbours.append((x+1, y)) return neighbours ###################### DFS = Find a path given a maze, start, goal ########################### def dfs(maze, start, goal): fringe = [start] tree = dict() tree[start] = None while fringe: current = fringe.pop() if current == goal: current = goal path = [] while current != start: path.append(current) current = tree[current] path.append(start) path.reverse() return path for neighbour in get_nonfire_neighbours(maze, current): if neighbour not in tree: fringe.append(neighbour) tree[neighbour] = current return None ###################### BFS = Find a path given a maze, start, goal ########################### def bfs(maze, start, goal): fringe = deque() fringe.append(start) tree = dict() tree[start] = None while fringe: current = fringe.popleft() if current == goal: current = goal path = [] while current != start: path.append(current) current = tree[current] path.append(start) path.reverse() return path for neighbour in get_nonfire_neighbours(maze, current): if neighbour not in tree: fringe.append(neighbour) tree[neighbour] = current return None ###################### A* = Find a path given a maze, start, goal ########################### def astar(maze, start, goal): fringe = [] heapq.heappush(fringe, (0,start)) tree = dict() cost_tree = dict() tree[start] = None cost_tree[start] = 0 while fringe: current = heapq.heappop(fringe)[1] if current == goal: current = goal path = [] while current != start: path.append(current) current = tree[current] path.append(start) path.reverse() return path for neighbour in get_nonfire_neighbours(maze, current): new_cost = cost_tree[current] + 1 if neighbour not in cost_tree or new_cost < cost_tree[neighbour]: cost_tree[neighbour] = new_cost priority = new_cost + distance(goal, neighbour) heapq.heappush(fringe, (priority, neighbour)) tree[neighbour] = current return None ################################################## ## Make maze dim = 10 p = 0.2 maze = make_maze(dim,p) print("\n\nOriginal maze: ") print_maze(maze) ### DFS path = dfs(maze, (0,0), (dim-1,dim-1)) take_n_steps(maze, path) print("\n\nDepth first search: ") print_maze(maze) ## BFS take_n_steps(maze, path, -1) path = bfs(maze, (0,0), (dim-1,dim-1)) take_n_steps(maze, path) print("\n\nBreadth first search:") print_maze(maze) ## A* take_n_steps(maze, path, -1) path = astar(maze, (0,0), (dim-1,dim-1)) take_n_steps(maze, path) print("\n\nA* search:") print_maze(maze)
import datetime # här importerar jag nu tidens tid while True: # Här sätter jag en loop som loopar varje gång det är sant DT = datetime.datetime.now() pernum = input("Skriv ditt personnummer ÅÅÅÅMMDD: ") # Här så sätter jag en input så att man kan skriva det den frågar efter DTpers = DT.strptime(pernum, '%Y%m%d') if (DT.month == DTpers.month and DT.day == DTpers.day): print("Grattis på födelsedagen!") # Här är det en if för om det är det som programet har då får du detta svar else: print("Du fyller inte år idag!") # annars får du det här svaret
from experiments import utility def run_experiment(): """ Experiment II: Noam Chomsky --> https://en.wikipedia.org/wiki/Noam_Chomsky """ noam_context='Avram Noam Chomsky (born December 7, 1928) is an American linguist, philosopher, cognitive \ scientist, historian, social critic, and political activist. Sometimes called "the father of \ modern linguistics", Chomsky is also a major figure in analytic philosophy and one of the \ founders of the field of cognitive science. He holds a joint appointment as Institute \ Professor Emeritus at the Massachusetts Institute of Technology (MIT) and Laureate Professor \ at the University of Arizona, and is the author of more than 100 books on topics such as \ linguistics, war, politics, and mass media. Ideologically, he aligns with anarcho-syndicalism \ and libertarian socialism.' question_1="When was Chomsky born?" print("question #1: {} --> answer: {}".format(question_1, utility.get_answer(question_1, noam_context))) question_2="What month was Chomsky born?" print("question #2: {} --> answer: {}".format(question_2, utility.get_answer(question_2, noam_context))) question_3="Who is Noam Chomsky?" print("question #2: {} --> answer: {}".format(question_3, utility.get_answer(question_3, noam_context))) question_4="What universities is Chomsky a professor at?" print("question #3: {} --> answer: {}".format(question_4, utility.get_answer(question_4, noam_context))) question_5="How many books Chomsky has been author of?" print("question #4: {} --> answer: {}".format(question_5, utility.get_answer(question_5, noam_context))) question_6="What topics has Chomsky written books in?" print("question #5: {} --> answer: {}".format(question_6, utility.get_answer(question_6, noam_context))) question_7="What is Chomsky first name?" print("question #7: {} --> answer: {}".format(question_7, utility.get_answer(question_7, noam_context))) question_8="What is Noam Chomsky nationality?" print("question #8: {} --> answer: {}".format(question_8, utility.get_answer(question_8, noam_context)))
# Python Activity # # Fill in the code for the functions below. # The starter code for each function includes a 'return' # which is just a placeholder for your code. # # Part A. def array_2_dict(emails, contacts): counter = 0 for i in emails: contacts[list(contacts.keys())[counter]] = i counter = counter + 1 return contacts return # # Part B. def array2d_2_dict(contact_info, contacts): # if (len(contact_info) == 0): return contacts counter = 0 for i in contact_info: if (len(i) == 0): return contacts contact = {"email": i[0], "phone": i[1]} contacts[list(contacts.keys())[counter]] = contact counter = counter + 1 return contacts return # # Part C. def dict_2_array(contacts): nameArray=[] emailArray=[] phoneArray=[] if(len(list(contacts.keys())) ==0): return [[],[],[]] for i in list(contacts.keys()): nameArray.append(i) emailArray.append(contacts[i]['email']) phoneArray.append(contacts[i]['phone']) return[emailArray,phoneArray,nameArray] return
import numpy as np from scipy import stats x=int(input()) sum1 = 0 arr=list(map(int, input().split()[:x])) for i in range(x): sum1 = sum1+arr[i] print(sum1/x) print(np.median(arr)) m=stats.mode(arr) print(int(m[0]))
"""This example lets you dynamically create static walls and dynamic balls """ __docformat__ = "reStructuredText" import pygame import pymunk from pymunk import Vec2d X, Y = 0, 1 ### Physics collision types COLLTYPE_DEFAULT = 0 COLLTYPE_MOUSE = 1 COLLTYPE_BALL = 2 def flipy(y): """Small hack to convert chipmunk physics to pygame coordinates""" return -y + 600 def mouse_coll_func(arbiter, space, data): """Simple callback that increases the radius of circles touching the mouse""" s1, s2 = arbiter.shapes s2.unsafe_set_radius(s2.radius + 0.15) return False def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() running = True ### Physics stuff space = pymunk.Space() space.gravity = 0.0, -900.0 ## Balls balls = [] ### Mouse mouse_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC) mouse_shape = pymunk.Circle(mouse_body, 3, (0, 0)) mouse_shape.collision_type = COLLTYPE_MOUSE space.add(mouse_body, mouse_shape) space.add_collision_handler( COLLTYPE_MOUSE, COLLTYPE_BALL ).pre_solve = mouse_coll_func ### Static line line_point1 = None static_lines = [] run_physics = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: pygame.image.save(screen, "balls_and_lines.png") elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: p = event.pos[X], flipy(event.pos[Y]) body = pymunk.Body(10, 100) body.position = p shape = pymunk.Circle(body, 10, (0, 0)) shape.friction = 0.5 shape.collision_type = COLLTYPE_BALL space.add(body, shape) balls.append(shape) elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3: if line_point1 is None: line_point1 = Vec2d(event.pos[X], flipy(event.pos[Y])) elif event.type == pygame.MOUSEBUTTONUP and event.button == 3: if line_point1 is not None: line_point2 = Vec2d(event.pos[X], flipy(event.pos[Y])) shape = pymunk.Segment( space.static_body, line_point1, line_point2, 0.0 ) shape.friction = 0.99 space.add(shape) static_lines.append(shape) line_point1 = None elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: run_physics = not run_physics p = pygame.mouse.get_pos() mouse_pos = Vec2d(p[X], flipy(p[Y])) mouse_body.position = mouse_pos if pygame.key.get_mods() & pygame.KMOD_SHIFT and pygame.mouse.get_pressed()[0]: body = pymunk.Body(10, 10) body.position = mouse_pos shape = pymunk.Circle(body, 10, (0, 0)) shape.collision_type = COLLTYPE_BALL space.add(body, shape) balls.append(shape) ### Update physics if run_physics: dt = 1.0 / 60.0 for x in range(1): space.step(dt) ### Draw stuff screen.fill(pygame.Color("white")) # Display some text font = pygame.font.Font(None, 16) text = """LMB: Create ball LMB + Shift: Create many balls RMB: Drag to create wall, release to finish Space: Pause physics simulation""" y = 5 for line in text.splitlines(): text = font.render(line, True, pygame.Color("black")) screen.blit(text, (5, y)) y += 10 for ball in balls: r = ball.radius v = ball.body.position rot = ball.body.rotation_vector p = int(v.x), int(flipy(v.y)) p2 = p + Vec2d(rot.x, -rot.y) * r * 0.9 p2 = int(p2.x), int(p2.y) pygame.draw.circle(screen, pygame.Color("blue"), p, int(r), 2) pygame.draw.line(screen, pygame.Color("red"), p, p2) if line_point1 is not None: p1 = int(line_point1.x), int(flipy(line_point1.y)) p2 = mouse_pos.x, flipy(mouse_pos.y) pygame.draw.lines(screen, pygame.Color("black"), False, [p1, p2]) for line in static_lines: body = line.body pv1 = body.position + line.a.rotated(body.angle) pv2 = body.position + line.b.rotated(body.angle) p1 = int(pv1.x), int(flipy(pv1.y)) p2 = int(pv2.x), int(flipy(pv2.y)) pygame.draw.lines(screen, pygame.Color("lightgray"), False, [p1, p2]) ### Flip screen pygame.display.flip() clock.tick(50) pygame.display.set_caption("fps: " + str(clock.get_fps())) if __name__ == "__main__": doprof = 0 if not doprof: main() else: import cProfile import pstats prof = cProfile.run("main()", "profile.prof") stats = pstats.Stats("profile.prof") stats.strip_dirs() stats.sort_stats("cumulative", "time", "calls") stats.print_stats(30)
import pygame pygame.init() screen = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: quit() screen.fill(pygame.Color("white")) pygame.draw.circle(screen, (255, 0, 0), (-50, 300), 5) pygame.display.flip() clock.tick()
def removeElement(nums, val): if len(nums)==0: return nums j=0 i=j+1 while i<len(nums): if nums[j] == val and nums[i] == val: i+=1 elif nums[j] == val and nums[i] != val: nums[i], nums[j] = nums[j], nums[i] j+=1 i+=1 else: i+=1 j+=1 if nums[i-1]!=val: return nums[:i] else: return nums[:j] nums = [0,1,2,2,3,0,4,2] val = 2 removeElement(nums, val)
# Sorting Algorithm Naive approach : Bubble Sort #Create a randomized array of length 'length' and range 0,maxint from random import randint import logging import os logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) def create_random_array(length=10, maxint=50): try : return [randint(0, maxint) for _ in range(length)] except Exception: myLib.INFO('Random numbers are {}'.format()) def bubbleSort(array): swapped=True while swapped: swapped=False for i in range(1,len(array)): if array[i-1] > array[i]: array[i],array[i-1] = array[i-1],array[i] swapped=True return array
def pascal(i,j): if j==i or j==1: return 1 else: return pascal(i-1, j-1) + pascal(i-1,j) pascal(10,5) class Solution: def pascal(self, row, col): if row == col or col == 1: return 1 else: return self.pascal(row-1, col-1) + self.pascal(row-1, col) def getRow(self, rowIndex: int): if rowIndex <= 1: return [1]*(rowIndex+1) res = [] for idx in range(1,rowIndex+1): val = self.pascal(rowIndex+1, idx) res.append(val) res.append(1) return res s = Solution() print(s.getRow(3), end='')
from collections import deque class TreeNode: def __init__(self, val): self.val = val self.left, self.right, self.next = None, None, None # level order traversal using 'next' pointer def print_level_order(self): nextLevelRoot = self while nextLevelRoot: current = nextLevelRoot nextLevelRoot = None while current: print(str(current.val) + " ", end='') if not nextLevelRoot: if current.left: nextLevelRoot = current.left elif current.right: nextLevelRoot = current.right current = current.next print() def connectLevels(root): if not root: return None queue = deque([root]) res = [] while queue: prev = None level = [] for _ in range(len(queue)): root = queue.popleft() level.append(root.val) if prev: prev.next = root prev = root if root.left: queue.append(root.left) if root.right: queue.append(root.right) res.append(level) return res root = TreeNode(12) root.left = TreeNode(7) root.right = TreeNode(1) root.left.left = TreeNode(9) root.right.left = TreeNode(10) root.right.right = TreeNode(5) connectLevels(root) print("Level order traversal using 'next' pointer: ") root.print_level_order()
# Merge Sort from random import randint def create_random_array(length=10, maxint=50): return [randint(0, maxint) for _ in range(length)] new_array = create_random_array(length=3, maxint=50) print(new_array) # class sorting(): # def __init__(algorith_name = None, array_length=10, randomized=True): # self.algorith_name = algorith_name # self.array_length = array_length def merge(left_array, right_array): merged_array = [] i = 0 j=0 while (i < len(left_array)) and (j < len(left_array)): if left_array[i] < right_array[j]: merged_array.append(left_array[i]) i =+ 1 else: merged_array.append(right_array[j]) j += 1 while (i < len(left_array)): merged_array.append(left_array[i]) i += 1 while (j < len(right_array)): merged_array.append(right_array[j]) j += 1 return merged_array def merge_sort(array): if len(array) < 2: return array else: middle = len(array)//2 left_array = merge_sort(array[:middle]) print(left_array) right_array = merge_sort(array[middle:]) print(right_array) return merge(left_array, right_array) print(merge_sort(new_array))
# todo : This is for Help in tabulate table from tabulate import tabulate head= ["Row1","Row2","Row3"] # assign data mydata = [{'a', 'b', 'c'},{12, 34, 56},{'Geeks', 'for', 'geeks!'}] # display table print(tabulate(mydata,headers=head,tablefmt="psql")) exit() # todo : This is our Project Tabulate part from tabulate import tabulate import mysql.connector as mysqlt mydb = mysqlt.connect( host="localhost", user="root", password="ujjwal2003", database="hotel_management" ) cursor = mydb.cursor() result_data = [] print("\nTO CHECK CUSTOMER DATA FROM DATABASE SERVER\n") head=["S NO.", "NAME", "AGE", " GENDER", "AADHAAR", "ADDRESS", "PHONE NO.", "NO.OF ROOMS", "PRICE", "ROOM CATEGORY", "ROOM NUMBER"] # TO PRINT ALL RECORDS FROM THE TABLE [DATABASE] call_all_records = "SELECT * FROM booking_info" cursor.execute(call_all_records) result = cursor.fetchall() for rec in result: # print(rec) result_data.append(rec) mydata = result_data print(tabulate(mydata,headers=head,tablefmt="psql")) # print(tabulate(mydata, headers=head, tablefmt="grid")) # todo : FOr more information Visit to - https://pypi.org/project/tabulate/
#Question 1 print("Python 3 uses parenthesis around print statements. Python 2 does not.") #Question 2 x = [0, 1, 2, 3, 4, 5, 6] print(x[2]) #Question 3 y = x[::-1] print(y) #Question 4 z = x[1::2] print(z) #Question 5 #Original Code #x = 99 #if(x > 0) is True #print('x is positive') x = 99 if(x > 0) is True: print('x is positive') # Needed colon after if statement and # body needed correct indentation
# By: Malane Lieng and Gregorio Lopez # Part 1 # Question 1 print("Question 1") print("Python 3 uses parenthesis to print out text while Python 2 does not use parenthesis to print text.") # Question 2 print("Question 2") x = [0, 1, 2, 3, 4, 5, 6] print(x[2]) # Question 3 print("Question 3") x.reverse() y = x print(y) # Question 4 print("Question 4") x.reverse() z = x[1:6:2] print(z) # Question 5 x = 99 if (x < 0) is True: print('x is positive') # Part 2 # Question 1 print("Part 2 Question 1") nterms = int(input("How many terms of the Fibonacci sequence would you like displayed?")) n1, n2 = 0, 1 count = 0 if nterms <= 0: print("Fibonacci sequence up to ", nterms, ":") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1 # Question 2 print("Part 2 Question 2") x = [2.0, 3.0, 5.0, 7.0, 9.0] ylist = [] i = x[1] while i <= x[4]: y = (((3.0 * i) ** 2 / ((99 * i) - (i ** 3))) - (1 / i)) ylist.append(y) i += 1 i = 0 print(ylist) # Question 3 print("Part 2 Question 3") a = float(input("Enter a value for a")) b = float(input("Enter a value for b")) c = float(input("Enter a value for c")) x0 = ((b * -1) + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a) x1 = ((b * -1) - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a) print("x0 is") print(x0) print("x1 is") print(x1) # Question 4 print("Part 2 Question 4") while i ** 2 < 2000: i = i + 1 print(i - 1) # Question 5 print("Part 2 Question 5") def volume(r): v = (4 / 3) * 3.14 * r ** 3 return v def surface_area(r): s = 4 * 3.14 * r ** 2 return s def density(r, m=0.35): p = m / volume(r) return p print("Volume is") print(volume(0.69)) print("Surface Area is") print(surface_area(0.4)) print("Density is") print(density(0.3)) print(density(2.0, 0.25))
"""Module which imports mathematical functions""" import math class CreateSphere: """Class which creates a sphere based on object's composed elements""" def calculate_volume(self): """Calculates the volume with the radius given""" return (4 / 3) * math.pi * self.radius ** 3 def calculate_surface_area(self): """Calculates the surface area with the radius given""" return 4 * math.pi * (self.radius ** 2) def calculate_density(self): """Calculates the density with the mass given and the volume function""" return self.mass / self.calculate_volume() def __init__(self, radius, mass): self.radius = radius self.mass = mass self.volume = self.calculate_volume() self.surface_area = self.calculate_surface_area() self.density = self.calculate_density()
#Homework 2 #Author: Donald Jalving #EGR 400 Full Stack Development in Python #Question 2 (Iterating Through Lists) x = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9 ,10, 11], [12, 13, 14, 15]]; for i in range(len(x)): print(*x[i], sep = ' & ')
def add(num1:int, num2:int)->int: return num1+num2 if __name__ == "__main__": assert add(1, 2) == 3 assert add(-1, 1) == 1
from turtle import * from paddle import Paddle from barrier import Barrier from ball import Ball import time screen = Screen() screen.bgcolor("black") screen.setup(width=600, height=600) screen.title("Break-out Game") paddle = Paddle() barrier = Barrier() ball = Ball() screen.listen() screen.onkey(fun=paddle.go_right, key="Right") screen.onkey(fun=paddle.go_left, key="Left") screen.tracer(0) run = True for _ in range(5): barrier.create_barrier_wall() barrier.come_down() screen.update() rep = 0 while run: rep += 1 if rep % 500 == 0: barrier.create_barrier_wall() barrier.come_down() screen.update() time.sleep(ball.move_speed) ball.move() # collision with side walls and going under the screen if ball.xcor() > 290 or ball.xcor() < -290: ball.bounce_x() elif ball.ycor() > 310: ball.bounce_y() elif ball.ycor() < - 290: ball.reset_position() # collision with paddle if ball.ycor() < -240 and ball.distance(paddle) < 50: ball.bounce_y() # collision with barriers for x in [y for y in barrier.TURTLES if y.isvisible()]: if ball.ycor() > x.ycor() - 20 and ball.distance(x) < 40: x.ht() ball.move_speed *= 0.99 ball.bounce_y() # There is a little problem with the barrier collisions I cannot seem # to find the right numbers for the game to be seem realistic. if len([y for y in barrier.TURTLES if y.isvisible()]) == 6: print("You won!") break elif [y for y in barrier.TURTLES if y.isvisible()][0].ycor() < -280: print("You lost!") break screen.update() screen.exitonclick()
''' Even number between 1 and 100''' i=1 while i <= 100: if i%2 == 0: print i i=i+1 # Generate Fibonacci series upto 10 a,b = 0,1 print a,b for i in range(0,15): c = a+b a,b=b,c print c
class Employee: """Class to represent an employee """ def __init__( self , first , last ): """Employee Constructor takes first and last name """ self.firstName = first self.lastName = last def __str__( self ): return "{} {}".format( self.firstName , self.lastName ) class HourlyWorker( Employee ): """ Constructor for HourlyWorker , takes first and last name , inital number of hours and inital wage""" def __init__( self , first , last , initHrs , initWg ): super().__init__( first , last ) self.hours = float( initHrs ) self.wage = float( initWg ) def getPay( self ): return self.hours * self.wage def __str__( self ): """String representation of HourlyWorker """ print("HourlyWorker.__str__ is executing") return "{} is an hourly worker with pay of {}".format( super().__str__() , self.getPay() ) #main Program hourly = HourlyWorker( "Bob" , "Smith" , 40.0 , 10.00 ) # invoke __str__ method several ways print("Calling __str__ several ways...") print(hourly) print(hourly.__str__()) print(HourlyWorker.__str__( hourly ))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 12 20:54:01 2018 @author: joykumardas """ from collections import deque class Node: def __init__(self, key): self.key = key self.left = None self.right = None def add(node, root): if root is None: raise ValueError('root cannot be None.') nodes_found = deque([root]) print("{0} = deque({1})".format(nodes_found,root)) while len(nodes_found) > 0: current_node = nodes_found.popleft() print("{0}".format( current_node )) if current_node.left is None: current_node.left = node print("current_node.left = node:: {0} = {1}".format(current_node.left,node)) break if current_node.right is None: current_node.right = node print("current_node.right = node:: {0} = {1}".format(current_node.right,node)) break nodes_found.append(current_node.left) nodes_found.append(current_node.right) root = Node(8) keys = [4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15] for key in keys: add(Node(key), root)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 7 21:57:00 2018 @author: joykumardas """ class Fraction: def __init__( self, num, deno ): self.numerator , self.denominator = Fraction.reduce( num , deno ) @classmethod def reduce( cls , top , bottom ): common = cls.gcd( top , bottom ) return ( top // common , bottom // common ) @staticmethod def gcd( opor , niche ): while niche != 0: opor , niche = niche , opor % niche return opor def __str__( self ): return str( self.numerator ) + " / " + str( self.denominator ) def __add__( self , other ): new_numerator = self.numerator * other.denominator + self.denominator * other.numerator new_denominator = self.denominator * other.numerator common = Fraction.gcd( new_numerator , new_denominator ) return Fraction( new_numerator // common , new_denominator // common ) def __eq__( self , other ): new_numerator = self.numerator * other.denominator new_denominator = self.denominator * other.numerator return new_numerator == new_denominator