text
stringlengths
37
1.41M
# 导入类 from collections import OrderedDict # 创建有序空字典 glossary = OrderedDict() # 给有序空字典添加键-值对 glossary['print'] = '打印' glossary['title'] = '首字母大写' glossary['lower'] = '全部小写' glossary['upper'] = '全部大写' glossary['str'] = '字符串' glossary['key'] = '键' glossary['value'] = '值' glossary['items'] = '项目' glossary['sorted'] = '排序' glossary['set'] = '集合' # 遍历字典并打印 for vocabulary, explanation in glossary.items(): print(f"{vocabulary.title()}'s explanation is {explanation.title()}")
# 创建类 class User(): """DocString.........""" def __init__(self, first_name, last_name, location, field): """初始化一个用户的属性""" self.first_name = first_name self.last_name = last_name self.location = location self.field = field self.login_attempts = 0 def describe_user(self): """打印用户信息摘要""" print(f"First name: {self.first_name.title()}!") print(f"Last name: {self.last_name.title()}!") print(f"Location: {self.location.title()}!") print(f"Field: {self.field.title()}!") print(f"Number of logins: {self.login_attempts}!" ) def greet_user(self): """向用户发出个性化的问候""" print(f"{self.first_name}{self.last_name}, how are you? have you eaten? are you healthy now?") def increment_login_attempts(self): """将属性login_attempts的值加1""" self.login_attempts += 1 def reset_login_attempts(self): """将属性login_attempts的值重置为0""" self.login_attempts = 0 class Privileges(): """特权的简单尝试""" def __init__(self, privileges=['can add post', 'can delet post', 'can ban user']): """初始化特权属性""" self.privileges = privileges def show_privileges(self): """显示管理员的权限""" for privilege in self.privileges: print(f"Every administrator {privilege}.") class Admin(User): """管理员用户的一次简单尝试""" def __init__(self, first_name, last_name, location, field): """初始化父类属性和管理员用户的特有属性""" super().__init__(first_name, last_name, location, field) self.three_privileges = Privileges() # 创建实例 admin_0 = Admin('yang', 'yahu', 'haerbin', 'navigation') # 调用方法 admin_0.three_privileges.show_privileges()
# 创建用户名列表 users = ['admin', 'yang yahu', 'gao xiangzhou', 'eric', 'yang yuhang'] # 遍历列表并打印相应的消息 for user in users: if user == 'admin': print("Hello admin, would you like to see a status report?\n") else: print(f"Hello {user}, thank you for logging in again.")
# 创建列表 invited_persons = ['dad','mother','sister','cui ping'] # 打印邀请消息 print(f"Dear {invited_persons[0].title()}, can you have dinner with me?") print(f"\nDear {invited_persons[1].title()}, can you have dinner with me?") print(f"\nDear {invited_persons[2].title()}, can you have dinner with me?") print(f"\nDear {invited_persons[3].title()}, can you have dinner with me?") # 指出无法赴约的嘉宾 print(f"\nHowever, {invited_persons[0].title()} cannot keep the appointment.") # 将无法赴约的嘉宾的姓名替换为新邀请的嘉宾的姓名 invited_persons[0] = 'ya ping' # 再次发出邀请 print(f"\nDear {invited_persons[0].title()}, can you have dinner with me?") print(f"\nDear {invited_persons[1].title()}, can you have dinner with me?") print(f"\nDear {invited_persons[2].title()}, can you have dinner with me?") print(f"\nDear {invited_persons[3].title()}, can you have dinner with me?")
# 创建列表 favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } # 创建调查人员名单 investigators = ['jen', 'phil', 'gao xiangzhou', 'yang yuhang'] for investigator in investigators: if investigator in favorite_languages.keys(): print(f"{investigator.title()}, thank you for participating in our survey!") else: print(f"{investigator.title()}, can I invite you to participate in our survey?")
# 创建列表 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 遍历列表 for number in numbers: if number == 1: print(str(number) + "st") elif number == 2: print(str(number) + "nd") elif number == 3: print(str(number) + "rd") else: print(str(number) + "th")
#! user/bin/env python3 x=100 def sum(x): if x == 1: return 1 else: return x + sum(x-1) total=x+sum(x-1) print(total)
#! usr/bin/env python3 import sys # # Binary Search is an algorithm that splits the information using a mid point # to find the specific data requested. # # This code uses Binary search to find <number> in a list of numbers. # # To run the program # # % python3 binary_search.py <number> # # where <number> can be any positive integer between the list of numbers # # Numbered_List = [] print(Numbered_List) def quicksort(Numbered_List): if len(Numbered_List) <= 2: return Numbered_List else: pivot = Numbered_List[int((len(Numbered_List)-1)/2)] Numbered_List.remove(pivot) Less_Than = [] Greater_Than = [] for i in Numbered_List: if i <= pivot: Less_Than.append(i) elif i > pivot: Greater_Than.append(i) return quicksort(Less_Than) + [pivot] + quicksort(Greater_Than) if len(Numbered_List) <= 2: print("List is already sorted") exit(1) else: print(quicksort(Numbered_List))
class trie: def __init__(self): self.data = None self.wordend = False self.child= [None]*26 def insert(root,word): l = len(word) tmp = root for i in range(l): ind = ord(word[i]) - 97 if(root.child[ind]==None): ptr = trie() ptr.data = word[i] if(i==l-1): ptr.wordend=True root.child[ind] = ptr root = root.child[ind] return tmp def search(root,word): l = len(word) for i in range(l): ind = ord(word[i]) - 97 if(root.child[ind]==None): return False root = root.child[ind] if(i==l-1 and root.wordend==0): return False return True root = trie() name = input('enter your fav character names in lowercase : ') name = list(name.split( )) for i in name: insert(root,i) while True: name = input() print(search(root,name))
class Phone(object): def __init__(self, given): self.number = '' for i in given: if i.isnumeric(): self.number += i if len(self.number) == 11 and self.number[0] == '1': self.number = self.number[1:] if len(self.number) != 10: self.number = '0'*10 def area_code(self): return self.number[0:3] def pretty(self): return '(' + self.number[0:3] + ') ' + self.number[3:6] + '-' + self.number[6:10]
class Node(object): def __init__(self, element, previous, next): self.element = element self.previous = previous self.next = next class LinkedList(object): def __init__(self): self.front = None self.back = None self.length = 0 def push(self, element): if self.front == None: self.front = Node(element, None, None) self.back = Node(element, None, None) else: self.back.next = Node(element, self.back, None) self.back = self.back.next node = self.back self.front = None while node: self.front = Node(node.element, None, self.front) node = node.previous self.length += 1 def pop(self): popped = self.back if self.back.previous == None: self.front = None self.back = None else: self.back = self.back.previous self.back.next = None self.length -= 1 return popped.element def shift(self): shifted = self.front if self.front.next == None: self.front = None self.back = None else: self.front = self.front.next self.front.previous = None self.length -= 1 return shifted.element def unshift(self, element): if self.back == None: self.front = Node(element, None, None) self.back = Node(element, None, None) else: self.front.previous = Node(element, None, self.front) self.front = self.front.previous node = self.front self.back = None while node: self.back = Node(node.element, self.back, None) node = node.next self.length += 1
def detect_anagrams(word, candidates): anagrams = [] for candidate in candidates: letterlist = [] for i in candidate: letterlist += i.lower() for i in word: if i.lower() in letterlist: letterlist.remove(i.lower()) else: break if letterlist == [] and candidate.lower() != word.lower(): anagrams.append(candidate) return anagrams
def encode(values): encoded = [] for value in values: bits = [] for i in range(7, -1, -1): if value // 128**i > 0 or len(bits) > 0: bits.append(bin(value // 128**i)) if value // 128**i > 0: value -= 128**i * (value // 128**i) for i in range(len(bits)-1): bits[i] = eval(hex(eval(bits[i]) + 128)) if len(bits) > 0: bits[len(bits)-1] = eval(hex(eval(bits[len(bits)-1]))) else: bits = [0] encoded.extend(bits) return encoded def decode(bytes): if bytes[len(bytes)-1] >= 128: raise ValueError decoded = [] values = [] start, end = 0, 0 for i in range(len(bytes)): if bytes[i] < 128: values.append(bytes[start:end+1]) start = i+1 end = start else: end += 1 for bits in values: value = 0 for i in range(len(bits)-1): bits[i] -= 128 for i in range(len(bits)): value += bits[i] * 128**(len(bits)-i-1) decoded.append(value) return decoded
def is_isogram(word): for i in range(len(word)): for j in range(len(word)): if word[i].lower() == word[j].lower() and i != j and word[i].isalpha() and word[j].isalpha(): return False return True
def largest_palindrome(max_factor, min_factor=1): largest = 1 factors = [] for i in range(min_factor, max_factor+1): for j in range(i, max_factor+1): if i*j == int(str(i*j)[::-1]): if i*j > largest: largest = i*j factors = [{i, j}] print(factors) return (largest, factors[0]) def smallest_palindrome(max_factor, min_factor): smallest = max_factor**2 factors = [] for i in range(min_factor, max_factor+1): for j in range(i, max_factor+1): if i*j == int(str(i*j)[::-1]): if i*j < smallest: smallest = i*j factors = [{i, j}] print(factors) return (smallest, factors[0])
def nth_prime(n): if n < 1: raise ValueError primes = [] num = 2 while len(primes) < n: prime = True for i in primes: if num % i == 0: prime = False if prime: primes.append(num) num += 1 return primes[len(primes)-1]
def transpose(input): rows = input.split("\n") maxlength = 0 for i in rows: if len(i) > maxlength: maxlength = len(i) for i in range(len(rows)): rows[i] = rows[i] + " " * (maxlength - len(rows[i])) newrows = [""] * maxlength for i in rows: for j in range(maxlength): newrows[j] += i[j] return "\n".join(newrows).rstrip()
#!/usr/bin/env python #-*- coding: utf-8 -*- def sum(arr): if len(arr) == 0: return 0 return arr[0] + sum(arr[1:]) if __name__ == '__main__': arr = [] for n in range(10): arr.append(n) result = sum(arr) print(result)
''' Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: a. o produto do dobro do primeiro com metade do segundo . b. a soma do triplo do primeiro com o terceiro. c. o terceiro elevado ao cubo. ''' n1 = int(input('Digite um numero inteiro: ')) n2 = int(input('Digite um outro numero inteiro: ')) n3 = float(input('Digite um numero real: ')) print('a. O produto do dobro do primeiro com metade do segundo .') quest_a = (n1**2)+n2/2 print('Resultado de A: {}'.format(quest_a)) print('b. a soma do triplo do primeiro com o terceiro.') quest_b = n1**3+n3 print('Resultado B: {}'.format(quest_b)) print('c. o terceiro elevado ao cubo') quest_c = n3**3 print('Resultado C: {}'.format(quest_c))
''' Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. calculo: C = 5 * ((F-32) / 9 ''' f = int(input('Digite a temperatura em Fahrenheit: ')) c = 5 * ((f-32)/9) print('A temperatura em Celsius é: {:.0f}º'.format(c))
def ask(_question): _question.ask() input = raw_input().lower() question = _question.answer(input) if not question is None: ask(question) pass class Question: def __init__(self, _prompt, _answers=None, _parse_answer=None): self.prompt = _prompt self.answers = _answers self.parse_answer = _parse_answer pass def ask(self): print (self.prompt) def answer(self, _input): if not self.answers or not dict.__contains__(self.answers, _input): if not self.parse_answer: self.ask() return self.answer(raw_input().lower()) return self.parse_answer(_input) return self.answers[_input]()
from typing import List Vector = List[float] #%% def add(v: Vector, w: Vector) -> Vector: """Adds corresponding elements""" assert len(v) == len(w), 'vectors must be the same length' return [v_i + w_i for v_i, w_i in zip(v, w)] def subtract(v: Vector, w: Vector) -> Vector: """Subtracts corresponding elements""" assert len(v) == len(w), "vectors must be the same length" return [v_i - w_i for v_i, w_i in zip(v, w)] #%% add([1, 2, 3], [4, 5, 6]) #%% subtract([5, 7, 9], [4, 5, 6]) #%% def vector_sum(vectors: List[Vector]) -> Vector: """Sums all corresponding elements""" assert vectors, 'no vectors provided' num_elements = len(vectors[0]) assert all(len(v) == num_elements for v in vectors), 'different sizes' return [sum(vector[i] for vector in vectors) for i in range(num_elements)] vector_sum([[1, 2], [3, 4], [5, 6], [7, 8]]) #%%
class Underscore(object): value = [] mapped = [] reduced = [] rejected = [] found = 0 def map(self, arr, function): for i in range(0, len(arr)): ld = function self.mapped.append(ld(arr[i])) return self.mapped def reduce(self, arr): one_digit = 0 for i in range(0, len(arr)): one_digit += arr[i] self.reduced.append(one_digit) return self.reduced def find(self, arr, function, num): for x in range(0, len(arr)): ld = function(num, arr[x]) if ld: self.found = arr[x] else: continue return True def filter(self, arr, function): for x in arr: data = function if data(x): self.value.append(x) return self.value def reject(self, arr, function, num): for i in range(0, len(arr)): ld = function(num, arr[i]) if ld: continue else: self.rejected.append(arr[i]) return self.rejected # Let's create an instance of our class # _ = Underscore() # yes we are setting our instance to a variable that is an underscore # evens = _.filter([1, 2, 3, 4, 5, 6], lambda x: x % 2 == 0) # add2 = _.map([1, 2, 3, 4, 5, 6], lambda x: x + 2) # should return [2, 4, 6] after code is implemented # reduction = _.reduce([1, 2, 3, 4, 5, 6]) # found_it = _.find([1, 2, 3, 4, 5, 6], lambda x, num: x == num, 4) # rejection = _.reject([1, 2, 3, 4, 5, 6], lambda num, x: num == x, 3) # print(evens) # print(add2) # print(reduction) # print(found_it) # print(rejection)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 7 13:29:42 2019 @author: lulumeng """ import pandas as pd from sklearn import preprocessing def data_read(file_path): data_raw = pd.read_csv(file_path,sep=r'\t',header=None, engine='python') x_raw = data_raw.iloc[:,:-1] y = data_raw.iloc[:,-1] # to do one-hot encoding for string column x = pd.get_dummies(x_raw) x = x.values y = y.values return x, y def data_norm(data): #normoalize with min max scaler min_max_scaler = preprocessing.MinMaxScaler() data_scaled = min_max_scaler.fit_transform(data) return data_scaled if __name__ == "__main__": #example of data loading x1,y1 = data_read("project2_dataset1.txt") x1_sc = data_norm(x1) x2,y2 = data_read("project2_dataset2.txt") x2_sc = data_norm(x2)
def getNoRectangles(n): from math import sqrt res = 0 for i in range(1, int(sqrt(n))+1): res += int(n/i)-i+1 return res N = int(input()) print (getNoRectangles(N))
#section 1 f = open("data.csv","r") #accessing the file print(f) #display the I/O header stations = f.read() #assign the contents of the file to the variable stations print(stations) #display the contents #section 2 station_list = stations.split('\n') #split the stations list by the new line character (by line) first_five = station_list[:5] # create a new list of 5 items which is a sublist of station_list #section 3 nested_list = [] #initialise nested_list for x in station_list: #iteration statement with x as iterator variable comma_list = x.split(',') #split each row and assign this newly split row to variable comma_list nested_list.append(comma_list) #append each new split row to nested_list print(nested_list[0:5]) #display the first five elements of nested_list #section 4 rainfall_list = [] for row in nested_list; station = row[0] rain = float(row[1]) float_list = [station, rain] rainfall_list.append(float_list) print(rainfall_list[:5]) #section 5 less_than_60 = [] for x in rainfall_list: if x[1] < 60 less_than_60.append(x[0]) print(less_than_60) f.close()
prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name? " name = input(prompt) print("\nHello, " + name + "!") age = input("How old are you: ") age = int(age) if age <= 18: print("You are not eligible to vote") else: print("you are eligible")
for item in range(20): if item == range(20)[-1]: print('*'*item) s = "Sekhar" copy = s s = "Sekhartsr" print("now S: ["+s+"], copy : ["+copy+"]") li = [2, 5, 8, 6] li_copy = li li[0] = 1 print("now li: ["+str(li)+"], li_copy : ["+str(li_copy)+"]")
# m × n = m + (m × (n - 1)). def Multiply(m, n): # generate base case for the recursive algorithm # base case m x 1 = m if n == 1: return m else: return m + Multiply(m, n - 1) def main(): print(Multiply(5, 4)) if __name__ == '__main__': main()
# Practical 1- Nguyen Quoc Minh Quan def main(): # enter your algorithm here # the logic can be included in another method list1 = [] # get number of elements inside a list n = int(input("Input the number of elements inside a list: ")) for i in range(n): elements = int(input(">> ")) list1.append(elements) print("Your current list: {}".format(list1)) # Check for duplicates by using Set and comparing len of the Set and the List # in Python, all elements inside a Set must be unique if len(list1) == len(set(list1)): return print("All the numbers are different from each other") else: return print("All the numbers are NOT different from each other") if __name__ == "__main__": main()
""" This model builds an index of web pages. """ import requests import pickle from bs4 import BeautifulSoup from BTrees import BTreeST class IndexWeb(object): """ an index of web pages each web page is stored as a file """ def __init__(self): self.st = BTreeST() def add(self, r): self.st.add(r) def size(self): return self.st.size() def contains(self, key): return self.st.contains(key) def get(self, key): """ key: a word value: list of urls """ return self.st.get(key) ########################################################### if __name__ == "__main__": ROOTURL = "http://www.princeton.edu" MAXNODES = 100 rset = set() # create index index = IndexWeb() # get root page r = requests.get(ROOTURL) rset.add(r) numwebpages = 0 while len(rset) < 200: r = rset.pop() index.add(r) numwebpages += 1 numnodes, numwords = index.size() print(numnodes, numwords, numwebpages) if numnodes > MAXNODES: print("total nodes: ", numnodes) break else: soup = BeautifulSoup(r.text, "lxml") for url in soup.find_all('a'): # 2 lines for debugging index.get #if len(rset) == 2: # break try: link = url['href'] if 'javascript' in link: continue if 'http' not in link: myurl = ROOTURL + link else: myurl = link try: rnext = requests.get(myurl) rset.add(rnext) except ConnectionError: print(myurl) continue except KeyError: continue print("len rset", len(rset)) while len(rset) > 0: r = rset.pop() index.add(r) numwebpages += 1 numnodes, numwords = index.size() print(numnodes, numwords, numwebpages) if numnodes > MAXNODES: print("total nodes: ", numnodes) break print("no more web pages") with open("index.txt", 'wb') as fp: pickle.dump(index, fp) print("wrote index to file") ########################################################################### print("Start searching") with open("index.txt", "rb") as fp: index2 = pickle.load(fp) with open("searchterms.txt", 'r', encoding='utf-8') as f: for word in f.read().split(): values = index2.get(word) if values: print(word, ":", values) else: print(word, "not found") print("done searching")
import sqlite3 from tkinter import * from tkinter import messagebox from PIL import Image,ImageTk import os # from tkinter import ttk def insert(): # database con = sqlite3.connect("ContactInfo.db") cur = con.cursor() cur.execute("INSERT INTO addresses VALUES(:First_Name,:Last_Name, :Gender, :Age, :Address, :Contact)",{ 'First_Name': first_name.get(), 'Last_Name': last_name.get(), 'Gender': gender.get(), 'Age': age.get(), 'Address': address.get(), 'Contact': contact.get() }) messagebox.showinfo("Employee", "Employee Added Sucessfully !") con.commit() con.close() root.destroy() os.system(('contact.py')) def clear(): first_name.delete(0,END) last_name.delete(0,END) gender.delete(0,END) age.delete(0,END) address.delete(0, END) contact.delete(0,END) def add(): global root root = Toplevel() root.title("Add Employee") # myimage1 = ImageTk.PhotoImage(Image.open('./images/add.png')) # label1 = Label(root, image=myimage1) # label1.pack() global first_name global last_name global gender global age global address global contact # desgin root.geometry("1366x768+60+10") root.resizable(0, 0) # root.iconbitmap('./images/3.ico') first_name_lbl = Label(root, text="First Name", font=('Consolas', 15), bg="white") first_name_lbl.place(x=180, y=200) last_name_lbl = Label(root, text="Last Name", font=('Consolas', 15), bg="white") last_name_lbl.place(x=720, y=200) gender_lbl = Label(root, text="Gender", font=('Consolas', 15), bg="white") gender_lbl.place(x=180, y=290) age_lbl = Label(root, text="Age", font=('Consolas', 15), bg="white") age_lbl.place(x=720, y=290) address_lbl = Label(root, text="Address", font=('Consolas', 15), bg="white") address_lbl.place(x=180, y=380) contact_lbl = Label(root, text="Contact", font=('Consolas', 15), bg="white") contact_lbl.place(x=720, y=380) first_name = Entry(root, width=40, border=0, font=('Consolas', 15)) first_name.place(x=180, y=230) last_name = Entry(root, width=40, border=0, font=('Consolas', 15)) last_name.place(x=720, y=230) gender = Entry(root, width=40, border=0, font=('Consolas', 15)) gender.place(x=180, y=320) age = Entry(root, width=40, border=0, font=('Consolas', 15)) age.place(x=720, y=320) address = Entry(root, width=40, border=0, font=('Consolas', 15)) address.place(x=180, y=410) contact = Entry(root, width=40, border=0, font=('Consolas', 15)) contact.place(x=720, y=410) add_btn = Button(root, text="ADD", font=('Consolas', 15), cursor='hand2', bg="#00bff3", border=0, activebackground="#00bff3", padx=25, pady=10,command=insert) add_btn.place(x=560, y=630) clear_btn = Button(root, text="CLEAR", font=('Consolas', 15), cursor='hand2', bg="#00bff3", border=0, activebackground="#00bff3", padx=25, pady=10,command=clear) clear_btn.place(x=715, y=630) root.mainloop()
import numpy as np from timeit import repeat from matplotlib import pyplot as plt from tree import make_tree from tree_np import make_tree_np iterations = np.arange(1, 15, 1) length = 1 scale = 0.6 angle = 0.1 def plot_time(iterations): tree_list, = plt.plot(iterations, list(map(time_to_make_tree, iterations)), label='lists') print() tree_np, = plt.plot(iterations, list(map(time_to_make_tree_np, iterations)), label='numpy arrays') plt.ylim(bottom=0) plt.ylabel('seconds') plt.xlabel('iterations') plt.title('Comparison of performance times') plt.legend(handles=[tree_list, tree_np]) plt.savefig('perf_plot.png') def time_to_make_tree(iterate): def totime(): make_tree(iterate, length, scale, angle, True) num_tests = 10 tests = repeat(totime, repeat=1, number=num_tests) average = [t / num_tests for t in tests] return average def time_to_make_tree_np(iterate): def totime(): make_tree_np(iterate, length, scale, angle, True) num_tests = 15 tests = repeat(totime, repeat=1, number=num_tests) average = [t / num_tests for t in tests] return average if __name__ == "__main__": plot_time(iterations)
#################################################################### # Structure: The placement of each element in the binary tree must # satisfy the binary search property: the value of the key of # an element is greater than the value of the key of the any element # element in its left subtree, and less than the value of the # key of an elment in its right subtree. #################################################################### class Node: def __init__(self, value = None, leftNode = None, rightNode = None): self.value = value self.rightNode = rightNode self.leftNode = leftNode def __str__ (self): return str(self.value) # Operations (provided by TreeADT) # Assumptions: Before any call is made to a tree operation, the tree has # been delcared and a constructor has been applied. class Tree: def __init__(self): self.root = None def insert(self, value): self.InsertItem(value, self.root) def InsertItem(self, value, childRoot): if ( self.root is None): self.root = Node(value) elif value < childRoot.value : self.InsertItem(value, childRoot.left) else: self.InsertItem( value, childRoot.right) def main(): print("Hello!") myTree = Tree() myTree.insert(1) myTree.insert(3) myTree.insert(2) myTree.insert(5) print("End") main()
# Using text2 from the nltk book corpa, create your own version of the # MadLib program. # Requirements: # 1) Only use the first 150 tokens # 2) Pick 5 parts of speech to prompt for, including nouns # 3) Replace nouns 15% of the time, everything else 10% # Deliverables: # 1) Print the orginal text (150 tokens) # 1) Print the new text import nltk import random from nltk.tokenize import sent_tokenize, word_tokenize #get text2 sense = nltk.corpus.gutenberg.words('austen-sense.txt')[:150] #taken from madlib_generatorP3.py #puts spaces where they should be def spaced(word): if word in [",", ".", "?", "!", ":", ";"]: return word else: return " " + word print("START*******\n\n") #tags words with pos abbreviations pos = nltk.pos_tag(sense) tagmap = {"NN":"a noun","NNS":"a plural noun","VB":"a verb","JJ":"an adjective", "PRP$":"a possessive pronoun"} subprobs= {"NN":.15,"NNS":.1,"VB":.1,"JJ":.1, "PRP$":.1} final = [] #taken from madlib_generatorP3.py #replaces words with inputted words for (word, tag) in pos: if tag not in subprobs or random.random() > subprobs[tag]: final.append(spaced(word)) else: new_word = input("Please enter %s:\n" % (tagmap[tag])) final.append(spaced(new_word)) #prints original text, followed by madlibbed text print("\n\nEND*******") print ("".join(spaced(w) for w in sense)) print ("\n", "".join(final))
def overLappingArea(R1X1Y1, R1X2Y2, R2X1Y1, R2X2Y2): R1x1 = R1X1Y1.get("x1") R2x1 = R2X1Y1.get("x1") R1x2 = R1X2Y2.get("x2") R2x2 = R2X2Y2.get("x2") R1y1 = R1X1Y1.get("y1") R2y1 = R2X1Y1.get("y1") R1y2 = R1X2Y2.get("y2") R2y2 = R2X2Y2.get("y2") width = min(R1x2, R2x2) - max(R1x1, R2x1) height = min(R1y2, R2y2) - max(R1y1, R2y1) # height=min()-max() if width <= 0 or height <= 0: return None else: return width*height if __name__ == "__main__": print(overLappingArea({"x1": 2, "y1": 4}, {"x2": 3, "y2": 5}, { "x1": 2, "y1": 2}, {"x2": 3, "y2": 2}))
def findCommon(arr1, arr2): newarr = [] i = 0 j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] == arr2[j]: newarr.append(arr1[i]) i += 1 j += 1 elif(arr1[i] > arr2[j]): j += 1 else: i += 1 return newarr if __name__ == "__main__": print(findCommon([1, 2, 3, 5, 4], [1, 4, 5, 8, 9]))
print("Enter the marks") marks = int(input()) def getPercentage(marks): return (marks/1200)*100 print("Yo got {0}".format(getPercentage(marks)))
#!/usr/bin/env python3.7 string1=input("Enter the String :") print("printing the string :"+string1) print("printing the string :"+string1.upper()) print("printing the string :"+string1.lower()) print("First Character: "+string1[0]) print("Last Character: "+string1[-1]) print("Middle Character: "+string1[int(len(string1)/2)]) print("Even Character: "+string1[0::2]) print("Odd Character: "+string1[1:: 2])
"""### Problem Statements In an ocean, there are `n` islands some of which are connected via bridges. Travelling over a bridge has some cost attaced with it. Find bridges in such a way that all islands are connected with minimum cost of travelling. You can assume that there is at least one possible way in which all islands are connected with each other. You will be provided with two input parameters: 1. `num_islands` = number of islands 2. `bridge_config` = list of lists. Each inner list will have 3 elements: a. island A b. island B c. cost of bridge connecting both islands Each island is represented using a number **Example:** * `num_islands = 4` * `bridge_config = [[1, 2, 1], [2, 3, 4], [1, 4, 3], [4, 3, 2], [1, 3, 10]]` Input parameters explanation: 1. Number of islands = 4 2. Island 1 and 2 are connected via a bridge with cost = 1 Island 2 and 3 are connected via a bridge with cost = 4 Island 1 and 4 are connected via a bridge with cost = 3 Island 4 and 3 are connected via a bridge with cost = 2 Island 1 and 3 are connected via a bridge with cost = 10 In this example if we are connecting bridges like this... * between 1 and 2 with cost = 1 * between 1 and 4 with cost = 3 * between 4 and 3 with cost = 2 ...then we connect all 4 islands with `cost = 6` which is the minimum traveling cost. ### Hint In addition to using a graph, you may want to use a custom priority queue for solving this problem. If you do not want to create a custom priority queue, you can use Python's `heapq` implementation. Using the `heapq` module, you can convert an existing list of items into a heap. The following two functionalities can be very handy for this problem: 1. `heappush(heap, item)` — add `item` to the `heap` 2. `heappop(heap)` — remove the smallest item from the `heap` Let's look at the above methods in action. We start by creating a list of integers. """ import heapq def create_graph(num_islands, bridge_config): # [YC] This is what I didn't think of. You need to first create a graph. Recall how to represent a graph. graph = [[] for _ in range(num_islands + 1)] for bridge in bridge_config: island_1, island_2, cost_1_2 = bridge[0], bridge[1], bridge[2] graph[island_1].append((island_2, cost_1_2)) # [YC] This is how we are going to represent graph here, with index as the start node, first element in tuple as the destination and the second of the tuple as the cose graph[island_2].append((island_1, cost_1_2)) return graph # TODO: [YC] why can you ensure all the vertex are connected??? def minimum_cost(graph): # [YC] This is the key of this problem. I didn't figure out how to solve this, this is integrated with the provided solution. start_vertex = 1 visited = [False for _ in range(len(graph) + 1)] heap = [(0, start_vertex)] total_cost = 0 while len(heap) > 0: # Always get the vertex with the least cost cost, current_vertex = heapq.heappop(heap) if visited[current_vertex]: continue # If the vertex has never been visited before, then visit it: # 1) add the cost to total cost # 2) add all the neighbor to the heap. # 3) mark visited True total_cost += cost for neighbor, edge_cost in graph[current_vertex]: heapq.heappush(heap, (edge_cost, neighbor)) visited[current_vertex] = True return total_cost # def get_minimum_cost_of_connecting(num_islands, bridge_config): # [YC] My own trying # """ # :param: num_islands - number of islands # :param: bridge_config - bridge configuration as explained in the problem statement # return: cost (int) minimum cost of connecting all islands # TODO complete this method to returh minimum cost of connecting all islands # """ # # Graph is a list of lists # graph = create_graph(num_islands, bridge_config) # # cost_heap = [] # # Create a heap order by cost # for bridge in bridge_config: # island_1, island_2, cost_1_2 = bridge[0], bridge[1], bridge[2] # heapq.heappush(cost_heap, (cost_1_2, island_1, island_2)) # # How to judge if all the island are connected? # connected = {} # total_cost = 0 # while len(connected) < num_islands and cost_heap: # cost, head, tail = cost_heap.pop() # if head in connected and tail in connected: # pass # total_cost += cost # connected.update({head: True}) # connected.update({tail: True}) # return cost def get_minimum_cost_of_connecting(num_islands, bridge_config): graph = create_graph(num_islands, bridge_config) return minimum_cost(graph) def test_function(test_case): num_islands = test_case[0] bridge_config = test_case[1] solution = test_case[2] output = get_minimum_cost_of_connecting(num_islands, bridge_config) if output == solution: print("Pass") else: print("Fail") num_islands = 4 bridge_config = [[1, 2, 1], [2, 3, 4], [1, 4, 3], [4, 3, 2], [1, 3, 10]] solution = 6 test_case = [num_islands, bridge_config, solution] test_function(test_case) num_islands = 5 bridge_config = [[1, 2, 5], [1, 3, 8], [2, 3, 9]] solution = 13 test_case = [num_islands, bridge_config, solution] test_function(test_case) num_islands = 5 bridge_config = [[1, 2, 3], [1, 5, 9], [2, 3, 10], [4, 3, 9]] solution = 31 test_case = [num_islands, bridge_config, solution] test_function(test_case)
# Python3 implementation to print the path from # root to a given node in a binary tree # Helper Class that allocates a new node # with the given data and None left and # right pointers. class getNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if there is a path from # root to the given node. It also # populates 'arr' with the given path def hasPath(root, arr, x): # if root is None there is no path if (not root): return False # push the node's value in 'arr' arr.append(root.data) # if it is the required node # return true if (root.data == x): return True # else check whether the required node # lies in the left subtree or right # subtree of the current node if (hasPath(root.left, arr, x) or hasPath(root.right, arr, x)): return True # required node does not lie either in # the left or right subtree of the current # node. Thus, remove current node's value # from 'arr'and then return false arr.pop(-1) return False # function to print the path from root to # the given node if the node lies in # the binary tree def printPath(root, x): # vector to store the path arr = [] # if required node 'x' is present # then print the path if (hasPath(root, arr, x)): for i in range(len(arr) - 1): print(arr[i], end="->") print(arr[len(arr) - 1]) # 'x' is not present in the # binary tree else: print("No Path") # Driver Code if __name__ == '__main__': # binary tree formation root = getNode(1) root.left = getNode(2) root.right = getNode(3) root.left.left = getNode(4) root.left.right = getNode(5) root.right.left = getNode(6) root.right.right = getNode(7) x = 5 printPath(root, x) # This code is contributed by PranchalK
def subsets(arr, index=0): """ :param: arr - input integer array Return - list of lists (two dimensional array) where each list represents a subset TODO: complete this method to return subsets of an array """ if len(arr) == 0: return [[]] if len(arr[index:]) == 1: return [[arr[index]], []] if len(arr[index:]) == 2: return [arr[index:], [arr[index]], [arr[index+1]], []] first_ele = arr[index] index += 1 sub_results = subsets(arr, index) new_result = [[first_ele] + result for result in sub_results] return new_result + sub_results # [0: index] is left inclusive, but right exclusive def test_function(test_case): arr = test_case[0] solution = test_case[1] output = subsets(arr) output.sort() solution.sort() if output == solution: print("Pass") else: print("Fail") arr = [9] solution = [[], [9]] test_case = [arr, solution] test_function(test_case) arr = [5, 7] solution = [[], [7], [5], [5, 7]] test_case = [arr, solution] test_function(test_case) arr = [9, 12, 15] solution = [[], [15], [12], [12, 15], [9], [9, 15], [9, 12], [9, 12, 15]] test_case = [arr, solution] test_function(test_case) arr = [9, 8, 9, 8] solution = [[], [8], [9], [9, 8], [8], [8, 8], [8, 9], [8, 9, 8], [9], [9, 8], [9, 9], [9, 9, 8], [9, 8], [9, 8, 8], [9, 8, 9], [9, 8, 9, 8]] test_case = [arr, solution] test_function(test_case)
class Node: """LinkedListNode class to be used for this problem""" def __init__(self, data): self.data = data self.next = None def swap_nodes(head, left_index, right_index): """ :param: head- head of input linked list :param: left_index - indicates position :param: right_index - indicates position return: head of updated linked list with nodes swapped TODO: complete this function and swap nodes present at left_index and right_index Do not create a new linked list 1) the next node of node_before_left is the next of the next of itself, pointing 5 --> 6 2) the TODO [YC] reproduce the solution 20191119 """ current_node = head counter = 0 while current_node is not None: # counter += 1 # [0, 1, 2, 3, 4, 5, 6] if counter == left_index: # say i = 3, j =5. [3, 4, 5, '2', 6, '1', 9], head = 3, counter = 0 # (5) # current (5) left_node = current_node.next # (2) node_before_left = current_node # (5) node_right_next = left_node.next # (6) elif counter == right_index: # current (6) right_node = current_node.next # ('1') left_node.next = right_node.next # left node is '2', and the next of '2' is 9 node_before_left.next = right_node # node before left node is 5, 5 and then '1' right_node.next = node_right_next current_node.next = left_node print("current node", current_node.value) current_node = current_node.next # TODO: check if left previous is None return head def test_function(test_case): head = test_case[0] left_index = test_case[1] right_index = test_case[2] left_node = None right_node = None temp = head index = 0 try: while temp is not None: if index == left_index: left_node = temp if index == right_index: right_node = temp break index += 1 temp = temp.next updated_head = swap_nodes(head, left_index, right_index) temp = updated_head index = 0 pass_status = [False, False] while temp is not None: if index == left_index: pass_status[0] = temp is right_node if index == right_index: pass_status[1] = temp is left_node index += 1 temp = temp.next if pass_status[0] and pass_status[1]: print("Pass") else: print("Fail") return updated_head except Exception as e: print("Fail") # helper functions for testing purpose def create_linked_list(arr): if len(arr)==0: return None head = Node(arr[0]) tail = head for data in arr[1:]: tail.next = Node(data) tail = tail.next return head def print_linked_list(head): while head: print(head.data, end=" ") head = head.next print() arr = [3, 4, 5, 2, 6, 1, 9] head = create_linked_list(arr) left_index = 3 right_index = 4 test_case = [head, left_index, right_index] updated_head = test_function(test_case) # arr = [3, 4, 5, 2, 6, 1, 9] # left_index = 2 # right_index = 4 # head = create_linked_list(arr) # test_case = [head, left_index, right_index] # updated_head = test_function(test_case) # # # arr = [3, 4, 5, 2, 6, 1, 9] # left_index = 0 # right_index = 1 # head = create_linked_list(arr) # test_case = [head, left_index, right_index] # updated_head = test_function(test_case)
"""Now that you saw the dynamic programming solution for the knapsack problem, it's time to implement it. Implement the function max_value to return the maximum value given the items (items) and the maximum weight of the knapsack (knapsack_max_weight). The items variable is the type Item, which is a named tuple.""" import collections Item = collections.namedtuple('Item', ['weight', 'value']) def max_value(knapsack_max_weight=None, items=None): """ Get the maximum value of the knapsack. """ # items_in_bag = collections.defaultdict(list) # item_seen = [] # result_table = [0 for i in range(knapsack_max_weight + 1)] # for item in items: # item_seen.append(item) # weight = item[0] # value = item[1] # for weight_limit in range(knapsack_max_weight + 1): # if weight > weight_limit: # continue # elif weight <= weight_limit: # remaining_weight = weight_limit - weight # You should evaluate the weight of the current item. [YC] This it important to note that the remaining weight should not be calculated with the weight limit of the knapsack, but the current weight limit!!! # if weight not in items_in_bag[remaining_weight]: # This is important to avoid adding one object twice # possible_value = value + result_table[remaining_weight] # bag_elements = items_in_bag[remaining_weight] + [weight] # Now you update the element in the bag, it should contain the current weight and whatever is it in the remaining_weight bag. # else: # possible_value = max(result_table[remaining_weight], value) # if value > result_table[remaining_weight]: # bag_elements = [weight] # else: # bag_elements = items_in_bag[remaining_weight] # TODO: This method doesn't include the items that were seen but not in the remaining weight. # if possible_value > result_table[weight_limit]: # items_in_bag[weight_limit] = bag_elements # result_table[weight_limit] = possible_value # [YC] Yay!!!!!! result_table = [[0 for i in range(knapsack_max_weight + 1)] for j in range(len(items) + 1)] # This is to build a matrix of the result for index, item in enumerate(items): index += 1 # The first row of the result_table is 0s, when no element is visited weight = item[0] value = item[1] result_table[index] = result_table[index - 1].copy() for weight_limit in range(knapsack_max_weight + 1): if weight > weight_limit: continue elif weight <= weight_limit: remaining_weight = weight_limit - weight possible_value = value + result_table[index - 1][remaining_weight] result_table[index][weight_limit] = max(result_table[index][weight_limit], possible_value) return result_table[index][knapsack_max_weight] tests = [ { 'correct_output': 14, 'input': { 'knapsack_max_weight': 15, 'items': [Item(10, 7), Item(9, 8), Item(5, 6)]}}, { 'correct_output': 13, 'input': { 'knapsack_max_weight': 25, 'items': [Item(10, 2), Item(29, 10), Item(5, 7), Item(5, 3), Item(5, 1), Item(24, 12)]}} ] for test in tests: assert test['correct_output'] == max_value(**test['input'])
def binary_search(array, target): # [Mine] '''Write a function that implements the binary search algorithm using iteration args: array: a sorted array of items of the same type target: the element you're searching for returns: int: the index of the target, if found, in the source -1: if the target is not found ''' low_i = 0 high_i = len(array) - 1 if len(array) == 0: return -1 mid_index = (low_i + high_i) // 2 mid = array[mid_index] if target == mid: return mid_index while high_i - low_i > 1: mid_index = (low_i + high_i) // 2 mid = array[mid_index] if target > mid: low_i = mid_index elif target < mid: high_i = mid_index else: return mid_index if array[high_i] == target: return high_i elif array[low_i] == target: return low_i return -1 def binary_search(array, target): # solution from Udacity start_index = 0 end_index = len(array) - 1 while start_index <= end_index: mid_index = (start_index + end_index) // 2 # integer division in Python 3 mid_element = array[mid_index] if target == mid_element: # we have found the element return mid_index elif target < mid_element: # the target is less than mid element end_index = mid_index - 1 # we will only search in the left half else: # the target is greater than mid element start_index = mid_element + 1 # we will search only in the right half return -1 def test_function(test_case): answer = binary_search(test_case[0], test_case[1]) if answer == test_case[2]: print("Pass!") else: print("Fail!") # test case 1 array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target = 6 index = 6 test_case = [array, target, index] test_function(test_case) # Test case 2 array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target = 12 index = -1 test_case = [array, target, index] test_function(test_case)
''' Computes gcd(a, b) ''' def EuclideanAlgorithm(a, b): #continue to divide a by be until remainder is 0 if a == 0: return b else: return EuclideanAlgorithm(b % a, a) def EuclideanIO(): print('\nThis program will calculate the greatest common divisor of 2 numbers.') a = input('Please enter the first value: ') b = input('Please enter the second value: ') c = EuclideanAlgorithm(a, b) print('The greatest common divisor is ' + str(c)) if __name__ == '__main__': EuclideanIO()
import string import sys text = raw_input("What are you trying to decode?") num = int(raw_input("How many characters is it shifting to the right?")) def shift(text, num): alphabet = string.ascii_lowercase shifted_alphabet = alphabet[num:] + alphabet[:num] table = string.maketrans(alphabet, shifted_alphabet) return text.translate(table) print shift(text,num)
import pprint partion = 3 def swap (list, i, n, Blist): while i + 1 != n: list[i][0] = list[i + 1][0] list[i][1] = list[i + 1][1] list[i][2] = list[i + 1][2] Blist[i][0] = Blist[i + 1][0] Blist[i][1] = Blist[i + 1][1] Blist[i][2] = Blist[i + 1][2] i = i + 1 n = int (input ("Enter Number of total states : ")) F = int (input ("Enter number if final states :")) Nstates = [[0 for i in range (n)] for j in range (n)] BNstates = [[0 for i in range (n)] for j in range (n)] print ("Non-final States ") for i in range (0, n): print("For State Q{0}: ".format(i)) if i == n - F: print ("Final States") if i < n - F: BNstates[i][0] = 1 Nstates[i][1] = int (input ("for a : ")) Nstates[i][2] = int (input ("for b : ")) if i >= n - F: BNstates[i][0] = 2 Nstates[i][1] = int (input ("for a : ")) Nstates[i][2] = int (input ("for b : ")) Nstates[i][0] = i for i in range (0, n): if Nstates[i][1] >= n - F: BNstates[i][1] = 2 else: BNstates[i][1] = 1 if Nstates[i][2] >= n - F: BNstates[i][2] = 2 else: BNstates[i][2] = 1 print ("states\t\ta\t\t\tb\t") for i in range (0, n): print ("q{0}({1})\t\t{2}({3})\t\t{4}({5})\t".format (Nstates[i][0], BNstates[i][0], Nstates[i][1], BNstates[i][1], Nstates[i][2], BNstates[i][2])) counter1 = 0 counter2 = 0 counter3 = 0 counter4 = 0 save = 0 save1 = 0 temp = [[0 for i in range (n)] for j in range (n)] temp1 = [[0 for i in range (n)] for j in range (n)] Btemp = [[0 for i in range (n)] for j in range (n)] Btemp1 = [[0 for i in range (n)] for j in range (n)] saveL = [0 for i in range (10)] i = 0 checking = 0 while i < n: if i + 1 == n: break if ((BNstates[i][0] != BNstates[i + 1][0])): print (" ") elif ((BNstates[i][1] == BNstates[i + 1][1]) and (BNstates[i][2] == BNstates[i + 1][2])): counter1 = counter1 + 1 else: save = i ko = i a = 0 b = 0 while (BNstates[i][0] == BNstates[i + 1][0]): if ((BNstates[save][1] == BNstates[i + 1][1]) and (BNstates[save][2] == BNstates[i + 1][2])): counter2 = counter2 + 1 temp[a][0] = Nstates[i + 1][0] temp[a][1] = Nstates[i + 1][1] temp[a][2] = Nstates[i + 1][2] Btemp[a][0] = BNstates[i + 1][0] Btemp[a][1] = BNstates[i + 1][1] Btemp[a][2] = BNstates[i + 1][2] a = a + 1 else: counter3 = counter3 + 1 temp1[b][0] = Nstates[i + 1][0] temp1[b][1] = Nstates[i + 1][1] temp1[b][2] = Nstates[i + 1][2] Btemp1[b][0] = BNstates[i + 1][0] Btemp1[b][1] = BNstates[i + 1][1] Btemp1[b][2] = BNstates[i + 1][2] b = b + 1 i = i + 1 if i + 1 == n: break i = ko i = i + 1 a = 0 b = 0 if counter3 > counter2: while i < n: if counter3 == 0: break if Nstates[i][0] == temp1[a][0]: swap (Nstates, i, n, BNstates) Nstates[n - 1][0] = temp1[a][0] Nstates[n - 1][1] = temp1[a][1] Nstates[n - 1][2] = temp1[a][2] save1 = temp1[a][0] BNstates[n - 1][0] = partion BNstates[n - 1][1] = Btemp1[a][1] BNstates[n - 1][2] = Btemp1[a][2] for i in range (0, n): for j in range (1, 3): if Nstates[i][j] == save1: BNstates[i][j] = partion a = a + 1 counter3 = counter3 - 1 i = 0 i = i + 1 i = -1 counter2 = 0 counter3 = 0 coutner4 = 0 counter1 = 0 partion = partion + 1 if counter3 < counter2: for i in range (0, n): if counter3 == 0: break if Nstates[i][0] == temp1[a][0]: swap (Nstates, i, n, BNstates) Nstates[n - 1][0] = temp1[a][0] Nstates[n - 1][1] = temp1[a][1] Nstates[n - 1][2] = temp1[a][2] save1 = temp1[a][0] BNstates[n - 1][0] = partion BNstates[n - 1][1] = Btemp1[a][1] BNstates[n - 1][2] = Btemp1[a][2] for i in range (0, n): for j in range (1, 3): if Nstates[i][j] == save1: BNstates[i][j] = partion a = a + 1 counter3 = counter3 - 1 i = -1 counter2 = 0 counter3 = 0 coutner4 = 0 counter1 = 0 partion = partion + 1 i = i + 1 # printing output print ("-------------------Minimized DFA--------------------") print ("States\t\ta\t\t\tb\t") for i in range (0, n): if Nstates[i][0] >= n - F: print ( "*q{0}({1})\t\t{2}({3})\t\t{4}({5})\t".format (Nstates[i][0], BNstates[i][0], Nstates[i][1], BNstates[i][1], Nstates[i][2], BNstates[i][2])) else: print ( "q{0}({1})\t\t{2}({3})\t\t{4}({5})\t".format (Nstates[i][0], BNstates[i][0], Nstates[i][1], BNstates[i][1], Nstates[i][2], BNstates[i][2])) i = 0 print ("\n\n-------------------Partions--------------------------") print ("Partion a\tb") while i < n: if i + 1 == n: print ("{0}\t\t{1}\t{2}".format (BNstates[i][0], BNstates[i][1], BNstates[i][2])) break if BNstates[i][0] == BNstates[i + 1][0]: while (BNstates[i][0] == BNstates[i + 1][0]): i = i + 1 if i + 1 == n: print ("{0}\t\t{1}\t{2}".format (BNstates[i][0], BNstates[i][1], BNstates[i][2])) break print ("{0}\t\t{1}\t{2}".format (BNstates[i][0], BNstates[i][1], BNstates[i][2])) i = i + 1
#Find and replace str = "If monkeys like bananas, then I must be a monkey!" print str print str.find("monkey") print str.replace("monkey", "allegator") # Min. and max x = [2,54,-2,7,12,98] print "max number is:", max(x) print "min number is:", min(x) #first and last x = ["hello",2,54,-2,7,12,98,"world"] print "first value is:", x[0] print "last value is:", x[len(x)-1] Fvalue = x[0] Lvalue = x[-1] newList = [] newList.append(Fvalue) newList.append(Lvalue) print newList #from asnwer key: print x[0],x[len(x)-1] #new list x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() sorted_list = x print sorted_list half_list_value = len(x)/2 total_list_value = len(x) print half_list_value, total_list_value list1 = sorted_list[:half_list_value] print list1 list2 = sorted_list[half_list_value:] print list2 list2.insert(0, list1) print list2
import math termX=input("Inserisci il termine in x: ") termN=input("Inserisci il termine noto: ") if termX == 0 and termN ==0: print "L'equazione e' indeterminata. " elif termX == 0: print "L'equazione e' impossibile. " else: ris =float (termN) / float (termX) * (-1.0) print "La soluzione dell'equazione e' x = ",ris
def ispow2(n): ''' True if n is a power of 2, False otherwise >>> ispow2(5) False >>> ispow2(4) True ''' return (n & (n-1)) == 0 def nextpow2(n): ''' Given n, return the nearest power of two that is >= n >>> nextpow2(1) 1 >>> nextpow2(2) 2 >>> nextpow2(5) 8 >>> nextpow2(17) 32 ''' if ispow2(n): return n count = 0 while n != 0: n = n >> 1 count += 1 return 1 << count class SamplingRateError(ValueError): ''' Indicates that the conversion of frequency to sampling rate could not be performed. ''' def __init__(self, fs, requested_fs): self.fs = fs self.requested_fs = requested_fs def __str__(self): mesg = 'The requested sampling rate, %f Hz, is greater than ' + \ 'the DSP clock frequency of %f Hz.' return mesg % (self.requested_fs, self.fs) def convert(src_unit, dest_unit, value, dsp_fs): ''' Converts value to desired unit give the sampling frequency of the DSP. Parameters specified in paradigms are typically expressed as frequency and time while many DSP parameters are expressed in number of samples (referenced to the DSP sampling frequency). This function provides a convenience method for converting between conventional values and the 'digital' values used by the DSP. Note that for converting units of time/frequency to n/nPer, we have to coerce the value to a multiple of the DSP period (e.g. the number of 'ticks' of the DSP clock). Appropriate strings for the unit types: fs sampling frequency nPer number of samples per period n number of samples s seconds ms milliseconds nPow2 number of samples, coerced to the next greater power of 2 (used for ensuring efficient FFT computation) >>> convert('s', 'n', 0.5, 10000) 5000 >>> convert('fs', 'nPer', 500, 10000) 20 >>> convert('s', 'nPow2', 5, 97.5e3) 524288 Parameters ---------- src_unit: string dest_unit: string Destination unit value: numerical (e.g. integer or float) Value to be converted Returns ------- converted unit : numerical value ''' def fs_to_nPer(req_fs, dsp_fs): if dsp_fs < req_fs: raise SamplingRateError(dsp_fs, req_fs) return int(dsp_fs/req_fs) def nPer_to_fs(nPer, dsp_fs): return dsp_fs/nPer def n_to_s(n, dsp_fs): return n/dsp_fs def s_to_n(s, dsp_fs): return int(s*dsp_fs) def ms_to_n(ms, dsp_fs): return int(ms*1e-3*dsp_fs) def n_to_ms(n, dsp_fs): return n/dsp_fs*1e3 def s_to_nPow2(s, dsp_fs): return nextpow2(s_to_n(s, dsp_fs)) fun = '%s_to_%s' % (src_unit, dest_unit) return locals()[fun](value, dsp_fs)
import scripts as s def FindPrime(a, b): """Find all primes for all x in a <= x <= b.""" return [x for x in range(a, b + 1) if s.IsPrime(x)] # def IsPrime(x): # """Determine if x is prime.""" # if x < 2: # return False # if x == 2: # return True # for i in range(2, int(sqrt(x)) + 1): # if x % i == 0: # return False # return True def FindLargestFactor(num): #import pdb; pdb.set_trace() factors = [] prime_list = sorted(FindPrime(2,600851475143)) for each in prime_list: if num % each == 0: #while num / each !=1: num = num / each factors.append(each) each = prime_list[0] while num == 1: break return sorted(factors)[-1] def FindEasyLargestFactor(num): i = 2 #import pdb; pdb.set_trace() while i**2 < num: while num % i ==0 : num = num / i i += 1 return num def main(): #print sorted(FindPrime(2,13195)) print FindEasyLargestFactor(600851475143) if __name__ == '__main__': main()
from sys import argv script, rezultatai = argv in_rezultatai = open(rezultatai, 'w') in_rezultatai.truncate() print "Hello, I'm %r program." % (script) print "Please type 3 integer numbers. After each, please press ENTER button." first_number = int(raw_input("first number: ")) second_number = int(raw_input("second number: ")) third_number = int(raw_input("third number: ")) sum = first_number + second_number + third_number in_rezultatai = open(rezultatai, 'w') in_rezultatai.write(str(first_number) + "\n") in_rezultatai.write(str(second_number) + "\n") in_rezultatai.write(str(third_number) + "\n") in_rezultatai.write("sum = %d + %d + %d = %d" % (first_number, second_number, third_number, sum)) in_rezultatai.write("\n") print "You can find these numbers and their sum in %s.\nCheck it out and find if it's true!" % (rezultatai) in_rezultatai.close()
#lists and strings '''a string is a sequence of characters, and a list is a sequence of values but a list of characters is not the same as a string to convert from a string to a list of characters, you can use LIST''' s = "spam" #naturally creates a string print(type(s)) t = list(s) #leaves the string alone, but creates a new list with same values print(t) print(type(t)) '''however, when it pulls in that string, it treats each letter as it's own element''' '''if you want to break a string into full words, you can use the SPLIT method''' s = "pining for the fjords" #build a string print(s) print(type(s)) t = s.split() #invoke a method so use dot notation print(t) print(type(t)) '''after you've used the split method to break a string into a list of words, you can use the index operator to look at specific words''' print(t[2]) '''if needed, you can invoke split with a special argument called a DELIMITER the delimiter specifies which characters to use as word boundaries this can be helpful with oddly formatted data''' example = "spam-spam-spam-gobbles-timmy" print(example) print(type(example)) fixed_example = example.split("-") print(fixed_example) print(type(fixed_example)) '''you can also write the delimiter as a variable, and inject that this was how it was done in the text''' example = "spam-spam-spam-gobbles-timmy" print(example) print(type(example)) delimiter = "-" fixed_example = example.split(delimiter) print(fixed_example) print(type(fixed_example)) '''the inverse of split is JOIN, which is used to take a list of strings and concatenate the elements join is a string method, so yuou invoke it on the delimiter and pass the list as a parameter it's worth noting that this process TURNS A LIST INTO A STRING''' example = ["oh", "no", "mr.", "bliss"] #create the list print(example) print(type(example)) delimiter = " " #basically saying "put the space in and bring together" fixed_example = delimiter.join(example) #start with the delimiter (i.e. what you want between the elements), and then add JOIN and pass in the variable print(fixed_example) print(type(fixed_example)) '''you could bring the whole thing together without spaces, by just passing in empty quotes'''
#build a grade calculator user_input_1 = input("Please enter your class grade in digit form: \n") try: user_input = float(user_input_1) if user_input >= 1.1: print("That's not a valid score, asshole!") elif user_input >= 0.9: print("A") elif user_input >= 0.8: print("B") elif user_input >= 0.7: print("C") elif user_input >= 0.6: print("D") elif user_input < 0.6: print("You get an F!") except: print("Please enter in digits only, between 0 and 1.0.")
#practice parsing strings #you can use the FIND and SLICE methods to take only pieces of strings practice = "From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008" #create practice string found_1 = practice.find("@") #finds position about half way through found_2 = practice.find(" ", found_1) #telling it to start the find at position found in first find #the above will tell it to start after the @ sign, and extract the email domain and stop at the first blank space it sees email_domain = practice[found_1+1:found_2] print(email_domain) #the FORMAT OPERATOR #the format operator is % when looking at a string (and not a modulo) #it allows you to replace parts of the string(s), with data store in a variable #the result after being formatted is a string, even if you used an integer value... #however, you can use %d to indicate the value stored within a string is a decimal value #here is the difference: camels = 42 print("%d" % camels) #prints the string "42" #you can further embed the value into a sentence: print("I have spotted %d camels in the wild" % camels) #this works and prints the statement #a TUPLE is a sequence of comma separated values inside a pair of brackets #if there is more than one format sequence for a string, the second argument must also be a tuple (to account for what's going into the string) #the types of elements must match the format sequences #the number of elements must match the number of format sequences in the string print("In %d, I have spotted %g %s in the wild" % (3, 42, "camels")) #this works but see below #NOT SURE WHY THE VARIOUS LATTERS ARE BEING USED AFTER THE FORMAT OPERATOR #string challenge line = "X-DSPAM-Confidence:0.8475" #challenge is to 1) extract everything after the colon, and 2)convert that value to a floating point number line_2 = line.find(":") line_3 = line[line_2+1:(len(line))] #holy shit this worked...I didn't think it would answer = float(line_3) print(answer) print(type(answer)) #write a program to 1) prompt for file name, 2) read through the file and seek certain span of text user_input = input("Please enter a file name:\n") count = 0 total = 0 try: handle = open(user_input) except: print("Sorry, that file name is incorrect or doesn't exist.") exit() for i in handle: i = i.rstrip() #strip out whitespace if i.find("X-DSPAM-Confidence") == -1: #if the line does not include this text continue #ignore it and move to next line! count = count + 1 #as it proceeds, start counting lines it finds the above value found_1 = i.find(":") #now seek the colon values = i[found_1+2 : (len(i))] #seek difference between colon + space and end of text values = float(values) #that span of text (the spam scores) are converted to floating point total = total + values #add those values together into one large number answer = total / count #divide that large number by the count established earlier print("Average spam confidence:", answer)
#working on list methods #Python provides methods to operate on lists #you do not want to write these as practice = practice.sort(), because most list methods are void #to ADD SOMETHING to a list, you use the APPEND method practice = ["a", "b", "c"] practice.append("d") #adds "d" to end of list print(practice) #to append all of the elements in two lists, use the EXTEND method: practice_2 = ["e", "f", "g", "h", "i", "j", "k"] practice.extend(practice_2) print(practice) #now you'll have elements from practice and practice_2 put together #it's worth noting that in the example above, it leaves practice_2 unmodified #if you want to ARRANGE items in a list, you use the SORT method, which arranges from LOW TO HIGH messy = ["t", "e", "q", "a", "h", "j", "o"] print(messy) messy.sort() print(messy) #worth noting that the sort method will irrevocably alter the order in the original list #you can DELETE elements from a list in a couple different ways #one way is to use the POP method, which keeps the removed element(s) in the new variable that you create for it practice = ["a", "b", "c", "d"] practice_2 = practice.pop(1) #takes "b" out of practice, and puts it into practice_2 print(practice) #prints original without b print(practice_2) #now this has the b #if you don't need to keep the element(s), you can use the DEL operator: practice = ["a", "b", "c", "d"] del practice[1] #gets rid of element at one-eth index, which is b print(practice) #original list minus b #you could also make it a range: del practice[1:3] #or del practice[:] #as always, the slice selects all elements UP TO, BUT NOT INCLUDING the second index (i.e. if you want to remove up for fourth element, specify 5) #if you know the element(s) you want to remove, but not the index, you can use the REMOVE method #however, remove method only takes one argument practice = ["a", "b", "c", "d"] practice.remove("c") print(practice)
#finding largest and smallest values in a set #find the largest value largest = None for i in [3, 41, 12, 9, 74, 15]: if largest is None or i >= largest: #if the largest variable has no value, OR if whatever is in there is greater than or equal to what is encountered in the set... largest = i #replace it! print("Loop iteration:", i, largest) print("The largest number in the set is: ", largest) #find the smallest value smallest = None for i in [3, 41, 12, 9, 74, 15]: if smallest is None or i <= smallest: smallest = i print("Loop iteration:", i, smallest) print("The smallest number in the set is: ", smallest) #try combining them largest_2 = None smallest_2 = None for i in [3, 41, 12, 9, 74, 15]: if largest_2 is None or i >= largest_2: largest_2 = i if smallest_2 is None or i <= smallest_2: smallest_2 = i print("The REAL largest number in the set is: ", largest_2) print("The REAL smallest number in the set is: ", smallest_2) #the above code works, showing that you can use the same iteration variable several times in a sequence #turning the above into functions: def largest_value(values): #sets up to inject set of values into the function largest = None for i in values: if largest is None or i >= largest: largest = i return largest #determines what output of the function should be...leave printed text out here and specify that in later output #test the above: test_set = [100, 1000, 2000, 37, 6000] print("The largest number in the test set is:", largest_value(test_set)) print("The largest number in the test set is:", max(test_set)) #should be same as above
# by LCCL Coding Academy, www.LccLcoding.com # for Shopee Code League 2020 print() # List of prime numbers def is_prime(n): for i in range(2, n): if n % i == 0: return None return n >= 2 primes = [x for x in range(2, 100) if is_prime(x)] print('Prime numbers between 0 and 100: ') print(primes) # Sum of prime numbers print('\nSum:') print(sum(primes)) # Digit sums def digit_sum(n): while n > 9: n = sum([int(i) for i in str(n)]) return n print('\nDigit Sums:') print(list(map(digit_sum, primes))) # String all numbers print('\nString of primes:') print(''.join(str(n) for n in primes)) print()
from triangle import Triangle class TriangulatedFigure: # Class Invariant 1: Every triangle in self.triangles has # a unique set of vertices [Note 1 (at end)] # Class Invariant 2: len(self.triangles) < 2 --XOR-- # Every Triangle in self.triangles shares two get_points with another def __init__(self): self.triangles = [] # the Triangle objects that make up self def add(self, a_triangle): # Precondition 1: a_triangle is a Triangle instance # Precondition 2: len(self.triangles) < 2 # --XOR-- # a_triangle ... is not in self.triangles AND # ... shares two vertices with a Triangle in old(self.triangles) # Postcondition: a_triangle is in self.triangles if (len(self.triangles) < 2 or (a_triangle not in self.triangles) and not ( len(self.triangles) < 2 and (a_triangle not in self.triangles))): ## satisfying the condition first self.triangles.append(a_triangle)## adding the value to the list def get_points(self): triangles_points = [] for triangle in self.triangles: triangles_points.extend(triangle.get_points())## attaching by extending the value to traingles.points return set(triangles_points) def to_string(self): for current_triangle in self.triangles: print(current_triangle.to_string()) def triangles_with_vertex(self, a_point): # Precondition: At least one triangle in self.triangles contains a_point # Returns the (contiguous) list of self.triangles containing a_point # in clockwise order # Example: URL1 (see at end) # [Collected]: triangles_with_a_point = # the triangles in self.triangles containing a_point [Note 3] triangles_with_a_point = [] for triangles_point in self.triangles: i = triangles_point.get_angles() j=0 while(j>len(triangles_with_a_point)): ## if i[j] == a_point: triangles_with_a_point.append(triangles_point) ##attaching every element in the list triangles_in_order = self.triangles j+=1 #triangles_with_a_point = sorted(triangles_with_a_point, key=int) return triangles_with_a_point
import sys def read_file(textfile): f=open(textfile,'r') next(f) i=0 j=0 matrix=[[0 for x in range(9)] for y in range(9)] while True: j=0 char=f.readline() for c in char: matrix[i][j]=int(c) j=j+1 if j==9: i=i+1 break if i==9: break return matrix def check_soduku(row,column,number,matrix_board): check=0 for i in range(0,9): if matrix_board[row][i]==number: check=1 for i in range(0,9): if matrix_board[i][column]==number: check=1 row=row-row%3 column=column-column%3 for i in range(0,3): for j in range(0,3): if matrix_board[row+i][column+j]==number: check=1 if check==1: return False else: return True class calls: number_of_calls=0 c=calls() def sudoku_solver(matrix): c.number_of_calls=c.number_of_calls+1 break_condition=0 checking_range=[] for i in range(0,9): for j in range(0,9): if matrix[i][j]==0: break_condition=1 temp=[] temp.append([i,j]) temp_2=[] for num in range(0,10): if check_soduku(i,j,num,matrix): temp_2.append(num) temp.append(len(temp_2)) checking_range.append(temp) if break_condition==0: print("Smart Backtracking Algorithm MRV Solution: ") for i in matrix: print(i) print("Amount of Recursions: ") print(c.number_of_calls) exit(0) minimum_range_selection=checking_range[0][0] low=checking_range[0][1] for i in range(0,len(checking_range)): if checking_range[i][1]<low: low=checking_range[i][1] minimum_range_selection=checking_range[i][0] row=minimum_range_selection[0] column=minimum_range_selection[1] for i in range(0,10): if check_soduku(row,column,i,matrix): matrix[row][column]=i if sudoku_solver(matrix): return True matrix[row][column]=0 return False matrix=read_file(sys.argv[1]) sudoku_solver(matrix)
def count(n): while n > 0: print('befour=%d',n) yield n # 生成值: n n -= 1 print('after=%d',n) c = count(5) c.__next__() c.__next__()
a= input('Please enter a string ') def most_frequent(str): d = dict() for b in str: if b not in d: d[b] = 1 else: d[b] += 1 return d print (most_frequent(a))
#Hangman import sys from sys import argv name, answer = argv words = answer.lower().replace(".", "").replace("'", "").split() print "" # Generates the list of all unique letters list_letters = [] for x in range(0, len(words)): z = 0 word_in_letters = list(words[x]) while z < len(word_in_letters): if word_in_letters[z] in list_letters: z += 1 else: list_letters.append(word_in_letters[z]) z += 1 hang_count = 10 #Interact with user, while there are still unguessed letters while len(list_letters) > 0: if hang_count < 1: print "You lose!" sys.exit(1) # Prints the line, where _ indicates an unguessed letter h = 0 for i in range(0, len(words)): this_word = words[h] g = 0 while g < len(this_word): if this_word[g] in list_letters: print "_", else: print this_word[g], g += 1 h += 1 print " ", #User input - checks if the letter is still in the "available" list print "" usr = raw_input("> ") if usr in list_letters: print "OK, %s." % usr list_letters.remove(usr) elif len(usr) > 1: print "Only one letter at a time, please!" else: hang_count -= 1 print "Wrong! Only %d more chances!" % hang_count print "Congratulations, you win!" """ Takes phrase, splits into words, then into letters. Adds all letters to a list. Checks if a letter is in the list. If yes, remove. If no, error. NEXT: print phrase with missing letters as _ """ #Attempted to split words into letters using classes - didnt work, used a list instead #class Letters(object): # instances = [] # all_letters = [] # def __init__(self, word): # self.word = word # self.instances.append(self) # def printing(self): # print self.word # def split(self): # self.wordsplit = list(self.word) # return self.wordsplit # all_letters.append(self.wordsplit.items()) # #objs = list() #for i in range(3): # objs.append(Letters(words[i])) #word1 = Letters(words[0]) #word2 = Letters(words[1]) #word3 = Letters(words[2]) #word1.printing() # for loop to create objs #objs = list() #for x in range(0, len(words)): # objs.append(Letters(words[x])) #print objs ### #def letters(): # for x in range(0, len(words)): # letter.append = list(words[x]) #letters() #print letter
import os.path file_1 = input("Enter 1st FileName:") file_2 = input("Enter 2nd FileName:") if(not os.path.isfile(file_1) and not os.path.isfile(file_2)): print("File1 & File2 Doesn't Exist") exit() if(not os.path.isfile(file_1)): print("File1 Doesn't Exist") exit() if (not os.path.isfile(file_2)): print("File2 Doesn't Exist") exit() fp1 = open(file_1, 'r') fp2 = open(file_2, 'r') if (fp1.read() == fp2.read()): print("The contents of files are same") else: print("The contents of files are NOT same") fp1.close() fp2.close()
n = int(input("Enter Number:")) i = 1 fact = 1 while (i != n+1): fact = fact * i i = i + 1 print("The factorial of " + str(n) + " is " + str(fact))
def max_toys(prices, k): prices.sort() purchase_count = 0 total_so_far = 0 ​ for toy_price in prices: total_so_far += toy_price if k >= total_so_far: purchase_count += 1 else: return purchase_count ##second solution
#!/usr/bin/env/ python3 #-*- coding: utf-8 -*- class Dict(dict): def __init__(self, **kw):#这一行没什么用 super(Dict, self).__init__(**kw) def __getattr__(self, key): try: return self[key]#self.key调用出来的是self[key]的value, key不是dict的属性 except KeyError as e: raise AttributeError(r"'Dict' 中object has no attribute '%s'(%s)" % (key, e)) def __setattr__(self, key, value): self[key] = value#把设置的属性添加到字典
def backtracking(idx, order, c, arr): # arr 채우기 arr += order[idx] # 다 채웠는지 판단 if len(arr) == c: if arr not in cases[c].keys(): cases[c][arr] = 0 cases[c][arr] += 1 return # 다음 백트래킹 for i in range(idx+1, len(order)): backtracking(i, order, c, arr) def solution(orders, course): answer = [] global cases cases = {} for c in course: cases[c] = {} # 순열 만들기 for order in orders: for c in course: if len(orders) >= c: for i in range(len(order)-c): backtracking(i, order, c, "") print(cases) # 각 코스요리 뽑아내기 for c in course: max_cnt = 0 max_cnt_keys = [] for k in cases[c].keys(): if cases[c][k] > max_cnt: max_cnt = cases[c][k] max_cnt_keys = [k] elif cases[c][k] == max_cnt: max_cnt_keys.append(k) answer.append(max_cnt_keys) print(sum(sorted(answer), [])) return sum(sorted(answer), []) examples = [ [["ABCFG", "AC", "CDE", "ACDE", "BCFG", "ACDEH"], [2,3,4], ["AC", "ACDE", "BCFG", "CDE"]], [["ABCDE", "AB", "CD", "ADE", "XYZ", "XYZ", "ACD"], [2,3,5], ["ACD", "AD", "ADE", "CD", "XYZ"]], [["XYZ", "XWY", "WXA"], [2,3,4], ["WX", "XY"]] ] for orders, course, result in examples: print(solution(orders, course) == result)
from collections import deque def solution(priorities, location): # 인쇄 대기 목록 큐 q = deque() for i in range(len(priorities)): q.append((i, priorities[i])) # 중요도 배열 weights = sorted(priorities, reverse=True) # 프린트 cnt = 0 while q: idx, p = q.popleft() if p == weights[0]: cnt += 1 weights.pop(0) if idx == location: return cnt else: q.append((idx, p)) ex = [ ([2, 1, 3, 2], 2, 1), ([1, 1, 9, 1, 1, 1], 0, 5) ] for p, l, r in ex: print(solution(p, l))
def find_lowest_cost_node(costs): lowest_cost = float("inf") lowest_cost_node = None for node in costs: cost = costs[node] if cost < lowest_cost and node not in processed: lowest_cost = cost lowest_cost_node = node return lowest_cost_node # 그래프 그리기 graph = {} graph["start"] = {} graph["start"]["a"] = 6 graph["start"]["b"] = 2 graph["a"] = {} graph["a"]["fin"] = 1 graph["b"] = {} graph["b"]["a"] = 3 graph["b"]["fin"] = 5 graph["fin"] = {} # 가격 해시테이블 infinity = float("inf") # 무한 (가격을 모르는 정점) costs = {} costs["a"] = 6 costs["b"] = 2 costs["fin"] = infinity # (확정 경로의) 부모 해시테이블 parents = {} parents["a"] = "start" parents["b"] = "start" parents["fin"] = None # 이미 처리한 정점 저장 processed = [] # 1. 가장 가격이 싼 정점을 찾는다. node = find_lowest_cost_node(costs) while node is not None: # 처리하지 않은 정점이 남아있는동안 cost = costs[node] neighbors = graph[node] # 2. 이웃 정점의 가격을 갱신한다. for n in neighbors.keys(): # 이 노드의 모든 이웃에 대하여 new_cost = cost + neighbors[n] if costs[n] > new_cost: # 가격이 더 싸면 '확정' # 3. 만약 이웃 정점의 가격을 갱신하면 부모도 갱신한다. costs[n] = new_cost parents[n] = node # 4. 해당 정점을 처리했다는 사실을 기록한다. processed.append(node) node = find_lowest_cost_node(costs) print(costs["fin"]) n = parents["fin"] print("fin") while n is not "start": print(n) n = parents[n] print("start")
str1 = "helloworldsohee" str2 = "hesworldllo" # 격자 만들기 dp = [[-1] * len(str1) for _ in range(len(str2))] for row in range(len(str2)): for column in range(len(str1)): if str1[column] != str2[row]: dp[row][column] = 0 continue else: if 0 <= row-1 < len(str2) and 0 <= column-1 < len(str1): dp[row][column] = dp[row - 1][column - 1] + 1 else: dp[row][column] = 1 print(dp) max = 0 for row in dp: for cell in row: if max < cell: max = cell print(max)
""" Create a mosaic image from a target image and source images. The sequence is: 1. Load a target image. This is the "big picture" which will be made up of smaller source images. 2. Divide the target image into squares with an edge of n pixels where n is the edge-length of the source images. 3. Iterate over these squares, calculating the average RGB value, selecting the source image with the closest RGB value and pasting that source image into the target image square. """ import math, json, time from pathlib import Path from PIL import Image import settings from settings import FILEPATHS from pyzantine.file_ops import read_file def calculate_euclidean_distance(square, source_image): """ Calculate the difference in average RGB values between two images. See https://en.wikipedia.org/wiki/Color_difference#sRGB """ per_channel_differences = [] for channel in zip(square, source_image): channel_difference = int(channel[1]) - int(channel[0]) per_channel_differences.append(channel_difference ** 2) return sum(per_channel_differences) def find_nearest_euclidean_distance(square): """ Work through the images listed in source_images.json. Return the path to the source image with the smallest Euclidean distance to the supplied square of the input image """ with open(FILEPATHS["source_images_data"]) as fin: source_images = json.loads(fin.read()) nearest_match = None for file, average_colour in source_images.items(): if file == "meta": # ignore the metadata section of the file continue if not nearest_match: # First iteration closest_distance = calculate_euclidean_distance(square, average_colour) nearest_match = file else: distance = calculate_euclidean_distance(square, average_colour) if distance < closest_distance: closest_distance = distance nearest_match = file return nearest_match def move_right(window, edge): new_window = [ window[0] + edge, window[1], window[2] + edge, window[3], ] return new_window def move_to_start_of_next_row(window, edge): new_window = [ 0, window[1] + edge, edge, window[3] + edge, ] return new_window def calculate_average_colour(region): pixels = region.getdata() red = int(sum([x[0] for x in pixels]) / len(pixels)) green = int(sum([x[1] for x in pixels]) / len(pixels)) blue = int(sum([x[2] for x in pixels]) / len(pixels)) return (red, green, blue) def calculate_number_of_source_images(img: Image.Image) -> tuple: """ Works out how many source images are needed to cover the target image. Takes the size of the source images from settings.py and gets the size of the target image directly from the image object properties. """ img_width = img.size[0] img_height = img.size[1] source_images_width = int(math.ceil(img_width / settings.SOURCE_IMAGE_WIDTH_HEIGHT)) source_images_height = int( math.ceil(img_height / settings.SOURCE_IMAGE_WIDTH_HEIGHT) ) return source_images_width, source_images_height def main(): start = time.perf_counter() window = initialise_window() # Open target image i.e. the "big picture" that will be recreated in small source images. input_img = read_file(FILEPATHS["test_image"]) # Calculate how many source images we need to cover the target image source_images_width, source_images_height = calculate_number_of_source_images( input_img ) # Uncomment the line below if the image needs to be rotated # input_img = input_img.transpose(Image.ROTATE_90) overwrite_target_squares_with_source_images( input_img, source_images_height, source_images_width, window ) end = time.perf_counter() elapsed = end - start print(f"finished in {elapsed} seconds") input_img.show() def overwrite_target_squares_with_source_images( input_img: Image.Image, source_images_height: int, source_images_width: int, window ) -> Image.Image: qty_analysed = 1 for i in range(source_images_height): # for j in range(source_images_width): # calculate average colour of square average_colour = calculate_average_colour(input_img.crop(window)) # get source image with closest match closest_image: str = find_nearest_euclidean_distance(average_colour) # paste source image over square this_source_image = Image.open(Path(closest_image)) # Source image and window are the same size, so let's reuse the window initialisation code. crop_area = initialise_window() paste_region = this_source_image.crop(crop_area) input_img.paste(paste_region, window) window = move_right(window, settings.SOURCE_IMAGE_WIDTH_HEIGHT) print(f"analysed {qty_analysed} squares") qty_analysed += 1 window = move_to_start_of_next_row(window, settings.SOURCE_IMAGE_WIDTH_HEIGHT) return input_img def initialise_window(): # Create the window that will define each square in the image. window = ( 0, 0, settings.SOURCE_IMAGE_WIDTH_HEIGHT, settings.SOURCE_IMAGE_WIDTH_HEIGHT, ) return window if __name__ == "__main__": main()
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import sklearn from sklearn import linear_model def prepare_country_stats(oecd_bli, gdp_per_capita): full_country_stats = pd.merge(left=oecd_bli, right=gdp_per_capita, left_index=True, right_index=True) full_country_stats.sort_values(by="GDP per capita", inplace=True) full_country_stats return full_country_stats #load the data oecd_bli = pd.read_csv("oecd_bli_2016.csv", thousands=',') oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"] oecd_bli = oecd_bli.pivot(index="Country", columns="Indicator", values="Value") gdp_per_capita = pd.read_csv("gdp_per_capita.csv", thousands=',', delimiter='\t', encoding='latin1', na_values="n/a") gdp_per_capita.rename(columns={"2015": "GDP per capita"}, inplace=True) gdp_per_capita.set_index("Country", inplace=True) gdp_per_capita.head(2) #prepare the data country_stats = prepare_country_stats(oecd_bli, gdp_per_capita) x = np.c_[country_stats["GDP per capita"]] y = np.c_[country_stats["Life satisfaction"]] #visualize the data country_stats.plot(kind='scatter', x='GDP per capita', y='Life satisfaction') #select a linear model prediction_model = sklearn.linear_model.LinearRegression() #train the model prediction_model.fit(x,y) t0, t1 = prediction_model.intercept_[0], prediction_model.coef_[0][0] plt.plot(x, t0 + t1*x, "b") #make a prediction for Cyprus X_new = [[22587]] #Cypru's GDP per capita Y_linear = prediction_model.predict(X_new) #use k_nearest neighor regression prediction_model = sklearn.neighbors.KNeighborsRegressor(n_neighbors=3) #train the model prediction_model.fit(x,y) #make a prediction for Cyprus Y_neighbor = prediction_model.predict(X_new) plt.plot(X_new, Y_linear, "gs") plt.plot(X_new, Y_neighbor, "rs") plt.annotate('Linear regression', xy=(X_new[0][0], Y_linear[0][0]), xytext=(X_new[0][0]-10000, Y_linear[0][0]+1), arrowprops = dict(facecolor='black', width=0.5, shrink=0.1, headwidth=5)) plt.annotate('K-neighbor regression', xy=(X_new[0][0], Y_neighbor[0][0]), xytext=(X_new[0][0], Y_neighbor[0][0]-0.8), arrowprops = dict(facecolor='black', width=0.5, shrink=0.1, headwidth=5)) plt.show()
import unittest #import the unittest module from user import User #import the user class class TestUser(unittest.TestCase): ''' Test class that defines test cases for the user class behaviours. Args: unittest.TestCase: TestCase class that helps in creating test cases. ''' # First test def setUp(self): #setup() creates new instances of the user class before each test method declared. it is called before invocation of the test. ''' Set up method to run before each test cases. ''' self.new_user = User("Maratah","Njoroge","1234r54","maratah7@gmail.com") # instance variable are stored here def test_init(self): #checks if objects are initialised correctly ''' test_init test case to test if the object is initialized properly ''' #check for an expected result self.assertEqual(self.new_user.first_name,"Maratah") self.assertEqual(self.new_user.last_name,"Njoroge") self.assertEqual(self.new_user.password,"1234r54") self.assertEqual(self.new_user.email,"maratah7@gmail.com") #second test def test_save_user(self): ''' test_save_user test case to test if the contac object is saved into the contact list ''' self.new_user.save_user() #save new user self.assertEqual(len(User.user_list),1) #check length to confirm new addition to the user list #third test def test_save_multiple_user(self): ''' test_save_multiple_user checks if we can save multiple user info to our user list ''' self.new_user.save_user() test_user = User("Test","user","123456723","test@user.com") test_user.save_user() self.assertEqual(len(User.user_list),2) def tearDown(self): #called after invocation of each test method ''' tearDown method that does clean up after each test case has run. ''' User.user_list = [] #to get accurate test results every time a new test case #forth test def test_delete_user(self): ''' test_delete_user to test if we can remove a user from the user list. ''' self.new_user.save_user() test_user= User("Test", "user","123456778", "test@user.com") test_user.save_user() self.assertEqual(len(User.user_list),1) #fifth test def test_find_user_by_name(self): ''' test to check if we can find a user by their name and display the info. ''' self.new_user.save_user() test_user= User("Test","user","1235t6","test@user.com") test_user.save_user() found_user = User.find_by_name("User") self.assertEqual(found_user.email,test_user.email) def test_user_exists(self): ''' test to check if we can return a Boolean if we cannot find the user. ''' self.new_user.save_user() test_user = User("Test","user","0711223344","test@user.com") # new contact test_user.save_user() user_exists = User.user_exist("0711223344") self.assertTrue(user_exists) #checks if the return value is true def test_display_all_user(self): ''' Method that returns a list of all users saved ''' self.assertEqual(User.display_users(),User.user_list) if __name__ == '__main__': #confirm that anything inside the if block should run only if the file is being run unittest.main() #command line interface
#!/usr/bin/python import time def twiddle_bool(it,a,q): print "child started" while True : print "Itteration %d" % it.value it.value = it.value +1 time.sleep(1) any = False for i in range(len(a)): any = any or a[i] for i in range((len(a)-1), 0, -1): a[i] = a[i-1] a[0] = not any if(not any) : q.put(it.value) q.put("this") q.put("is a") q.put("test")
# -*- coding:utf8 -*- # 生成九九乘法表 # 初始化表格为空 table = '' for i in range(1, 10): for j in range(1, 10): if i < j: continue table += '{} * {} = {}\t'.format(j, i, i * j) # 边界情况下换行 if i == j: table += '\n' print(table)
# -*- coding:utf8 -*- # 1. 列出所有人列表,并用3中方式打印信息 yanXiPalace = '延禧宫' yuGarden = '御花园' partyPlace = yanXiPalace invitees = ['太后', '皇后', '纯妃', '小嘉嫔', '舒妃', '皇上'] print('春节将至,请大家过来%s相聚,受邀名单:%s' % (partyPlace, invitees)) print('春节将至,请大家过来{}相聚,受邀名单:{}'.format(partyPlace, invitees)) print(f'春节将至,请大家过来{partyPlace}相聚,受邀名单:{invitees}') # 2. 小嘉嫔拒绝邀请,并打印不能参加的人 refusedPerson = invitees.pop(3) print('{}拒绝参加'.format(refusedPerson)) # 3. 尔晴参加,重新修改列表,打印出邀请名单 invitees.append('尔晴') print(invitees) # 4. 地点从延禧宫变成御花园 partyPlace = yuGarden # 5. insert方法将`哥哥`放在邀请名单的开头;append方法将`傅恒`放在名单最后 invitees.insert(0, '哥哥') invitees.append('傅恒') # 5.1 重新打印所有人名单,并用len方法打印邀请人数,并复制一个新的列表作为备份 print(invitees) print('受邀人数:{}'.format(len(invitees))) inviteesBak = invitees.copy() # 6. 打印前、后三个人名,并颠倒顺序 print('前3个人:{}'.format(invitees[:3])) print('后3个人:{}'.format(invitees[-3:])) invitees.reverse() print(invitees) # 7. 只请皇后和尔晴,告知依然在受邀之列 # 8. 删除多于人员,并告知“特别遗憾不能请大家吃饭” excess = list() excess.append(invitees.pop(0)) excess.append(invitees.pop(1)) excess.append(invitees.pop(1)) excess.append(invitees.pop(1)) excess.append(invitees.pop(2)) excess.append(invitees.pop(2)) print('依然在邀请之列:{}'.format(invitees)) print('特别遗憾不能邀请大家吃饭:{}'.format(excess)) # 9. del删除名单 del invitees
class Solution(object): def findCircleNum(self, M): def dfs(M, visited, col): for row in range(len(M)): # if there is a friendship and if friend has not already been added to circle if M[col][row] == 1 and visited[row] == 0: visited[row] = 1 dfs(M, visited, row) # else it is no longer in the same circle of friends, so exit """ :type M: List[List[int]] # adjacency matrix :rtype: int """ visited = [0] * len(M) #create an array of zeros count = 0; for col in range(len(M)): #for every friend if (visited[col] == 0): #if not yet visited dfs(M, visited, col) count += 1 return count def stringToInt2dArray(input): return json.loads(input) def intToString(input): if input is None: input = 0 return str(input) def main(): import sys def readlines(): for line in sys.stdin: yield line.strip('\n') lines = readlines() while True: try: line = lines.next() M = stringToInt2dArray(line) ret = Solution().findCircleNum(M) out = intToString(ret) print out except StopIteration: break if __name__ == '__main__': main()
# Count the number of vowels in a String # Bonus - report a sum of each vowel def is_vowel(char): if ((char == 'a') or (char == 'e') or (char == 'i') or (char == 'o') or (char == 'u')): return True else: return False vowelCount = 0 vowels = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0} inputStr = input('Enter a string... ') while (inputStr != ''): for letter in inputStr: if(is_vowel(letter)): vowelCount = vowelCount + 1 vowels[letter] = vowels[letter] + 1 print('There are {} vowels'.format(vowelCount)) for vowel in vowels: print('There were {} {}'.format(vowels[vowel],vowel)) inputStr = input('Enter another string... ')
from p5 import * x,y = width/2,height/2 import random import math l=[] #radius of the circle radius=350 golden_ratio = 0.61803 n=int(input('enter the no of vertices')) center_x,center_y= width/2+200,height/2+200 angle = 2*math.pi/n #to store the points of the vertices generated for i in range(1,n+1): l.append([center_x+math.sin(angle*i)*radius,center_y+math.cos(angle*i)*radius]) print(l) def setup(): #this is the function for the window size setting and also the back_ground color size(800,800) no_stroke() background(0) def draw(): global x global y global l global golden_ratio fill(255,0,0) for i in l: circle(tuple(i),10) #here we generate a random selection of the points of the generated vertices newx,newy=tuple(random.choice(l)) x,y=(1-golden_ratio )*x+(newx)*golden_ratio ,(1-golden_ratio )*y+(newy)*golden_ratio #we move to that point and we make a circle of size 3 and we will repeat this procedure fill(255,0,0) circle((x,y),3) run()
""" Class controlling car """ import random class Car(): """ Represent a car """ model1 = """ {pos}.-'--`-._ {pos}'-O---O--' """ model2 = r""" {pos} __ {pos} _| =\__ {pos}/o____o_\ """ model3 = r""" {pos} ______ {pos} /|_||_\`.__ {pos}( _ _ _\ {pos}=`-(_)--(_)-' """ model4 = """ {pos} .--. {pos}.----' '--. {pos}'-()-----()-' """ wheels = 4 car_count = 0 def __init__(self, model, price, driver): """ Constructor - Gentlemen, start your engines """ self.model = model self.driver = driver self._price = price self._speed = random.uniform(0.5, 2) self._position = 0 Car.car_count += 1 @classmethod def create_from_json(cls, json_data): """ Get data from json-file """ return cls(json_data["model"], json_data["price"], json_data["driver"]) def present_car(self): """ Reveal car facts """ return "{d} with the car {m}. The car costs {p}$.".format( m=self.model, p=self._price, d=self.driver ) def get_price(self): """ What does this car cost? """ return self._price def get_model(self): """ What model is this car? """ spaces = " " * round(self._position) return getattr(self, self.model).format(pos=spaces) def set_price(self, new_price): """ Set the pricetag on the car """ if float(new_price) / float(self._price) > 0.7: self._price = new_price return "New price is " + str(self._price) return "New price is too low. You can lower it with 30% max." def move_cars(self): """ Start the race """ for car in self.car_count: print(car.get_model()) def move(self): """ The race itself""" self._position += random.uniform(0.5, 2.5) + self._speed def get_pos(self): """ Did we win?""" return self._position def __add__(self, other): """ Overload + """ return self._price + other.get_price() def __iadd__(self, other): """ Overload += """ self._price += other.get_price() return self @classmethod def wheel_message(cls): """ Available outside the class """ print("A car normally have {nr} wheels".format(nr=cls.wheels)) # bmw = Car("BMW", 100000) # volvo = Car("Volvo", 150000) # print(bmw.model) # # print(volvo.model) # # print(bmw.wheels)
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Tests for custom data structures """ # Gör tester # Ta bort första sista och mitt i länkad lista import unittest from unorderedlist import UnorderedList from error import KeyErr, ValErr, ListEmpty class TestLists(unittest.TestCase): """ Test class for lists """ @classmethod def setUp(cls): cls.ul = UnorderedList() cls.ul.append(5) cls.ul.append(7) cls.ul.append(9) cls.ul.append(7) cls.ul.append(6) cls.ul.append("Last one") def test_erase(self): """ Try erasing list """ self.ul.erase() with self.assertRaises(ListEmpty): self.ul.search(7) with self.assertRaises(ListEmpty): self.ul.print_list() def test_erase_empty(self): """ Erase an empty list """ self.ul.erase() with self.assertRaises(ListEmpty): self.ul.erase() def test_delete_index(self): """ Delete single element, check return value """ self.assertEqual(9, self.ul.remove_index(2)) def test_delete_first(self): """ Try deleting first node in list """ self.assertEqual(5, self.ul.remove_index(0)) def test_delete_last(self): """ Try deleting last node in list """ self.assertEqual("Last one", self.ul.remove_index(5)) def test_delete_nonexistent(self): """ Delete a nonexistent node """ with self.assertRaises(IndexError): self.ul.remove_index(22) def test_remove_value(self): """ Delete value """ # Returns number of deleted items. self.assertEqual(2, self.ul.remove_value(7)) def test_search(self): """ Quick test search """ self.assertEqual(2, self.ul.search(9)) with self.assertRaises(ValErr): self.ul.search(13) def test_get(self): """ Get value at index """ self.assertEqual(7, self.ul.get(3)) with self.assertRaises(KeyErr): self.ul.get(13) if __name__ == "__main__": unittest.main()
# your code goes here f=1 n=int(input()) for i in range(1,n+1): f=f*i print(f)
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements # Your code here new_list = arrA + arrB for i in range(elements): mini = min(new_list) merged_arr[i] = mini new_list.remove(mini) print(merged_arr) return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # Your code here # need to split in half in half in half until head = 0 tail = len(arr)-1 mid = (head+tail)//2 return arr # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input # def merge_in_place(arr, start, mid, end): # # Your code here # def merge_sort_in_place(arr, l, r): # # Your code here merge([3, 10, 4], [9, 2, 19]) merge_sort([1, 45, 3, 2, 56, 23])
#code to find the next empty grid def nextCell(grid): for x in range(9): for y in range(9): if grid[x][y] == 0: return x, y return -1, -1 #code to check if row is possible def row_check(grid, row, num): for x in range(9): if grid[row][x] == num: return False return True #code to check if column is possible def col_check(grid, col, num): for x in range(9): if grid[x][col] == num: return False return True #code to check if grid is possible def grid_check(grid, row, col, num): for i in range(row, row + 3): for j in range(col, col + 3): if grid[i][j] == num: return False return True #to print def print_grid(grid): for i in range(9): for j in range(9): print(grid[i][j], end = " ") print("") #solving function def solve_sudoku(grid): i, j = nextCell(grid) if i == -1: return True for num in range(1, 10): if row_check(grid, i, num) and col_check(grid, j, num) and grid_check(grid, i - i%3, j - j%3, num): grid[i][j] = num if solve_sudoku(grid): return True grid[i][j] = 0 return False #code to test, grid is hard coded grid=[[3,0,5,4,2,0,8,1,0], [4,8,7,9,0,1,5,0,6], [0,2,9,0,5,6,3,7,4], [8,5,0,7,9,3,0,4,1], [6,1,3,2,0,8,9,5,7], [0,7,4,0,6,5,2,8,0], [0,0,0,0,0,0,0,0,0], [5,0,8,6,7,0,1,9,2], [0,9,6,5,1,2,4,0,8]] if(solve_sudoku(grid)): print_grid(grid) else: print("No grid found")
#This is the 10th program in 99 programs in Python #This is extension of the last program, instead of storing the complete list your store the element and its size #superList2 is the working function def superList2(list): lastEl = None count = 0 finList = [] for i in list: if i == lastEl: count += 1 else: if count != 0: finList.append((count, lastEl)) count = 0 count = 1 lastEl = i finList.append((count, lastEl)) return finList #test code, list is hard coded list1 = ["a", "a", "a", "b", "b", "c", "c", "a"] finList = superList2(list1) print("Super list = " + str(finList))
#This is the 14th program in 99 programs in Python #This creates a duplicate of each element in the list #working function duplicate_it def duplicate_it(list): finList = [] for i in list: finList.append(i) finList.append(i) return finList #test code, list is hard coded list1 = ["a", "c", "e", "p"] finList = duplicate_it(list1) print(finList)
# https://www.acmicpc.net/problem/7490 import sys import copy def solution(array, n): if len(array) == n: operators_list.append(copy.deepcopy(array)) return array.append(' ') solution(array, n) array.pop() array.append('+') solution(array, n) array.pop() array.append('-') solution(array, n) array.pop() test_case = int(sys.stdin.readline()) for _ in range(test_case): operators_list = [] n = int(sys.stdin.readline()) solution([], n-1) integers = [i for i in range(1, n+1)] for operators in operators_list: string = "" for i in range(n-1): string += str(integers[i]) + operators[i] string += str(integers[-1]) if eval(string.replace(' ', '')) == 0: print(string) print()
# https://www.acmicpc.net/problem/11720 def main(): number = int(input()) num_for_cal = input() result = 0 for i in range(number): result += int(num_for_cal[i]) print(result) if __name__ == "__main__": main()
import numpy as np from sklearn.metrics import r2_score def helloworld(): #print("Hello, world!") print("uncomment me") return def simple_linear_regression(x, y): """ Implement simple linear regression below y: list of dependent variables x: list of independent variables return: b1- slope, b0- intercept """ y_mean = np.mean(y) x_mean = np.mean(x) b1 = sum(\ (x[i][0] - x_mean) * (y[i] - y_mean) \ for i in range(len(x)) ) / sum((x[i][0] - x_mean)**2 for i in range(len(x))) b0 = y_mean - b1*x_mean return b1, b0 def multiple_regression(x, y): """ x: np array of shape (n, p) where n is the number of samples and p is the number of features. y: np array of shape (n, ) where n is the number of samples return b: np array of shape (n, ) """ # Need to add a column as the first column to get b0. x.insert(loc=0, column='B0', value=np.ones(shape=x.shape[0]).reshape(-1,1)) x_transpose = x.transpose() t = x_transpose.dot(x) _inverse = np.linalg.pinv(t.values) b = _inverse.dot(x_transpose).dot(y) return b def predict(x, b): """ This function would allow us to perform predictions. As we are performing linear regression we need to consider the b0 value as well. This can be achieved by using the beta values and the first beta value which is b0 is what we would use here. """ if len(b) < 2: return b0, b_coeff = b[0], b[1:] # Multiply all the beta_coeffecients with their respective columns. x *= b_coeff # Compute the sum of each row and also add the b0 which we had segregated earlier. yhat = x.sum(axis=1) yhat += b0 return yhat def calculate_r2(y, yhat): # y: np array of shape (n,) where n is the number of samples # yhat: np array of shape (n,) where n is the number of samples # yhat is calculated by predict() # calculate the residual sum of squares (rss) and total sum of squares (tss) rss = sum((y[i] - yhat[i])**2 for i in range(len(y))) y_mean = np.mean(y) tss = sum((y[i] - y_mean)**2 for i in range(len(y))) r2 = 1.0 - rss/tss return r2 def calculate_adjusted_r2(y, yhat, num_of_features): r2 = calculate_r2(y, yhat) num_samples = len(y) return (1 - ((1-r2)*(num_samples-1)/(num_samples-1-num_of_features))) def check_r2(y, yhat): return np.allclose(calculate_r2(y, yhat), r2_score(y, yhat))
def add(value1, value2): return value1 + value2 def sub(value1, value2): return value1 - value2 def mul(value1, value2): return value1 * value2 def div(value1, value2): return value1 / value2
try: x1 = float(input()) y1 = float(input()) x2 = float(input()) y2 = float(input()) print("Unsuccessful typification") except ValueError as e: print("Unsuccessful typification: __ ", e) except ZeroDivisionError: print("Trying to devide by zero") except Exception: print("Common exception") def distance(x1, y1, x2, y2): return (((x2-x1)**2 + (y2-y1)**2) ** 0.5) print (distance(x1, y1, x2, y2))
import sys from collections import Counter class Task2d: def __init__(self): self.n = 0 self.x = set() self.line = set() def fill_x_list(self): for i in range(self.n-1): self.x.add(str(i+1)) def set_included_values(self): buf1 = set() # (self.x & self.line) buf1.update(self.x & self.line) self.x.clear() self.x.update(buf1) print(sorted(list(self.x))) def set_excluded_values(self): buf1 = set() # print(self.x - self.line) buf1.update(self.x - self.line) self.x.clear() self.x.update(buf1) print(sorted(list(self.x))) if __name__ == '__main__': my_task = Task2d() print("This is task 2d:") print("Enter range") my_task.n = int(input()) my_task.fill_x_list() print("Enter numbers") buf = input() while(buf.lower()!="end"): my_task.line = set(buf.split()) # print("Size of splited items") # print(len(my_task.line)) print("Enter The Answer") buf_ans = input() if buf_ans.lower() == "yes": my_task.set_included_values() elif buf_ans.lower() == "no": my_task.set_excluded_values() print("Enter numbers") buf = input() print(sorted(list(my_task.x))) input() sys.exit(1)
def union(P,Q) : R = [] for i in range(0,len(P)) : R.insert(i,P[i]) length = len(str(R)) for j in range(0,len(Q)) : if Q[j] not in R : R.insert(length,Q[j]) length = length + 1 return R def difference(P,Q) : #elements of P which are not in Q R = [] #R = P - Q for i in range(0,len(P)) : if P[i] not in Q : R.insert(i,P[i]) return R def is_subset(P,Q) : check = True #to check if P is a subset of Q for i in range(0,len(P)) : if P[i] not in Q : check = False return check def powerset(P) : R = [] length = len(P) lenpow = 2**length #total number of powersets counter = 0 i = 0 for counter in range(0,lenpow) : print("[",end="") for i in range(0,length) : if ((counter & (1 << i))>0) : print(P[i],end=",",) print("]") def symmetric_difference(P,Q) : R = [] #symmetric difference (P-Q union Q-P) G = [] #P-Q S = [] #Q-P if len(Q) > len(P) : for i in range(0,len(P)) : if P[i] not in Q : G.insert(i,P[i]) R.insert(i,P[i]) #first inserting P-Q for i in range(0,len(Q)) : if Q[i] not in P : S.insert(i,Q[i]) length = len(R) length = length + len(S) for i in range(len(S)-1,length) : R.insert(i,S[i-len(S)]) #inserting Q-P return R elif len(P) > len(Q) : for i in range(0,len(Q)) : if Q[i] not in P : S.insert(i,Q[i]) R.insert(i,Q[i]) #first inserting P-Q for i in range(0,len(P)) : if P[i] not in Q : G.insert(i,P[i]) length = len(R) length = length + len(G) for i in range(len(G),length) : R.insert(i,G[i-len(G-1)]) #inserting Q-P return R else : length = len(P)*2 for i in range(0,len(P)) : if P[i] not in Q : R.insert(i,P[i]) for i in range(len(P),length) : if Q[i-len(Q)] not in P : R.insert(i,Q[i-len(Q)]) return R Set1 = [] Set2 = [] S1 = input("Enter Set 1 : ") Set1 = S1.split() S2 = input("Enter Set 2 : ") Set2 = S2.split() print("Set 1 : ",end ="") print(Set1) print("Set 2 : ",end="") print(Set2) union = union(Set1,Set2) print("\nUnion : ",end='') print(union) diff = difference(Set1,Set2) print("\nP - Q : ",end='') print(diff) value = is_subset(Set1, Set2) if (value == True) : print("\nP is a subset of Q") else : print("\nP is not a subset of Q") print("\nPowerset of P : ") powerset(Set1) symdif = symmetric_difference(Set1,Set2) print("\nSymmteric Difference : ",end='') print(symdif)
def add(x,y): a = x + y return a def subtract(x,y): s = x - y return s def multiply(x,y): m = x * y return m def divide(x,y): d = x / y return d x = int(input("Number 1 : ")) y = int(input("Number 2 : ")) print("\nCalculator : ") add = add(x,y) print("\nAddition : "+str(add)) sub = subtract(x,y) print("\nSubtraction : "+str(sub)) mul = multiply(x,y) print("\nMultiplication : "+str(mul)) div = divide(x,y) print("\nDivision : "+str(div))
i = 0 x = True trinum = 0 trinumbers = [] #to store which triange number it is while x == True : i = i + 1 trinum = trinum + i trinumbers.append(trinum) checkfac = trinum counter = 1 for y in range(2,checkfac+1) : if checkfac%y == 0 : counter = counter + 1 if counter == 500 : x = False break; if counter == 500 : ind = trinumbers.index(trinum) print("The Triangle Number containing over 500 divisors is : ") print(str(ind+1)) print(trinum)
numbers = [] for x in range(0,10) : num = int(input("Enter Number "+str(x+1)+" : ")) numbers.append(num) diff = numbers[0] - numbers[1] #finding the pair of numbers with least difference pair1 = 0 pair2 = 0 for y in range(0,9) : if (numbers[y]<numbers[y+1]) < diff : diff = numbers[y] - numbers [y+1] pair1 = numbers[y] pair2 = numbers[y+1] print("The pairs with least difference are : ") print(str(pair1)+" "+str(pair2))
def isPrime(num) : #to check if a number is prime or not if num < 2 : #for negative numbers and 0 and 1 return False else : root = num**0.5 root1 = int(root) prime = True for x in range(2,root1+1) : if(num%x==0) : prime = False if(prime==True) : return True else : return False maximum = 0 #to store maximum primes for a in range(-1001,1000) : for b in range(-1001,1000) : if isPrime(b): counter = 0 n = 0 while isPrime((n*n)+(a*n)+b) : counter = counter + 1 n = n + 1 if counter > maximum : maximum = counter A = a B = b print("The product of the coefficients a and b, that produce the maximum number of primes for consecutive values of n is : ") print(A*B)
array = [] for i in range(0,10) : num = float(input("Enter Number "+str(i+1)+" : ")) array.append(num) sumnum = 0 for i in range(0,10) : sumnum = sumnum + array[i] average = sumnum/10 print("Average of 10 floating point value is : "+str(average))