text
stringlengths
37
1.41M
#!/usr/bin/env python # coding: utf-8 # # KNN on Customer Dataset # # # <h1>Table of contents</h1> # # <div class="alert alert-block alert-info" style="margin-top: 20px"> # <ol> # <li><a href="#1">KNN Theory</a></li> # <li><a href="#2">KNN Algorithm</a></li> # <li><a href="#3">Calculati...
import numpy as np def pi_bound(x): return (x + np.pi) % (2 * np.pi) - np.pi def cross_product(a, b): assert len(a) == len(b) == 3, 'Vectors a, b must be three-dimensional' out = np.array( [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] ) re...
import Tree def pretty_print_tree(root): """ This function pretty prints a binary tree :param root: root of tree :return: none """ lines, _, _, _ = _pretty_print_tree(root) for line in lines: print(line) def _pretty_print_tree(root): """ Code credits: Stack overflow :p...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 3 13:39:26 2019 @author: zoureni """ #Entrer le nombre d'heure nombre_d_heure = int(input("entrer le nombre d'heure ")) #On multiplie le nombre d'heure par 60 nombre_de_minutes = nombre_d_heure * 60 #On imprime le résultat print(("le nombre de...
# -*- coding: utf-8 -*- """ Created on Wed Nov 6 15:23:39 2019 @author: 3300116973 """ print(3 + 2) # Addition print(2 * 3) # multiplication print(3 // 3)# division entiere print(7 / 2)#Division print(5 % 2)# modulo print(5 - 2)# soustraction print(2 ** 8)# exposant # comparaison print(50 > 10)# strictement superi...
Created on Tue Nov 06 18:24:03 2019 @author: idira """ # creer une variable Ch contenant le chaine ma chaine ch = 'Tombouctou' #afficher tout le caractere 'Tombouctou' print (ch) # afficher le premier caractere(T). print(ch[0]) # afficher le caractere t print(ch[7]) # afficher la chaine de caractere "ob" dans l...
# calcul de fonction f def f( x): return x+1 x=1 print(f(1)) # chercher un resultat qui sera inerieur ou egale a 10. n =0 while n <=10: n = n+1 print (n) #le resultat la racine x = 0 while x <=10: x = x + 1 from math import sqrt print(sqrt(f(x)))
# Ma variable en mémoire # Type Inference x=1 print(2*x) # Integer x=4 print(2*x) if (x == 4): print('x = 4') else: print('on ne sait pas') a = 'x = 4' print ( a ) #string a = 'x = 4' print ( a ) # Double d = 2.56 print (2 * d)
# -*- coding: utf-8 -*- # les operateurs print(5+2) # addtion print(6-2) # soustraction print(47/3) # division print(14//9) # division entière print(9 % 2) # le reste de la division ou modulo print(4**5) # l'exposant # co...
# -*- coding: utf-8 -*- """ Created on Wed Dec 4 14:26:20 2019 @author: 300117806 """ def f(x): return x + 1 print (f(1)) #Creation de boucle avec while i=0 while i < 10: print(f(i)) i = i + 1 #creation de boucle avec racine carree de 1 a 10 import math def f(x): ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 16 14:23:41 2019 @author: Amir """ print('hello') #tuple t1 vide t1 = () print ( t1 ) # tuple t2 une paire de meme type t2 = (4, 5) print ( t2 ) #tuple t3 une paire de type different t3 = ('a', '2' ) print( t3 ) #tuple t4 un trio de type de types differents t4 = (...
""" @author: Morti """ print("welcome to the mashup game") name1=input("inter one full name(First Last) :") name2=input("enter another full name(First Last) :") space=name1 . find (" ") name1_first=name1[0:space] name1_last=name1[space+1:len(name1)] space=name2.find(" ") name2_first=name2[0:space] name2_last=name...
# -*- coding: utf-8 -*- """ Created on Sun Nov 3 17:56:17 2019 @author: Nathalie """ print("bienvenue au mashup game") # l'utilisateur doit entre son nom et son prenom nom1 = str(input("entre le premier nom (FIRST LAST) : ")) # l'utilisateur a la possibilite d'entrer deux autres noms nom2 = str(input("entre un a...
# -*- coding: utf-8 -*- """ Created on Wed Nov 27 16:13:44 2019 @author: 10 """ for v in range(3): print ("var v is" ,v)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 27 14:03:09 2019 @author: zoureni """ for v in range(3): print('var is' , v)
# -*- coding: utf-8 -*- """ Created on Tue Oct 29 15:31:58 2019 @author: User """ # Declaration de la variable heure heures= int(input('veuillez entrez votre heure: ')) # calcul de la conversation d'heure en minutes minutes = heures*60 # affichage du resultat obtenue apres convertion print('la converstion de', heu...
# -*- coding: utf-8 -*- """ Created on Wed Oct 16 11:24:00 2019 @author: willfrid boris """ ###recherche la chaine 'and' dans la varaible who who="me myself and I" print(who.find("and")) print(len(who)) fruit="pomme" #imprimer le nombre de fois que le caracter "m" apparait dans fruit print(fruit.count('m')) print(f...
import turtle import math # everything is in base SI units, scale just helps keep everything on a normal-sized screen t = turtle.Turtle() # parameters x = 0.1 # x value of the spaceship. Has to be greater than 0, or else the program will crash from the first calculation. y = 160 # y value of the spaceship dx = 5 # x ...
from math import sin, cos, atan2, hypot, exp, floor, tan, sqrt from assignment_3.geometry import to_index, to_world, to_grid # ------------------------------------------------------------------------------ # Given two integer coordinates of two cells return a list of coordinates of # cells that are traversed by the li...
import time print("Hallo, welkom bij me beroeps opdracht. \nJe krijgt straks verschillende vragen en elke vraag beinvloed het spel, sommige kunnen je dus af laten gaan. Succes! ") def vraag1(): vraag1 = input("Je zit thuis en hoort ineens een knal. Wat doe je? \n A) Je doet niks en hoopt op het beste. B) Je vl...
from neuralnet import * import pandas as pd import numpy as np import matplotlib.pyplot as plt import generallib as gl #le dataset y_column = -1 data = pd.read_csv("data/Churn_Modelling_Edited.csv") #abre arquivo y = np.array(pd.DataFrame(data.iloc[:, y_column])) dataset = np.array(data.drop(data.columns[y_column]...
l=lambda x:'EVEN'if x%2==0 else 'ODD' k=int(input("enter a number")) print(l(k))
# *** coding: utf-8 *** #@Time : 2020/12/4 15:25 #@Author : xueqing.wu #@Email : wuxueqing@126.com #@File : test.py # num1 = input('请输入第一个数字:') # num2 = input('请输入第二个数字:') # num3 = input('请输入第三个数字:') # # if num1.isdigit() and num2.isdigit() and num3.isdigit(): # num1 = int(num1) # num2 = int(num2) # n...
class Cat: def __init__(self,name): self.name = name self.kind = "cat" self.next = None def __str__(self): return f"I am a cat, my name is {self.name}" class Dog: def __init__(self,name): self.name = name self.kind = "dog" self.next = None def _...
# a function to reverse an input array def reverseArray(inputArray): for i in range(len(inputArray)//2): inputArray[i],inputArray[-i-1]=inputArray[-i-1],inputArray[i] return inputArray # print(reverseArray([1,2,3,4,5])) # print(reverseArray([89, 2354, 3546, 23, 10, -923, 823, -12])) # method #2. def reverseA...
locations = [["The Porch", "An old, wooden porch lies before the entrance to the house.", {"key": ["A rusty old key.", False, [False, None]]}], ["Hallway", "The hallway is laden with dust. Old paintings hang from the crumbling walls.", {"painting": ["An old painting. '07/10/1873' is written in the lower right corner...
""" Description: Create blank Omnigo Data Object & fill in data Convert Python Class Object to JSON string Create JSON file if it doesn't exist Append new JSON string to the file """ #import sys import json import sys class OmniData: CLIENT_NAME = 'TSE' PROJECT_KIT_ID = 515151515 STAGE = 'NULL' NO_OF_BOARDS = 0 N...
#================================ CAPTURING A SINGLE FRAME: #================================ from cv2.cv import * # Initialize the camera capture = CaptureFromCAM(0) # 0 -> index of camera if capture: # Camera initialized without any errors NamedWindow("cam-test",CV_WINDOW_AUTOSIZE) f = QueryFrame...
# -*- coding: utf-8 -*- """ Description: Get image size in pixels Resize 2 images to screen length [800] width = scaled % of original width """ import PIL from PIL import Image file0 = "/home/antz/0_Python/image/Armadillo/img1.jpg" # path to woring directory file1 = "/home/antz/0_Python/image/Armadillo/img...
""" 70 Examples: https://www.programcreek.com/python/example/83064/tkinter.OptionMenu """ import Tkinter as tk OptionList = [ "Aries", "Taurus", "Gemini", "Cancer" ] app = tk.Tk() app.geometry('100x200') variable = tk.StringVar(app) variable.set(OptionList[0]) opt = tk.OptionMenu(app, variable, *OptionList) opt....
# -*- coding: utf-8 -*- """ Python 2.7 (virtual env) -> If directory doesn't exist, it is created -> If it exists, opens existing directory & prints contents """ import sys import os def main(): exists = 0 # variable to append after printing contents cnt = 0 # file_path1 = "/home/antz/0Python/...
# -*- coding: utf-8 -*- """ Description: Description: Displays all images in full screen mode Images found in given file path Loops continuously [ctrl+C to exit] """ import pygame import sys import os def main(): cnt = 0 # new file counter #file_path1 = "/home/pi/Pictures/pics" # actua...
""" Created 8-bit Port for Raspberry Pi """ import wiringpi2 as wiringpi from time import sleep # allows us a time delay wiringpi.wiringPiSetupGpio() wiringpi.pinMode(24, 1) # sets GPIO 24 to output wiringpi.digitalWrite(24, 0) # sets port 24 to 0 (0V, off) var=1 try: print "Start loop" ...
from flask import Flask from flask_restful import Api, Resource app = Flask(__name__) api = Api(app) names = { "tim": { "age": 19, "gender": "male" }, "suyash": { "age": 25, "gender": "male" }, "sonal": { "age": 25, "gender": "female" } } class...
name = "Vladut" #Difference between Tuples () and Arrays [] is, that Tuples are immutable! It is recommended to use them, when we don't want values from it modified months = ("January","February","March") students = ["John","Diana","George"] print(students) print(students[0]) students.append("Kate") print(students[...
# wip # def insertion_sort(A, n, g): # count = 0 # for i in range(g, n): # v = A[i] # j = i - g # while j >= 0 and A[j] > v: # A[j+g] = A[j] # j= j - g # count += 1 # A[j+g] = v # return count # def shell_sort(A, n): # count = 0 # ...
slowa = ['aaabaaa', 'aa', 'c', 'bbaa', 'baba', 'abba'] def palindrom(slowo): print(slowo) a=len(slowo) b=a/2 i=0 while i < b: if slowo[i] == slowo[-1-i]: pass else: print("to nie jest palindrom") return False i=i+1 print("to jest palin...
#!/usr/bin/env python # coding: utf-8 # In[21]: #1 Define a function named is_two. It should accept one input and return #True if the passed input is either the number or the string 2, #False otherwise. def is_two(num): return int(num) == 2 is_two(2) # In[23]: #2 Define a function named is_vowel. It sho...
# Importing modules that are required. import sympy as sp # Required for dictating the sub-shells with number of electrons. from mendeleev import * # Required for synthesis of data from Periodic Table. sp.init_printing() # Taking the value from the user. o = input('Enter the Symbol of element : ') # Synth...
import time # Given an array [10,9,8,7,6,5,4,3,2,1] # Sort the array in Ascending order def insertion_sort(arr: list): start = time.time() for i in range(1, len(arr)): for j in range(0, i): if arr[i] < arr[j]: popped = arr.pop(i) arr.insert(j, popped) d...
class SplayTree(object): """Splay Tree object. A splay tree is a self balancing binary search tree with operations that run in O(log(n)) amortized time, where n is the number of entries in the tree. This particular implementation uses a dictionary interface; it may be extended to use a key only interface how...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 29 23:03:25 2021 @author: andrewtuckman """ class Board: """ a data type for a Connect Four board with arbitrary dimensions """ def __init__(self, height, width): """ constructs a new Board object inputs: t...
# BOJ 1922 네트워크 연결 def find_set(x): if parent[x] < 0: return x parent[x] = find_set(parent[x]) return parent[x] def union(x, y): x = find_set(x) y = find_set(y) if x < y: parent[x] += parent[y] parent[y] = x else: parent[y] += parent[x] parent[x] = y...
# BOJ 1197 최소 스패닝 트리 def find_set(x): if parent[x] < 0: return x parent[x] = find_set(parent[x]) return parent[x] def union(x, y): x = find_set(x) y = find_set(y) if x < y: parent[x] += parent[y] parent[y] = x else: parent[y] += parent[x] parent[x] =...
# BOJ 1978 소수 찾기 def is_prime(number): if number == 1: return False i = 2 while i * i <= number: if number % i == 0: return False i += 1 return True N = int(input()) numbers = list(map(int, input().split())) numbers.sort(reverse=True) prime = [] for i in range(1, nu...
# BOJ 6497 전력난_kruskal def find_parent(x): if parent[x] < 0: return x parent[x] = find_parent(parent[x]) return parent[x] def union(x, y): x = find_parent(x) y = find_parent(y) if x == y: return if x < y: parent[x] += parent[y] parent[y] = x return ...
from Tkinter import * m1 = PanedWindow() m1.pack(fill=BOTH, expand=1) left = Label(m1 , text = "left pane") m1.add(left) m2 = PanedWindow(m1, orient = VERTICAL) m1.add(m2) top = Label(m2,text = "top pane") m2.add(top) bottom = Label(m2,text="bottom pane") m2.add(bottom) mainloop()
# First and last occurrences of X """ Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array. Note: If the number x is not found in the array just print '-1'. Input: The first line consists of an integer T i.e number of test ...
import turtle def drawSpiral(t, length, color): if length != 0: newcolor = (int(color[1:],16) + 2**20)%(2**24) newcolor = hex(newcolor)[2:] newcolor = "#"+("0"*(6-len(newcolor)))+newcolor t.color(newcolor) t.forward(length) t.left(200) drawSpiral(t,...
import binascii import hashlib import os import sqlite3 import string import smtplib import ssl import uuid from random import choice, randint import yaml from DBInfo import DBInfo from weight import Weight def create_connection(db_file): """ Create a database connection to the SQLite database specif...
from collections import defaultdict from collections import Counter sequenceString = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC" class Sequence: def __init__(self, seq): self.sequence = seq class SequenceCountService: def __init__(self, sequence): if not isinstanc...
from collections import defaultdict from collections import Counter seq = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC" #print(len(seq)) class Sequence: def __init__(self, seq): self.seq = seq def calc(self): pass seq2 = Sequence(seq) class SequenceCo...
def reverseString(str_data): return str_data[::-1] def reverseString2(str_data): stack = [] for ch in str_data: stack.append(ch) result = "" while len(stack) > 0: result += stack.pop() return result print(reverseString2("asdbqwe1234"))
#!/usr/bin/env python from functools import wraps from datetime import datetime as DateTime def print_name( old_func ): @wraps(old_func) def new_func( *args, **kwargs ): print " ==> Calling function {0} at {1}".format(old_func.__name__, DateTime.now()) return old_func( *args, **kwargs ) # c...
#!/usr/bin/env python presidents = [] with open('../DATA/presidents.txt') as PRES: for line in PRES: fields = line.split(':') last_name = fields[1] first_name = fields[2] presidents.append(first_name + ' ' + last_name) pres_upper = [ p.upper() for p in presidents ] for pres in pre...
#!/usr/bin/env python class AddProperty(object): def __init__(self, property_name, **kw): '''Add one property to a class. fixed parameter: property_name->str or unicode Name of the property keyword parameters: readwrite->Boolean Whether the property...
#!/usr/bin/env python from datetime import datetime as DateTime class PrintName(object): def __init__(self, old_function): self._old_function = old_function self.__name__ = self._old_function.__name__ def __call__( self, *args, **kwargs ): print " ==> Calling function {0} at {1}".for...
#!/usr/bin/env python # (c)2014 John Strickler people = [ [ 'Ann', 'Whittier', 'TX' ], [ 'Raul', 'Rodriguez', 'NV' ], [ 'Jim', 'Benson', 'VA' ], [ 'Srini', 'Singh', 'IL' ], ] for p in people: print p[0], p[2] print for first_name, last_name, state in people: print first_name, state
#!/usr/bin/env python def pres_upper(): with open('../DATA/presidents.txt') as PRES: for line in PRES: # trim line, make it upper case, split on ':', # then grab fields 1 through 2 lname, fname = line[:-1].upper().split(':')[1:3] # yield (return) "Fi...
#!/usr/bin/env python LIMIT=99 if len(sys.argv) > 1: limit = int(sys.argv[1]) values = [ True for val in range(LIMIT+1) ] primes = [] #print list(enumerate(values)) for addr in range(2, LIMIT+1): if values[addr]: primes.append(addr) for val in xrange(2*addr, LIMIT+1, addr): value...
#!/usr/bin/env python import re # sum the squares of a list of numbers # using list comprehension, entire list is stored in memory s1 = sum([x*x for x in range(10)]) # only one square is in memory at a time with generator expression s2 = sum(x*x for x in range(10)) print s1,s2 print # set constructor -- does not pu...
#!/usr/bin/env python FRUITS = ['watermelon', 'apple', 'kiwi', 'lime', 'orange', 'cherry', 'banana', 'raspberry', 'grape', 'lemon', 'durian', 'guava', 'mango', 'papaya', 'mangosteen', 'breadfruit'] KV_SEQ = ('red', 5, 'blue', 3, 'yellow', 7, 'purple', 2, 'pink', 8) EVEN_SLICE = slice(0, None, 2) # even elements OD...
# coding: utf-8 # # Exercise Sheet 11 (Bonus)- MLP # Yiping Deng, Shalom-David Anifowoshe # In[36]: # initialize numpy enviroment get_ipython().magic(u'matplotlib notebook') import numpy as np from numpy import square import matplotlib.pyplot as plt # In[2]: # Code for visualizing MLP structure def draw_neura...
# defining the class named Person # it has 3 parameters that each instance of the class will need # first name, last name, and age class Person: def __init__(self, first, last, age): self.__first = first self.__last = last self.__age = age # declaring a public function that returns the...
import random import turtle import numpy as np from matplotlib import pyplot as plt from matplotlib import colors from matplotlib.ticker import PercentFormatter def task1(steps, prob, move): x = 0 if not move: return x for _ in range(steps): if random.random() < prob: ...
from collections import Counter import re def _merge_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z def replace(clicks): clicks = clicks.replace('blue', 'B') clicks = clicks.replace('red', 'R') clicks = clicks.replace('ye...
def check_palindrome(word): letters = list(word.lower()) for i in letters: j = letters.index(i) + 1 if i == letters[-j]: pass else: return False return True def palindrome_two(word): letters = list(word.lower()) letter_dict = {a+b:True for a, b in zip(letters, letters[::-1]) if a == b} return True i...
print("------------------------------------Exercise A -----------------------------------------------") print("Display all numbers 1-5, using list of numbers.") for num in (1,2,3,4,5): print (num, end=' ') print ("\n") print("------------------------------------Exercise B -----------------------------------------...
def personal_info(): print("My name is Ashur Motlagh") print("In live in California.") print("My phone number is: 714-726-4503") def work_info(): name=str(input("Enter your name: ")) age=int(input("Enter your age: ")) salary=int(input("Enter your salary: ")) bonus=int(input("Enter your bonu...
def main(): n1=int(input("Enter your first number: ")) n2=int(input("Enter your second number: ")) print() print("Calling method \"sum_two\" inside main function") s=sum_two(n1, n2) print("Sum of ", n1, "and", n2, "inside \'main\' function is: ", s) print() print("Calling method \"min_...
# This lab is teaching us to use file append mode ans = "yes" while ans[0].lower() == "y": print("I am writing 3 numbers to the file.") f1 = int(input("Enter first number: ")) f2 = int(input("Enter second number: ")) f3 = int(input("Enter third number: ")) myfile = open('lab25.txt', 'a') myfile...
def main(): n1 = int(input("Enter a number: ")) print() print("Calling\'show_double\' function inside main function.") show_double(n1) print() print("Back to \'main\' function.") def show_double(a): print("Double of",a,"inside \'show_double\' is:",a*2) main()
#!/usr/bin/python class WordNode: """ Object representing a word and it's followers """ def __init__(self, word): """ Initialize with a string """ self.word = word self.followers = {} #can be used to begin a sentence self.starter = Fa...
#TIC-TAC board=['_','_','_','_','_','_','_','_','_',] pp1=[] pp2=[] def rules(): print("Positions:\t 1 | 2 | 3") print("\t\t____|___|____") print("\t\t 4 | 5 | 6") print("\t\t____|___|____") print("\t\t 7 | 8 | 9") print("\t\t | | ") def check(pos): #Checking Weather the requested...
import random def miller_test(n, iterations): if n == 2: # corner case even prime 2 return True if n % 2 == 0: # if n is even it can't be prime except for 2 handled above return False m = n - 1 k = 0 # finding m where m is the least integer = n-1/2^k while m % 2 == 0: ...
def favGenre(userSongs, songGenres): """ TC:O(m*n*l) , m=len of genre, n= len of songs, l=len of users SC:(m*n), {song:genre} hashmap https://leetcode.com/discuss/interview-question/373006 """ songMapGenre = {} res = defaultdict(list) # mapping each song to genre for key in songGe...
# Explorar el tema de conceptos y turnos # Continua en test7, aquí realmente destaca el "colocador de texto" import pygame import pygame_widgets import random from Constantes import * from Clases import * from Funciones import * # Creamos la ventana donde se muestra todo WIN = pygame.display.set_mode((WIDTH, HEIGHT))...
class Twitter(object, ): def __init__(self): self.tweets = {} self.followDB = {} self.count = 0 def postTweet(self, userId, tweetId): self.count += 1 if (userId not in self.tweets): self.tweets[userId] = [] self.tweets[userId].append({'count': self.c...
import random class Solution(object): def __init__(self, nums): self.db = {} for (i, val) in enumerate(nums): if (val not in self.db): self.db[val] = [] self.db[val].append(i) def pick(self, target): return random.choice(self.db[target])
class Solution(object): def insert(self, intervals, newInterval): def merge_interval(intervals): a = [] prevVal = (-1) while (len(intervals) > 0): startInterval = intervals[0][0] endInterval = intervals[0][1] intervals.pop...
import string class Solution(object): def mostCommonWord(self, paragraph, banned): listOfWords = banned allWords = [] for word in paragraph.split(' '): for letter in string.punctuation: word = word.replace(letter, '') word = word.lower() ...
class Solution(object): def treeToDoublyList(self, root): a = [] def check(root): if (root == None): return a.append(root.val) check(root.left) check(root.right) check(root) a.sort() g = [] def linkedL...
import string diction = {} MAIN = list(string.printable) for (i, letter) in enumerate(MAIN): diction[str(i)] = letter class Codec: def encode(self, longUrl): new = '' for letter in longUrl: new = ((new + '-') + str(MAIN.index(letter))) print new return new def...
import string class Solution(object): def generateTheString(self, n): if ((n % 2) == 0): stringVal = ''.join(['a' for i in range((n - 1))]) return (stringVal + 'z') else: return ''.join(['a' for i in range(n)])
class NestedIterator(object, ): def __init__(self, nestedList): def getR(a): final = [] if (type(a) == list): for val in a: if (val.isInteger() == False): final += getR(val) else: ...
class Solution(object): def average(self, salary): minVal = float('inf') maxVal = float('-inf') total = 0 for v in salary: if (v < minVal): minVal = v if (v > maxVal): maxVal = v total += v print minVal ...
class Solution(object): def isPowerOfTwo(self, n): def is_power(n): if ((n == 1) or (n == 2)): return True if (n < 2): return False if (n != int(n)): return False return is_power((float(n) / 2.0)) retur...
class Solution(object): def isPowerOfThree(self, n): def is_power(n): if (n != int(n)): return False if (n == 3): return True if (n == 1): return True if (n < 3): return False return...
from tkinter import * import random w=Tk() w.title("가위 바위 보 게임") def selection(var): img = [PhotoImage(file='image/scissor.png'), PhotoImage(file='image/rock.png'), PhotoImage(file='image/paper.png')] user_lb = Label(w, text='사용자', compound='top', image=img[var]) user_lb.image = img[var] user_lb.grid(...
def binary_search(arr, n, k): start_index = 0 end_index = n-1 # while start index is less or equal to end index while start_index <= end_index: # mid index is the start index + end index - start index # if start index is 40 and end index is 45 then mid index is 40 + 1.5 ie 43/42 ~ what...
rojo = [255,0,0] verde = [0,255,0] azul = [0,0,255] # Los vectores en Python se representan con la estructura de datos lista tupla = (1,1,1) # Las tuplas son otra estructura de datos pero son imutables print(type(rojo)) print(type(tupla)) print('El color rojo se representa con el vector ', rojo) print('El c...
import numpy as np # Importamos numpy vector = np.array([1,-1,1]) # Declaramos el vector como numpy array escalar = 3.1 # Declaramos el escalar print('El resultado del producto vector y escalar es ', vector*escalar) ### EJERCICIO ### v = np.array([1,1]) a = -1 b = 2 c = 0.1
T=input('#TestCases') cases=[] for i in range(int(T)): N=0 B=0 test_case_line=input('#OfHouses Budget') test_case_line_list=test_case_line.split(' ') N=int(test_case_line_list[0]) B=int(test_case_line_list[1]) test_case_line2=input('NPricesOfEachHouse') A=test_case_line2.split(' ') ...
# -*- coding:utf-8 -*- ''' python文件操作 创建,打开,添加,读取文件和写入文件等操作. ''' """ # 1. 如何创建一个txt文件 def main(): # 声明变量f来打开一个名为first.txt的文件, open需要一个文件名和一个对文件的模式, w+: 表示写入并且如果文件中不存在则会创建文件 f = open('./demo/first.txt','w+') # 如果文件不存在,w会自动创建该文件. # 写入文件内容: for i in range(10): f.write('this is firstoneyuan ...
def write_to_file(file, postcode, city, country): try: with open(file, 'w') as opened_file: opened_file.write(f'My postcode is {postcode} \nI am based in {city}, which is in {country}.') except FileNotFoundError: print('File not found.')
"""Dans ce fichier vous trouvez des exemples d'utilisations des boucles N'hesitez pas a vous exercer pour mieux comprendre comment on utilise cela""" def Bonjour(nombre): """Cette fonction va servir à afficher la valeur absolu de nombre fois le mot bonjour elle va prendre en paramètre un nombre qui indique...
from functools import reduce class Group(): def __init__(self, raw): self.persons = [set(x) for x in raw.split("\n")] def get_answers_count(self, aggregation): return len(reduce(aggregation, self.persons)) with open('input', 'r') as f: groups = [Group(x) for x in f.read().split("\n\n")] ...
def solve1(board): return descend(board, 3, 1) def solve2(board): a = descend(board, 1, 1) b = descend(board, 3, 1) c = descend(board, 5, 1) d = descend(board, 7, 1) e = descend(board, 1, 2) return a * b * c * d * e def descend(board, slope_x, slope_y): trees_count = 0 x, y = 0, ...
def partOne(val): # The bottom right value of each square is an odd power of 2 (9, 25, 49, 81, ...) # Find which square the number is in by getting the next upper odd power of 2 i = 1 while i*i < val: i += 2 square = i/2 # The number "square" is at distance "square * 2" from the center ...
#!/usr/bin/env python # coding=utf-8 import sys def left_child(node): return node * 2 + 1 def right_child(node): return node * 2 + 2 def parent(node): if (node % 2): return (i - 1) / 2 else: return (i - 2) / 2 def max_heapify(array, i, heap_size): l = left_child(i) ...