text
stringlengths
37
1.41M
# Create function that returns the average of an integer list def average_numbers(num_list): avg = sum(num_list)/float(len(num_list)) # divide by length of list return avg # Take the average of a list: my_avg my_avg = average_numbers([1, 2, 3, 4, 5, 6]) # Print out my_avg print(my_avg) -----------------------------...
# -*- coding: utf-8 -*- """ PS3 Itsaso Apezteguia """ import numpy as np import math import sympy from sympy import symbols from scipy.optimize import fsolve import scipy.optimize as sc import matplotlib.pyplot as plt """ Question 1: TRANSITIONS IN A REPRESENTATIVE AGENT ECONOMY """ ## a) COMPUTING T...
# -*- coding: utf-8 -*- """ Created on Wed Apr 25 14:01:19 2018 @author: urand Théophane """ import tkinter as tk p = 37 #Numéro du corps class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title("Courbes elliptiques") self.can = tk.Canvas(self, width = 600, heigh...
""" This function's main goal is to translate the coordinates of the mouse into what position of the chessboard the mouse is in This was a repetative implementation, there might (most likely) another way to implement this that is more effecient both in the run time, and the time it took to code IF YOU DON'T KNOW THE C...
import random from problem.problem_instance_properties import ProblemInstanceProperties from mutators.mutators import simple_mutator from crossovers.crossovers import single_point_crossover from selectors.selectors import tournament_selector class ProblemInstance: """ Class that represents an instantiated gen...
import matplotlib.pyplot as plt import numpy as np """Space Complexity""" # example def return_squares(n): square_list = [] for num in n: square_list.append(num * num) return square_list nums = [2, 4, 6, 8, 10] print(return_squares(nums)) """Worst vs Best Case Complexity""" # example # def ...
"""fibonacci via recursion""" def fibonacci(n): if n in (1, 2): return 1 return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(7)) # print(fibonacci(10)) # print(fibonacci(33)) """fibonacci via 'for' loop""" # fib1 = fib2 = 1 # n = int(input()) # # if n < 2: # quit() # # print(fib1, end=' ') ...
class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def insert_left(self, child_val): subtree = self.pop(1) if len(subtree) > 1: self.insert(1, [child_val, subtree, []]) else: self.insert(1, [chil...
# Advent of Code 2019 - day 4 import re def has_double_digit(num: int): return re.search(r'(\d)(?<!(?=\1)..)\1(?!\1)', str(num)) is not None def has_right_length(num: int, length: int=6): return len(str(num)) == length def has_no_decreasing_digits(num: int): return re.search(r'^1*2*3*4*5*6*7*8*9*$', str(...
import numpy as np import math as mt from functions import * class Curve: def get_dist(self, x=None, y=None): """ Returns ------- numpy array distances between consecutive points given by pairs of coordinates; the first value is 0 """ if x is None...
def bye_duplicate (): noki = input ("ENTER NUMBERS:") noki = list (noki) nok = [] for i in noki: if i not in nok: nok.append(i) print(nok) bye_duplicate()
""" This is the program for credit card manager. Author: Gurleen Kaur Date: 01-08-2021 """ transactions = [] months = { 0: "January", 1: "February", 2: "March", 3: "April", 4: "May", 5: "June", 6: "July", 7: "August", 8: "September", 9: "October", 10: "November", 11: "De...
#include<bits/stdc++.h> using namespace std; // Struct struct Node { int data; struct Node* next; }; /* Function to get the middle of the linked list*/ void printMiddle(struct Node *head) { struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && ...
import math import heapq def minimum_distance(n, x, y): result = 0 cost = {}; h = []; vertices = {} new_tree = {} for i in range(n): if i == 0: cost[i] = 0; else: cost[i] = float('inf'); heapq.heappush(h, (cost[i],i)); vertices[...
import Queue def distance(a, s, t): frontier = Queue.Queue() frontier.put(s) dist = {}; for i in range(len(adj)): dist[i]= float("inf") dist[s] = 0; while not frontier.empty(): u = frontier.get() if u==t: return dist[u]; else: neighb...
import sys with open(sys.argv[1], 'r') as f: for line in f: uniqueSet = set() print ','.join(str(item) for item in [x for x in line.strip().split(',') if x not in uniqueSet and not uniqueSet.add(x)])
import sys with open(sys.argv[1], 'r') as f: for line in f: sentence = line.split(', ')[0] replace = line.split(', ')[1].strip() for c in replace: sentence = str.replace(sentence, c, '') print sentence
#!/usr/bin/python3 ''' Read an integer N. For all non-negative integers i<N, print i^2. ''' n = int(input()) for i in range (0,n): print(i*i)
import numpy as np def monopoly_outcome(env, agent): ''' Calculate the theoretical optimum quantity, price and profit earned by a monopolist with linear cost and demand functions ''' q = (env.intercept - agent.mc) / 2 * env.slope p = env.intercept - env.slope * q profit = p * q - age...
#!/usr/bin/env python # get input from user response = raw_input("Would you like a toast? [Yes/No]: ") # set response string using if/else construction # Test response to a string if response == "Yes": response_str = "That's great!" else: response_str = "How about a muffin?" # output the response string print r...
#!/usr/bin/env python # create the subroutine def addNums (*numbers): sum = 0 # initialize starting sum value for num in numbers: # collection loop to get each number sum += num # sum up nums print "The summation is: %d" % sum # output resul...
#!/usr/bin/env python import sys # illustrative variables ARG_COUNT = len(sys.argv) - 1 # get num of real arguments FIRST = 1 # index of first argument print "The arugments passed are:" # use collection loop with range to enumerate arguments # Note: range ending must be one greater than desired ...
#!/usr/bin/env python import sys # illustrative variables ARG_COUNT = len(sys.argv) - 1 # get num of real arguments FIRST = 1 # index of first argument # utility variables count = ARG_COUNT # initialize counter print "The arugments passed are:" # use count style loop while count >= FI...
#Savitskiy Kirill #Problem set 1 # #Problem 1 s = 'dfsefqwfdsaweo' vow = 'euoai' n = 0 for i in vow: for j in s: if i == j: n += 1 print (n) # #Problem 2 s = 'bobazcbobobegghaklbob' w = 'bob' n = 0 for i in range (0,len(s)-2): if (s.find(w,i,i+3)>=0): n += 1 print (n) # #Problem 3 de...
# # Ejercicio _colabirativo_ #cambios introducidos 25/01 import numpy as np # **Ejercicio 1**: Escribir un arreglo con 100 números equiespaciados del 0 al 9. Pista: `linspace` np.linspace(0,9,100) # **Ejercicio 2:** crear un arreglo 1D de 20 ceros. # Reemplazar los primeros 15 elementos por unos. arr = np.zeros...
def ok(n, m): if n == 1 or m == 1: return False if n == 2: return m % 3 == 0 if m == 2: return n % 3 == 0 if n % 2 == 0 and m % 3 == 0: return True if n % 3 == 0 and m % 2 == 0: return True if n % 6 == 0: return True if m % 6 == 0: ret...
import re s = input() c = re.sub(r'[aeiouy]', '', s) v = re.sub(r'[^aeiouy]', '', s) print('Vowel' if c < v else 'Consonant')
import sys s = input() start, finish = input().split() start = list(map(int, start.split('-'))) finish = list(map(int, finish.split('-'))) a = [2000, 1, 1] if s == 'WEEK': a = [1999, 12, 27] elif s == 'FEBRUARY_THE_29TH': a = [1996, 2, 29] def addMonth(d, cnt): for i in range(cnt): month = d[1] ...
class Function: """Representation of a Function""" def __init__(self, identifier, returntype, arguments, implemented, label): """Initialize with an identifier(string), returnType(Type), argument(argumentList), implemented(bool) and label(string)""" self.identifier = identifier self.retu...
# Rewrite the program that prompts the user for a list of numbers and prints out # the maximum and minimum of the numbers at the end when the user enters "done". # Write the program to store the numbers the user enters in a list and use the # max() and min() functions to compute the maximum and minimum numbers after th...
#-*- coding:utf-8 -*- import random import itertools # plan 0 def genList0 (x): dic = [str(i+1) for i in range(x)] res = list(set(['-'.join(sorted(random.sample(dic,2))) for i in range(x*2)])) return genList(x) if len(res) < x else res[0:x] def randomList (x): return [i if random.randint(1,2) == 1 e...
vat = 0.23 cena = float(input()) def calculate_vat(netto): wart_vat = cena * vat netto = cena - wart_vat return(netto) if __name__ == "__main__": vat = calculate_vat(1000) print("{0}".format(vat)) # drugi sposob def calucate_vat(netto): return (netto * 23)/100 if __name__ == "__main__": ...
import unittest import io import sys import main ## Test Classes and Methods class TestRoll(unittest.TestCase): # Check that a Roll created with a face value of 4 has a value of 4 def test_roll_creation(self): face = 4 result = main.Roll(face) self.assertEqual(result.value, face) class TestDie(unittest.Te...
# 1. simple decorator def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper def say_whee(): print("Whee!") say_whee = my_decorator(say_whee...
#!/usr/bin/env python3 def heap_sort(l, n): for i in reversed(range(n//2)): move_down(l, n, i) for i in reversed(range(n)): l[0], l[i] = l[i], l[0] move_down(l, i, 0) def move_down(l, n, i): leftChild, rightChild, largest = 2*i+1, 2*i+2, i if leftChild < n ...
def listTest(): li_test = [] li_test.append(0) assert(len(li_test) == 1) assert(li_test[0] == 0) li_test.extend([1,2,3]) assert(len(li_test) == 4) li_test.insert(1, 9) # insert 9 before the index 1 assert(li_test[1] == 9 and li_test[2] == 1) # remove elem '9' in li_test ...
import heapq def heappop_max(heap): """Pop the largest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt heapq._siftup_max(heap, 0) else: ...
from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_iris from sklearn.cross_validation import train_test_split from sklearn.metrics import accuracy_score from sklearn.decomposition import PCA import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer...
n = int(input("Enter integer : ")) cnt = 0 if n == 0 or n == 1 : print (n,"is not a prime.") elif n == 2 : print (n,"is a prime.") else : for i in range (1,n+1) : if n % i == 0 : cnt = cnt + 1 if cnt > 2 : print (n,"is not a prime.") elif cnt == 2 : p...
# -------------------------- Problem 1 --------------------------------------- with open('score.txt', 'r') as f: studentList = f.readlines() scList = [] # เป็นลิสต์ของลิสต์ของคะแนนกับชื่อ for line in studentList: name, score = line.strip().split() score = float(score) scLi...
# coding=utf-8 #!/usr/bin/python # Cody Dillinger - EE556 - Homework 4 - MultiLayer Perceptron and Backpropagation for XOR Problem import numpy as np import matplotlib.pyplot as plt import csv, math ############################################################################ def activation_out(x): shiftx = x - n...
def sort(nums: list[int]): if len(nums) in [0, 1]: return mergesort(nums, 0, len(nums)-1) def mergesort(nums, left, right): if left == right: return mid = left + (right - left) // 2 mergesort(nums, left, mid) mergesort(nums, mid+1, right) merge(nums, left, mid, right) ...
class JumpGame(object): def __init__(self, board): self._board = board self._size = len(board) self._cache = [[None] * self._size for _ in range(self._size)] def jump(self): return self._jump_at(0, 0) def _jump_at(self, y, x): n = self._size if x >= n or y ...
def euler_circuit(adj, circuit, here): for there in range(len(adj)): if adj[here][there] > 0: adj[here][there] -= 1 adj[there][here] -= 1 print("here: %d, there: %d, circuit: %s" % (here, there, circuit)) euler_circuit(adj, circuit, there) circuit.appen...
from collections import Counter def is_perm_of_palindrome(s): counter = Counter(s) num_of_odds = 0 for c, n in counter.items(): if n % 2 != 0: num_of_odds += 1 if num_of_odds > 1: return False return num_of_odds == 0 or num_of_odds == 1 if __name__ == "__m...
class DisjointSet(object): def __init__(self, size): self.parent = [] self.rank = [] for i in range(size): self.parent.append(i) self.rank.append(1) def find(self, u): if u == self.parent[u]: return u self.parent[u] = self.find(self.p...
import random import string def getCode(length = 10, char = string.ascii_uppercase + string.digits + string.ascii_lowercase + string.punctuation): try: crtPass = "".join(random.choice( char) for x in range(length)) print 'Use The Password in side the ' return crtPass except TypeError: ...
from math import sqrt for _ in range(int(input())): c = int(input()) d = 1 + 8 * c x = int((sqrt(d) - 1) // 2) print(x)
from math import sqrt for _ in range(int(input())): n, v1, v2 = map(int, input().split()) t1 = sqrt(2) * n / v1 t2 = 2 * n / v2 if t1 < t2: print("Stairs") else: print("Elevator")
n = int(input()) people = 5 liked = 2 total = 2 for x in range(2, n+1): people = 3 * liked liked = people // 2 total += liked print(total)
length = int(input()) string = input() key = int(input()) msg = "" for x in string: if ord('a') <= ord(x) <= ord('z'): msg += chr(((ord(x) - ord('a') + key) % 26) + ord('a')) elif ord('A') <= ord(x) <= ord('Z'): msg += chr(((ord(x) - ord('A') + key) % 26) + ord('A')) else: msg += x print(msg)
def ismultipleof(arr, num): for i in arr: if num % i != 0: return False return True def isfactorof(arr, num): for i in arr: if i % num != 0: return False return True n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) a.sort() b.so...
arr = list(map(int, input().split())) word = input() h = 0 for x in word: if arr[ord(x)-ord('a')] > h: h = arr[ord(x)-ord('a')] print(h * len(word))
for _ in range(int(input())): n = int(input()) l = [1, 2] for i in range(2, n): l.append(0) l[i] = l[i-1] + 3 for i in range(n): print(l[i], end=" ") print("")
l = [] for _ in range(int(input())): l.append(int(input())) print(*sorted(l), sep="\n")
fact = [1] for i in range(1, 21): fact.append(0) fact[i] = fact[i-1] * i for _ in range(int(input())): print(fact[int(input())])
yrs = [2010, 2015, 2016, 2017, 2019] for _ in range(int(input())): if int(input()) in yrs: print("HOSTED") else: print("NOT HOSTED")
prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] #, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] for _ in range(int(input())): n = int(input()) pdt = 1 count = 0 for x in prime: pdt *= x if pdt > n: break elif pdt == n: count += 1 break count += 1 print(count)
for _ in range(int(input())): num = input() n = int(num) count = 0 for x in num: if x == "0": continue else: if n % int(x) == 0: count += 1 print(count)
import numpy as np # put user made clustering algorithms here to transform them into sklearn esque class objects class RandomAssign(object): """ Randomly assigns all stars to a cluster. If the number of clusters is not specified, the algorithm chooses a random number less than the total number of stars. """ def ...
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple ...
''' state - the state of the game being evaluated level - determines what level being evaluated where Max: level % 2 == 0 Min: level % 2 != 0 ''' def minimax(state, level): ''' If we are at a terminal state, return the utility (value) of the state. This may be a simple +1/0/-1 representing whet...
# -*- coding: utf-8 -*- #!usr/bin/env python 3 def write_file(data,filepath): with open(filepath,'w') as f: for n in data: f.write(str(n)+'\n') f.close()
stack = [] lb = int(input("Enter the lower bound:")) ub = int(input("Enter the upper bound:")) for n in range(lb, ub): for x in range(2, n): # Keep this as 2 no matter what if n % x == 0: #print(n, 'equals', x, '*', int(n/x)) break else: # loop...
def main(): print (letter) score = float(input('What mark did you get?')) if score >= 90: letter = 'A*' main() print("Very good") elif score >= 80: letter = 'A' main() print("Well done") elif score >= 70: letter = 'B' main() print("Not ba...
rep = 1 while rep == 1: num = int(input("Enter a number you think is a prime:")) for n in range(num,num+1): for x in range(2,n): if n % x == 0: print("no,",n, 'equals', x, '*', int(n/x)) break else: ...
person = input('Enter your name: ') print('Hello,', person+'!') # The + sign means there is no space after the name
temperature = float(input('What is the temperature? ')) if temperature > 30: print('Wear shorts.') else: print('Wear trousers.') print('Get some exercise outside.') import os os.system("pause")
SIZE= 10 class Heaps: def __init__(self): self.heap = [0]*SIZE self.size = 0 def insert(self,data): if self.size == SIZE: return self.heap[self.size]=data self.size+=1 self.check(self.size-1) def check(self,index): parent_index = (index-...
##used to calculate standard deviation import math import numpy class StandardDeviation(): ##passed in a pt array and returns the simple standard deviation @staticmethod def simple2(pt_array): num_points = len(pt_array) ##calculate avg sum = 0 for pt in pt_array: sum += pt.value avg = sum/float(num_...
#Perceptron. #created by Isaí vargas Chávez-Age 19 All rigths reserved @ # Compilador Clang 6.0 (clang-600.0.57)] on darwin. # version 1.0. # 03/02/2018 in Mexico City. import math import random import artificialNeuron from artificialNeuron import Neuron if __name__ == "__main__": neuron = Neuron ( ) #New neuron b...
# Programming Question-5 Algorithms Part 1 # Question 1 # Dijkstra's Shortest Path import numpy as np graph = [] # read with open('/Users/minjay/Documents/Documents/Courses/Algorithms_Part1/dijkstraData.txt') as f: for line in f: line = line.rstrip() line = line.replace(',', '\t') line = line.split('\t') lin...
# Write the code that: # 1. Prompts the user to enter a letter in the alphabet: # Please enter a letter from the alphabet (a-z or A-Z): # 2. Write the code that determines whether the letter entered is a vowel # 3. Print one of following messages (substituting the letter for x): # - The letter x is a vowel ...
""" import time t = time.time() e = (1 + (float(1) / 10000000000)) ** 10000 # eulers number """ def fact(n): # factorial function. i = 2 s = 1 while i <= n: s *= i i += 1 return s def ncr(n, r): return fact(n) / (fact(r) * fact(n-r)) class Sample(): # c...
# -*- coding: utf-8 -*- """ Created on Wed Feb 03 21:00:01 2016 @author: Geetha Yedida """ class Animal(object): """Makes cute animals.""" is_alive = True health = "good" def __init__(self, name, age): self.name = name self.age = age # Add your method here! def description(self...
# -*- coding: utf-8 -*- """ Created on Wed Feb 03 11:46:04 2016 @author: Geetha Yedida """ def product(integers): product = 1 for i in range(len(integers)): product = product * integers[i] return product
# -*- coding: utf-8 -*- """ Created on Thu Feb 04 13:29:25 2016 @author: Geetha Yedida """ my_list = [i**2 for i in range(1,11)] my_file = open("output.txt", "r+") # Add your code below! for i in my_list: my_file.write(str(i)) my_file.write("\n") my_file.close()
# -*- coding: utf-8 -*- """ Created on Wed Feb 03 11:46:29 2016 @author: Geetha Yedida """ def median(ls): count = len(ls) med = sorted(ls) mid = count / 2 if count % 2 == 0: return (med[mid] + med[mid-1])/2.0 else: return med[mid]
# -*- coding: utf-8 -*- """ Created on Wed Feb 03 11:15:37 2016 @author: Geetha Yedida """ from datetime import datetime now = datetime.now() print '%s/%s/%s %s:%s:%s' % ( now.month, now.day,now.year,now.hour, now.minute,now.second)
import csv, sqlite3 #Read given file and return the sql query def get_sql_query_string(sqlFile): fd = open(sqlFile, 'r') sqlFile = fd.read() fd.close() return sqlFile #Execute given aggregate query(Like sum, count) and return result. def execute_aggregate_query(sqlFile): result = cur.execute(get_s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 8 19:06:13 2018 @author: duh17 """ class Solution: def reverse(self, x): """ :type x: int :rtype: int """ if x.bit_length() > 31 : return 0 temp = -int(str(-x)[::-1]) if x < 0 else int(str(x)[::-...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 8 18:48:25 2018 @author: duh17 """ class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ matrix[:] = map(li...
Countries=['Afghanistan','Albania', 'Argentina','Austria','Bahamas','Bahrain','Bangladesh','Barbados','Belarus','Belgium','Bermuda','Bhutan','Bolivia'] Capital=["Kabul",'Tirana','Buenos Aires','Vienna','Nassau','Manama','Dhaka','Bridgetown','Minsk','Brussels','Hamilton','Thimphu','Sucre'] Currency=["Afghani","Lek", "Pe...
from string import punctuation """ Write a small text editor, that is, write a program that asks the user to input a text and then the program offers the following options: 1) Count the number of words in the text. 2) Count the number of a given string in the text. 3) Count the number of punctuation marks in the tex...
alphabet = 'abcdefghijklmnopqrstuvwxyz' key = 'xznlwebgjhqdyvtkfuompciasr' secret_message = input( ' Enter your message: ' ) secret_message = secret_message.lower() for c in secret_message: if c.isalpha(): print(key[alphabet.index(c)],end= '' ) else: print(c, end= '' ) print()
# Problem B - Digit Sums # input N = input() N_str = list(N) N_num = int(N) # initialization digit_sum = 0 # count for n in N_str: tmp = int(n) digit_sum += tmp # check if N_num%digit_sum==0: print("Yes") else: print("No")
# Problem A - スーパーICT高校生 # input process S = input() # initialization teacher_data = 'ict ' str_step = 0 # step process for i in range(len(S)): if S[i].lower()==teacher_data[str_step]: str_step += 1 if str_step==3: break # output process if str_step==3: print('YES') else: print('NO'...
# 競技プログラミングで使える関数集合 # 組み合わせ def combinations_count(n, r): return math.factorial(n) // (math.factorial(n - r) * math.factorial(r)) # 最大公約数を列挙する関数 def make_divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: ...
# Problem A - Heavy Rotation # input N = int(input()) # output if N%2==0: print("White") else: print("Black")
# Problem A - 暗証番号 # input N = list(input()) # initialization nums_len = len(set(N)) # output if nums_len==1: print("SAME") else: print("DIFFERENT")
import unittest from math import sqrt def distanceFormula(x1, y1, x2, y2): try: return sqrt(pow((x2-x1), 2) + pow((y2-y1), 2)) except: print("Please provide a proper input") class distanceFormulaTests(unittest.TestCase): def test_normalInputs(self): self.assertEqual(distanceFormula(1,1,0,0), sqrt(...
""" Так как PyPika не имеет возможности задавать конструкции вида `col IS TRUE` или `col IS FALSE`, то эта возможность была добавлена при помощи этого патча. Данный модуль необходимо импортировать для использования данной возможности """ from functools import wraps from typing import Any import pypika def add_method...
#--- endswith() string.endswith('.csv') # returns True if the string ends with the string passed in as the argument #--- iterating through a dictionary d = {(1,2): 3, (4,5): 6} for k, v in d: print(k) print(v) # A new built-in function, enumerate(), will make certain loops a bit clearer. # enumerate(thing), wh...
# Example of a decorator #Write code here def wrapper(function): def fun(lst): result = function(lst) sorted_list = sorted(result) return sorted_list return fun @wrapper def convert_to_phone(num_list): output = [] for phone_num in ...
from itertools import permutations suits = ['h', 'c', 's', 'd'] def all_permutations(): for y1 in suits: for y2 in suits: if y2 == y1: continue for y3 in suits: if y3 in {y1, y2}: continue for y4 in suits: ...
""" This module is python practice exercises for programmers new to Python. All exercises can be found at: http://www.practicepython.org/exercises/ You may submit them there to get feedback on your solutions. Put the code for your solutions to each exercise in the appropriate function. DON'T change the ...
# Given the root of a binary search tree, and a target K, return two nodes in # the tree whose sum equals K. # For example, given the following tree and K of 20: # 10 # / \ # 5 15 # / \ # 11 15 # Return the nodes 5 and 15. class Tree(object): def __init__(self, val, L, R): ...
from PIL import Image, ImageEnhance from os import listdir def reduce_opacity(im, opacity): """Returns an image with reduced opacity.""" assert opacity >= 0 and opacity <= 1 if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = ImageEn...
""" Instance Method Class Method Static Method """ # Instance Method #The purpose of instance methods is to set or get details about instances (objects), # and that is why they’re known as instance methods. # They have one default parameter- self # Any method you create inside a class is an instance method unless you ...
print ("Hello World from Kevin Toapanta \n Espe\n GEO") # input variables addend1= input('Enter the first number --> ') adden2=input('Enter the second number" --> ') #add two numbers sum= int (addend1) + int(addend2) #displatying the sum print(' The sum od {0} abd {1} is {2} .format(addend1,addend2,sum)) print('The s...