text
stringlengths
37
1.41M
import fileinput, math, bisect filename = "inputs/day5.txt" def first(x,y): return (x, x + math.ceil((y - x) / 2)) def last(x,y): return (x + math.ceil((y - x) / 2), y) directions = {"F": first, "B": last, "L": first, "R": last} maxseat = 0 def get_seat_id(row, col): return row * 8 + col def binsearch(...
def sum_of_odd(): sum = 0 myList = [] for i in range(524, 10509, 2): sum += i myList.append(i) print(sum) print(len(myList))
def smaller_of_largest(L1, L2): '''(list of int, list of int) -> int Return the smaller of the largest value in L1 and the large st value inL2. Precondition: L1 and L2 are not empty. >>> smaller_of_largest([1, 4, 0], [3, 2]) 3 >>> smaller_of_largest([4], [9, 6, 3]) 4 '''...
# -*- coding: utf-8 -*- """ Created on Fri Feb 5 15:03:11 2021 @author: ray-h """ # Givens # Outstanding balance on the card balance = 484 # Annual interest rate as decimal annualInterestRate = 0.2 # Minimum monthly payment as decimal monthlyPaymentRate = 0.04 # To be solved monthlyInterestR...
from sys import argv def main(): # Fail check if len(argv) != 3: print("Usage: python dna.py {data.csv} {sequence.txt}") return 1 strands = [] people = {} # Opening the csv file containing data data = open(argv[1], "r") # For each row, index and row both iterates fo...
# -*- coding: utf-8 -*- """ Created on Sat Jan 30 00:16:12 2021 @author: ray-h """ # Part B - Saving, with a raise annual_salary = float(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ")) total_cost = float(input("Enter the cost of y...
Message = ''' class Message: """Shows a message in a little rectangle :) methods : show attributes : text, color, surface, borderwidth, bordercolor, rounded, rect text: the message you want to display color: the background color of the message box rect: the rectangle that bounds the mes...
from Calculator.Multiplication import multiplication from Calculator.Division import division def cochran(p, q, z, e): try: n1 = multiplication(p, p) n2 = z * z n3 = multiplication(n1, n2) n4 = e * e nCochran = division(n4, n3) return int(nCochran) except ZeroDi...
from Calculator.Multiplication import multiplication from Calculator.Division import division from Calculator.SquareRoot import square_root def cimarginerror(n, x, s): try: zValue = 1.96 n1 = square_root(n) n2 = division(n1, s) n3 = multiplication(n2, zValue) return round(f...
import math def sqrt_test(X): eps = 0.0000001 old = 1 new = 1 while True: old = new new = (new + X/new) / 2.0 if abs(new - old) < eps: break return new #fu for i in range(0,1000): out = sqrt_test(i) print(i,out)
# General functions for working with time series data def time_series_split(data, split): """Split time series data into train and test set :param DataFrame data: data frame with n x time points and m x variables :param float split: proportion of train and test split :return: split train and test dat...
import math def resolve(f, a, b, epsilon): c = (a + b) / 2.0 print(c) if(f(c) == 0 or b-a < epsilon): return c elif(f(a)*f(c) < 0): return resolve(f, a, c, epsilon) else: return resolve(f, c, b, epsilon) f = lambda x: x**3 - x**2 - 1 a = 0 b = 4 epsilon = 0.00001 prin...
import unittest class TestPartitionList(unittest.TestCase): def test_leet_example(self): head = ListNode(1) four = ListNode(4) three = ListNode(3) two = ListNode(2) five = ListNode(5) two2 = ListNode(2) head.next = four four.next = three thre...
# Day 3 def transform_data(data): return [int(x) for x in data.strip().split()] with open('day3.txt') as f: transform = transform_data(f.read()) data = [transform[i:i+3] for i in range(0, len(transform), 3)] #with open('day3_test.txt') as f: # transform = transform_data(f.read()) # data = [transfor...
# Weighted Mean import unittest def weighted_mean(n, x, w): product = [a*b for a,b in zip(x,w)] factorials = [x for x in w] print product print factorials return float(("{0:.1f}".format(float(sum(product))/float(sum(factorials))))) class TestWeightedMean(unittest.TestCase): def test_simple_a...
import unittest class TestSumSublist(unittest.TestCase): def test_single(self): self.assertEqual(max_sum_sublist([-4, 2, -5, 1, 2, 3, 6, -5]), 12) def max_sum_sublist(lst: list) -> int: global_max = lst[0] current_max = lst[0] for i in range(0, len(lst)): if current_max < 0: ...
import unittest class TestRerverseVowels(unittest.TestClass): def test_leet_examples(self): self.assertEqual(reverse_vowels("hello"), "holle") self.assertEqual(reverse_vowels("leetcode"), "leotcede") def reverse_vowels(s): vowels = {'a', 'e', 'i', 'o', 'u'} letters = list(s) last_vowe...
''' You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken...
import math import unittest class TestBinarySearch(unittest.TestCase): def test_contiguous_sorted(self): self.assertFalse(binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11, None, None)) self.assertTrue(binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10, None, None)) def test_non_contiguous_sor...
import unittest class TestSymmetricTree(unittest.TestCase): def test_is_mirror(self): self.assertTrue(check_symmetry([1, 2, 2, 3, 4, 4, 3])) self.assertFalse(check_symmetry([1, 2, 2, None, 3, None, 3])) def check_symmetry(root): left_root = root right_root = root left = [] right =...
# Standard Deviation import unittest def std_deviation(n, array): # Mean mean = float("{0:.1f}".format(sum(array)/ float(n))) squares = [] for x in array: squares.append((x-mean)**2) return float("{0:.1f}".format((sum(squares)/float(n))**.5print "{}\n{}\n{}".format(*mean_median_mode(n, arr...
import unittest class TestLongestCommonPrefix(unittest.TestCase): def test_leet_example_1(self): self.assertEqual(longest_common_prefix(['flower', 'flow', 'flight']), 'fl') def test_leet_example_1(self): self.assertEqual(longest_common_prefix(['dog', 'racecar', 'car']), '') def test_lee...
import math import unittest class TestBinarySearchIterative(unittest.TestCase): def test_contiguous_sorted(self): self.assertFalse(binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11)) self.assertTrue(binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10)) def test_non_contiguous_sorted(self): ...
# Day 2 - 2021 def transform_data(data): return [x.strip().split() for x in data.strip().splitlines()] with open("day2.txt") as f: data = transform_data(f.read()) def depth_traversed(data): hor = 0 vert = 0 for x in range(0, len(data)): if data[x][0] == 'forward': hor += int(...
while True: ask = str(input('What is the quote? ')) if len(ask) > 0: break while True: who = str(input('Who said it? ')) if len(who) > 0: break print(f'{who} says: "{ask}."')
num1 = 42 # variable declaration, Number num2 = 2.3 # variable declaration, Number boolean = True # variable declaration, boolean string = 'Hello World' # variable declaration, string pizza_toppings = ['Pepperoni', 'Sausage', 'Jalepenos', 'Cheese', 'Olives'] # variable declaration, list person = {'name': 'John', 'locat...
n = int(input()) k = int(input()) if n>=6: print("Love is open door") else: for i in range(1,n): if k == 0: print(i) elif k == 1:
#2๊ฐœ์˜ ํƒ€์ผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋Š” ๋„๋ฏธ๋…ธ๋ฅผ ๋ณด๋ฉด, #์œ„์— ์žˆ๋Š” ๋„๋ฏธ๋…ธ ์กฐ๊ฐ์„ ์ฒซ๋ฒˆ์งธ, #์•„๋ž˜์— ์žˆ๋Š” ๋„๋ฏธ๋…ธ ์กฐ๊ฐ์„ ๋‘๋ฒˆ์งธ๋กœ ๋ณด๋ฉด ํŒจํ„ด์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. #์ด์ค‘ for๋ฌธ ์‚ฌ์šฉํ•ด์„œ ํ•ด๊ฒฐ ๊ฐ€๋Šฅ #(0,0), (0,1), (0,2), (1,1), (1,2), (2,2) N = int(input()) sum = 0 for i in range(0,N+1): for j in range(i, N+1): sum += i + j print(sum)
#1st method def maxnum(arr): n = len(arr) count = 0 for i in range(n): if(arr[i]==max(arr)): count += 1 return count #2nd method def max_num(arr): return arr.count(max(arr)) arr = [2,3,3,1] print(maxnum(arr)) print(max_num(arr))
#!/usr/bin/env python3 import sys assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') color = input("What is my favorite color? ") print(color) #Before running ''' This program is different from the last in two ways. First off it actually stores my guess into a varible (...
class Point: def __init__(self, x, y): self.x= x self.y= y def __add__(self, p): if isinstance(p, Point): return Point(self.x+ p.x, self.y+ p.y) def __repr__(self): return "Point({},{})".format(self.x, self.y)
from tkinter import * root = Tk() root.title("kkyu GUI") root.geometry("640x480") Label(root, text="Select the menu").pack() burger_var = IntVar() btn_burger1 = Radiobutton(root, text="Hamburger", value=1, variable=burger_var) btn_burger1....
""" Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer. """ def digital_root(n): digit_sum = sum([int(d) f...
# sample6.py # ํ•จ์ˆ˜์— ๋Œ€ํ•ด์„œ ๊ฐ„๋žตํžˆ ๋ฐฐ์›Œ๋ด…์‹œ๋‹ค!!! # ๋ง์…ˆ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ํ•จ์ˆ˜(function)์„ ๋งŒ๋“ค์–ด ๋ด…์‹œ๋‹ค!(ํ•จ์ˆ˜์ •์˜/์„ ์–ธ) """ def ํ•จ์ˆ˜์ด๋ฆ„(): ์ฝ”๋“œ1 ์ฝ”๋“œ2 .... """ def add(op1, op2): # add ํ•จ์ˆ˜ ์ •์˜(์„ ์–ธ) result = op1 + op2 return result # ์œ„์—์„œ ์ •์˜ํ•œ add ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉ --> "ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค!!!"๋ผ๊ณ  ํ•จ # result = add(1, 2) result111 = add(10, 10) print(result111)...
# sample54.py # To test inheritance of class. class Parent : # ๋ถ€๋ชจ ํด๋ž˜์Šค def __init__(self): # ์ƒ์„ฑ์ž(Constructor) print('- Parent::__init__ invoked.') # super().__init__() self.field1 = 0 pass def method1(self): # ๋ฉ”์†Œ๋“œ(Method) print('- Pa...
# sample45.py # ๋žŒ๋‹ค์‹ = Lambda Expression # ๋žŒ๋‹ค์‹์˜ ๋ชฉํ‘œ๋Š” ๋‹จ ํ•œ๊ฐ€์ง€: # ์ต๋ช…ํ•จ์ˆ˜(Anonymous Function) ์ •์˜(์„ ์–ธ) # 1. def ํ‚ค์›Œ๋“œ๋กœ ๋ง์…ˆํ•จ์ˆ˜ ์„ ์–ธ # def add(num1, num2): # return num1 + num2 # pass # result = add(1, 3) # print(result) # 2. ๋žŒ๋‹ค์‹์„ ์ด์šฉํ•œ ๋ง์…ˆ์ˆ˜ํ–‰ # print('-'*30) # ๋ง์…ˆํ•จ์ˆ˜(add)๋ฅผ ๋žŒ๋‹ค์‹์œผ๋กœ ๊ตฌํ˜„ add = lambda num1, num2 : num1 + num2 ...
# import random randNum = random.randint(1,45) inputNum = int(input('์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.(1~45) : ' )) TryNum = 5 MaxNum = 45 MinNum = 1 while (inputNum != randNum) : if (inputNum > randNum) : TryNum -= 1 print('์ž…๋ ฅ๊ฐ’์ด ํฝ๋‹ˆ๋‹ค') MaxNum = inputNum -1 else : print('์ž…๋ ฅ๊ฐ’์ด ์ž‘์Šต๋‹ˆ๋‹ค') MinNum = ...
# sample21.py # tuple object manipulation # 1. Slicing t = (0, 1, 2, 3, 4, 5) # result = t[ : ] # result = t[0 : 2] # result = t[ :3] # result = t[2 : ] # result = t[-1] # result = t[-3 : -1] t1 = (1, ) t2 = 2, 3 # result = t1 + t2 result = t1 * 2
import arcpy import math class ArcArcKDTreeNode(object): """ Class object that stores properties that allow for a functional ArcKDTree to be implemented on any acpy shape based on centroid. """ def __init__(self, axis, left=None, right=None, depth=None, shape=None, x=None, y=None, data=...
""" Locates word-spaces in a given grid. """ # Could probably clean this up def search_rows(grid, grid_size): ''' Searches for word-spaces in the 'across' direction in a grid. Parameters: grid_size |<int>| The size of the grid. grid |<list><int>| List of active (white) grid square numbers. ...
name = input("What's ur name? ") # input function queries the user print ("Hey", name, "!") name = input("What's ur name? ") print ("Hey {}".format (name)) #.format can be used with print function fname = input("What's ur first name? ") l_name = input("What's ur last name? ") print ("Hey {} {}!".forma...
#Basic if statement # v = int(input("enter a number from 10 to 20 ")) if v == 15: print ("i thought you might choose that number") else: print ("i guessed the wrong number") #Basic Elif statement # v = int(input("enter a number from 1 to 20 ")) if v == 15: print ("i thought you might choose that number") e...
a_list = [3,1,2,9,5,4,7,8,6] #Ordena los elementos de la lista in situ a_list.sort() a_list.sort(reverse=True) a_list = [(1,9), (1,3), (1,4), (1,2)] a_list.sort(key=lambda x: x[1]) #Revierte los elementos de la lista in situ a_list = [3, 1, 2, 9, 5, 4, 7, 8, 6] a_list.reverse() a_list = [3, 1, 2, 9, 5, 4...
matriz = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] matriz[0][0] matriz[1][2] #Ejemplo funciรณn suma de matrices def suma_matrices(A,B): """ Suma dos matrices. Precondiciรณn: A y B son del mismo tamaรฑo y son matrices de nรบmeros. """ cant_filas = len(A) cant_...
#! python3 from math import trunc def truncate(number, decimals=0): if not isinstance(decimals, int): raise TypeError('decimal places must be an integer') elif decimals < 0: raise ValueError('decimal places have to be at least 0') elif decimals == 0: return trunc(number) facto...
#!/usr/bin//env python import psycopg2 ''' 1. What are the most popular three articles of all time? Which articles have been accessed the most? Present this information as a sorted list with the most popular article at the top. ''' query_one_question = 'What are the most popular three articles of all time?' # Store th...
# Celine Manigbas # Assignment: Prog A1 # returns the AT content by counting the amount of times # A and T are in the DNA, and divides the sum by the # length of the DNA stranf print "Part 1" dna1 = "ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT" at = (dna1.count("A") + dna1.count("T"))/float(len(dna1)) print...
import math def count_roads(roads): len_roads = len(roads) essential_raods = [] essential_group = [] for i, line in enumerate(roads): for j, point in enumerate(line): if point == "Y": road = (i, j) if j > i else (j, i) if road not in essential_raods:...
#inList = [1, 5, 3, 3, 7]; inList = [1, 3, 5, 3, 4]; def isSorted(nums): for i in range(0, len(nums) - 1): if nums[i] > nums[i+1]: return False return True def isSortedSwap(nums): if isSorted(nums): return True inLength = len(inList) #print(inLength) for i in range...
limit = 10**17 printgeninfo = False printcountinfo = False # dynamic programming, zeckendorf representation requires that the fibonacci # numbers used in the representation are not consecutive # using f_2=1 and f_3=2, index in rtsum is sum of terms used in representations # for the fibonacci numbers below f_i (for in...
import math iterations = 1000 def digits(n): # number of base 10 digits return 1 + math.floor(math.log10(n)) # brute force with python large integer support # x = 1 + (1 / (2 + 1 / (2 + 1 / ...)) --> x = 1 + 1 / (1 + x) --> x = sqrt(2) # suppose we have x_n = 1 + 1 / (1 + x_n-1) # this sequence results from recu...
import math from bitarray import bitarray def prime(n): # requires sqrt(n) time if n < 2: return False; if n == 2 or n == 3: return True; if n % 2 == 0: return False; for d in range(3, int(math.sqrt(n))+1, 2): if n % d == 0: return False return True def miller_rabin_verified(n)...
import libtkoz as lib import math limit = 10**8 # sieve, then pick a prime p and count how many primes q >= p such that # pq <= limit, so its summing pi(limit/p)-pi(p-1) for every p<=sqrt(limit) # sieving primes takes long but summing is fast since computing pi(n) can be # done efficiently with a prime list and binar...
length = 50 # how many ways to place blocks on different length ways = [1,1,1,2] while len(ways) <= length: curlen = len(ways) ways.append(ways[-1]) # if last space is empty # consider the first block placed and how many ways to fill the rest # for example, if length is L, first block is n, then we m...
import libtkoz as lib width = 20 height = 20 # too large to solve by brute force, dynamic programming # direction is left and up for this array # 0 1 2 ... # 1 . # 2 . grid = [[0] * (width+1)] * (height+1) grid[0] = [1] * (width+1) # 1 path starting from top row for i in range(height+1): grid[i][0] = 1 # 1 path...
base = 2 exp = 1000 # use simple python features to do this # compute number, convert to string, convert to list of digits as integers # from there its just the sum of those integers (which are the digits) print(sum(list(int(x) for x in str(base**exp))))
import math limit = 2000000 # faster method with prime sieve, odds only to reduce memory needs by 50% # sum starts at 2 since sieve is only considering odds psum = 2 pcount = 1 sievesize = (limit+1) // 2 # last index has largest odd, index i means 2i+1 sieve = [True] * sievesize # loop for odds up to square root for...
# table of 5th powers so they arent calculated every time fifths = list(x**5 for x in range(10)) print(':', fifths) # must satisfy 9^5 * n < 10^n for n digits # n=6 is satisfactory so pick an upper bound of 9^5 * 6 total = 0 for i in range(10, 6*(9**5)+1): ii = i s = 0 while ii != 0: # sum digit exponent...
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] permutation=1000000 # combinatorics algorithm, assumes all digits are unique # an algorithm based on combinatorics, for example: 10th permutation of 1234 # theres 3!=6 of digits starting with 1 so 7th is 2134 # with 3 to go to get to 10th, 10-7=3 --> 3/2! = 1 increments of the 1...
import libtkoz as lib seqlen = 3 # currently hardcoded, has no effect digits = 4 # brute force primes = lib.list_primes2(10**digits) print(': listed', len(primes), 'primes') def is_prime(n): # assumes it would be in the primes list, binary search global primes l, h = 0, len(primes) while l != h: ...
def check_horizontal(): row = 0 row1 = 1 row2 = 2 col = 0 col1 = 1 col2 = 2 if grid[row][col] == grid[row][col1] == grid[row][col2] == 'x': return 'x' elif grid[row][col] == grid[row][col1] == grid[row][col2] == 'o': return 'o' elif grid[row1][col] == grid[row1][col1...
"""Day 8. To make sure the image wasn't corrupted during transmission, the Elves would like you to find the layer that contains the fewest 0 digits. On that layer, what is the number of 1 digits multiplied by the number of 2 digits? """ from typing import List from collections import Counter with open('input.txt') as...
employee_file = open("employees.txt","a") #append employee_file.write("Toby - Manager\n") #if append twice the entry is done twice employee_file.write("kelly - Saleswoman") employee_file.close() employee_file1 = open("employees1.txt","w") #if done in existing file it rewrites the whole existing data employee_file1.wri...
# functions def say_hi(name,age): print("Hello "+name+ " You're " + age) # print("Top") say_hi("Mike", "35") say_hi("Abhi", "20") # print("Bottom") def say_hi(name,age): print("Hello "+name+ " You're " + str(age)) # print("Top") say_hi("Mike", 35) say_hi("Abhi", 20)
class book(): def __init__(self, title, author, y_publish, no_pages, isbn): self.title = title self.author = author self.y_publish = y_publish self.no_pages = no_pages self.isbn = isbn def __repr__(self): return f" book title is {self.title}\n Author i...
# This script will create a graph of mean read length distribution import gzip import matplotlib.pyplot as plt import sys def make_graph(read1,read2,read1Name,read2Name): '''Creates a graph of quality score counts''' lists1 = sorted(read1.items()) x1, y1 = zip(*lists1) lists2 = sorted(read2.items())...
"""Opens and ingests the contects of a csv file containing quotes CSVInvestor realizes the IngestorInterface abstract class. The class variable allowed_extensions adds csv to the list of allowed extensions. The class can run the IngestorInterface class method can_ingest to confirm the file is a csv. The class metho...
# encoding: utf-8 """ ไธ€. ๆœ‰ๅ››ไธชๆ•ฐๅญ—๏ผš1ใ€2ใ€3ใ€4๏ผŒ่ƒฝ็ป„ๆˆๅคšๅฐ‘ไธชไบ’ไธ็›ธๅŒไธ”ๆ— ้‡ๅคๆ•ฐๅญ—็š„ไธ‰ไฝๆ•ฐ๏ผŸๅ„ๆ˜ฏๅคšๅฐ‘๏ผŸ ๅฏๅกซๅœจ็™พไฝใ€ๅไฝใ€ไธชไฝ็š„ๆ•ฐๅญ—้ƒฝๆ˜ฏ1ใ€2ใ€3ใ€4ใ€‚็ป„ๆˆๆ‰€ๆœ‰็š„ๆŽ’ๅˆ—ๅŽๅ†ๅŽป ๆމไธๆปก่ถณๆกไปถ็š„ๆŽ’ๅˆ—ใ€‚ """ import pprint # pprint็พŽ่ง‚ๆ‰“ๅฐ # my_answer: lis_01 = [] def func(): lis = [1, 2, 3, 4] for i in lis: for j in lis: for k in lis: if (i != j) and (i != k) and (...
# # Shell sort # # https://www.alphacodingskills.com/python/pages/python-program-for-shell-sort.php # def sort(array): n = len(array) gap = n // 2 while gap > 0: for i in range(gap, n): temp = array[i] j = i while j >= gap and array[j-gap] > temp: ...
def ldistance(string, token): # Calculate the Levenshtein distance between string, token if len(string) < len(token): return ldistance(token, string) if len(token) == 0: return len(string) previous_row = range(len(token) + 1) for i, c_string in enumerate(string): current_row...
import random # Write your code here word_file = "dic" words = open(word_file).read().splitlines() #words = ["python", "java", "kotlin", "javascript"] playing = True #loop for main hangman game while playing: word = random.choice(words) word2 = list(len(word) * "-") man = [".....|......", "......
# To capitalize the first character in a sentense and change the rest to # lower case you are use the capitalize function that comes built-in # for a string data type # The following will print the capitalize of simpleSentence simpleSentence = "hi, this is Jayanth Kanive" print simpleSentence.capitalize()
# This is used to split a string into a list based on a defined separator. # The default separator is a space simpleSentence = "HI, THIS, IS, JAYANTH, KANIVE" newArr1 = simpleSentence.split() newArr2 = simpleSentence.split(',') print simpleSentence print newArr1 print newArr2
# You can reverse a list of elements using the reverse method. aList = [123, 'xyz', 'zara', 'abc', 'xyz']; print aList aList.reverse() print aList
''' James D. Zoll 4/2/2013 Purpose: Define a class that the various feeds can inherit from. License: This is a public work. ''' class Feed(object): ''' Base class for Feeds. Do not instantiate directly. ''' def __init__(self, name, label, description, display_priority): ''' In...
""" Partition class (holds feature information, feature values, and labels for a dataset). Includes helper class Example. Author: Sara Mathieson + Lamiaa Dakir Date: 13/09/2019 """ from math import log2 class Example: def __init__(self, features, label): """ Helper class (like a struct) that store...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # findFile.py for ๆ“ไฝœๆ–‡ไปถๅ’Œ็›ฎๅฝ•: ๆŸฅๆ‰พๆ–‡ไปถ # ็ผ–ๅ†™ไธ€ไธช็จ‹ๅบ๏ผŒ่ƒฝๅœจๅฝ“ๅ‰็›ฎๅฝ•ไปฅๅŠๅฝ“ๅ‰็›ฎๅฝ•็š„ๆ‰€ๆœ‰ๅญ็›ฎๅฝ•ไธ‹ๆŸฅๆ‰พๆ–‡ไปถๅๅŒ…ๅซๆŒ‡ๅฎšๅญ—็ฌฆไธฒ็š„ๆ–‡ไปถ๏ผŒ # ๅนถๆ‰“ๅฐๅ‡บ็›ธๅฏน่ทฏๅพ„ใ€‚ import os import os.path targetDir = input('Please enter where you want to search:\n') key = input('Please enter what you want to search:\n') def find_file(targetDi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # hanoi pazzle def move(n,a,b,c): if n==1: print(a+'-->'+c) return else: move(n-1,a,c,b) move(1,a,b,c) move(n-1,b,a,c) def pas_triangles(): a = [1] while True: yield a a = [sum(i) for i in zip([0]+a, a+[0])] n = input('Please en...
# -*- coding: utf-8 -*- """ Created on Sun May 30 18:22:38 2021 @author: Uchechukwu """ """ Assignment1 Write a simple statement to implement the usage of each of the following dictionary methods """ # 1. fromkeys() position= {'CEO', 'Managing director', 'Operations manager', 'Securty cordinator'} description= 'Execu...
import os import random def main(): mainMenu() def mainMenu(): print("(1). Play Game") print("(2). See History") print("(3). Login") print("(4). Exit\n") while(True): userInput = input(">>") if(userInput == "1"): mainLoop() elif(userInput == "2"): ...
# Bubble Sort def bubble_sort(a_list): # Setting Swapped to True to get the loop going and variable instantiating swapped = True while swapped: # This breaks the loop if we don't swap anything swapped = False for i in range(len(a_list) - 1): # compare list data and swap ...
# Read the puzzle input into a file f = open('D1-P1-input.txt', 'r') module_masses = f.readlines() index = 0 total_fuel = 0 for mass in module_masses: # Strip the \n out mass = mass.strip('\n') # Replace that value with the stripped value and increment the index module_masses[index] = int(m...
fib_num= lambda n:fib_num(n-1)+fib_num(n-2) if n>2 else 1 print(fib_num(6)) def test1_fib_num(): assert (fib_num(6)==8) def test2_fib_num(): assert (fib_num(5)==5) def test3_fib_num(): n = 10 assert (fib_num(2*n)==fib_num(n+1)**2 - fib_num(n-1)**2)
from math import pi r = float(input("Specify the radius of the circle: ")) print ("The area of the circle is " + str(pi * r **2))
import math a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) print("The GCD of the two numbers is: ", math.gcd(a, b))
name = str(input("Enter your name: ")) age = int(input("ENter your age: ")) address = str(input("Enter your address: ")) print ("Name" + "-", name) print ("Age" + "-", age) print ("Address" + "-", address)
x = float(input("Enter a number: ")) if x == 0: print ("Value is zero.") elif x > 0: print ("Value is positive.") else: print ("Value is negative.")
#Loops in the python are very powerful. # for item in <iterable> # For loop can be iterable on any Iterable item like char,list,tuple,set,dict. # for item in 'Hello Manish Gandhi': # print(item) #Iterables user = { 'name': 'Prabhas', 'role': 'Hero', 'age': 100, 'movie': 'baahubali' } for item ...
#Conditional Logic - Booleans are very important in this. #and is a keyword. #we can have multiple elif but only one if and else. is_old = True is_licensed = True if is_old and is_licensed: print('You are old enough and you have a license') else: print('You are not old enough') print('okoko') #Indentation i...
#Short circuiting. #short ciruiting majorly explains like if there is an operation of and, if the first conditions is False. #Python interpreter will not check for the second condition after and, because anyway it is going to skip the #statement. It is the same with or condition as well. #The process of skipping the c...
name = input('Whats is your name') print('Helloooooo ' + name)
#Booleans - Booleans in python are bool - It is only two values "True or False" name = 'Manish' is_cool = False is_cool = True print(type(is_cool)) print(bool(1)) print(bool(0)) print(bool(True)) print(bool(False))
#Tuple #These are like lists but immutable. # we are going to use brackets in tupe "()" #Creation of Tuple my_tuple = (1,2,3,4,5,5) print(my_tuple[3]) #Dict can have the key objects as Tuple becuase We can only have the immutable objects as keys. user = { (1,2): 'manish', 'job': 'student' } print(user[(1,2...
# Dictionaries - its a data type in python but also a data structure. Its a way for us to organise the data. # So, that we can organise the data within it. # Dict will be having a key and a value. It is an unordered Key value pairs. # This means that unlike lists Dict variables values are not stored side by side in the...
# Zip - It acts like a zipper. # This will combine with the iterable in the list. # fist element with the first item of the another iterable. # Key catch is none of the iterables variables will not be changed. # zip() will accept multiples iterables. # Example list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] pr...
x = int(input("enter the number:")) result = 1 for i in range(x,0,-1) : result = result*i print("factorial of",x,"is",result)
def main (x1, y1, x2, y2): return (float)(y2-y1)/(x2-x1) x1 = float(input('x1 = ')) y1 = float(input('y1 = ')) x2 = float(input('x2 = ')) y2 = float(input('y2 = ')) print('Slope is=', main(x1, y1, x2, y2))
##Rudy Garcia print("Hi, I\'m here to give you Pythagorean triples!") x= int(input("All I need is for yu to give me the smallest number in it:\n")) y=x/2 z= x/4 if y.is_integer() is True: if z.is_integer() is True: print("This actually makes a triple starting with an odd number") triple_2= ((x**2)-4)/4 t...
from math import atan2, pi, sqrt def wind_speed_from_u_v(u, v): return sqrt(pow(u, 2) + pow(v, 2)) def wind_direction_from_u_v(u, v): """ Meteorological wind direction 90ยฐ corresponds to wind from east, 180ยฐ from south 270ยฐ from west 360ยฐ wind from north. 0ยฐ is used for no ...
m = {'A':0,'A#':1,'B':2,'C':3,'C#':4,'D':5,'D#':6,'E':7, 'F':8,'F#':9,'G':10,'G#':11} def interval(a, b): d = (m[b] - m[a] + 12) % 12 return d k1 = raw_input() k2 = raw_input() k3 = raw_input() f = k1 d1 = interval(k1, k2) d2 = interval(k2, k3) c = 0 if not ((d1 == 4 and d2 == 3) or (d1 == 3 and d2 == 4) ...