text
stringlengths
37
1.41M
#!/usr/bin/env python """ Experiments about occur checking and unification algorithms, useful for haskell, lambda calculus and prolog """ class Subst(object): "Contains a variable and the term you want to substitute" def __init__(self, var, term): self.var = var self.term = term # see how a te...
import tkinter #import b as b # Описываю какие-то события def handler1(event): print('Hello World! x =', event.x, 'y =', event.y) def handler2(event): exit() # Инициализация root = tkinter.Tk() hello_label = tkinter.Label(root, text='Hello world!', font="Times 40") hello_label.pack() # Привязка обработч...
# Import of the required packages import json import urllib from urllib.request import urlopen # This function returns URLs (for the "theMovieDB"-API) for all movie of an user given time span def linksYearCreater(): # "s" is the complete URL to get the 20 most succesful movies of a certan year, without the year s...
import sys class Variable: """docstring for Variable""" def __init__(self,name, datatype='Int', size=4,isArray=False): self.name = name self.datatype = datatype self.isArray = isArray self.size = size class Method: def __init__(self, name, datatype='Int'): self.name = name self.datatype = datatype ...
__author__ = "Sai Sujith Kammari" ''' CSCI-603: LAB 8 Author1: SAI SUJITH KAMMARI Author2: KEERTHI NAGAPPA PRADHANI Draws the balance with the weights provided. If the torque on the right doesn't match then exits ''' import sys import turtle # global constants for turtle window dimensions WINDOW_WIDTH = 2000 WIN...
# -*- coding: utf-8 -*- ''' Created on 2018年1月19日 @author: Jeff Yang ''' # 列表是可以修改的,而元组的值是不可变的 # 元组使用括号()标识 dimensions = (200, 50) print(dimensions[0]) # 访问元组元素和列表相似 print(dimensions[1]) # 单元素元组要加一个逗号避免歧义,如dimensions = (200,) dimensions = (200) print(type(dimensions)) # <class 'int'> # dimensions...
# -*- coding: utf-8 -*- ''' Created on 2018年1月18日 @author: Jeff Yang ''' import random for value in range(1, 5): # 表示从1开始,到4位置 # 默认情况下,range()起始值是0,range(5)范围为0到4 print(value) numbers = list(range(1, 6)) # 使用函数list()将range()的结果直接转换为列表 print(numbers) even_numbers = list(range(2, 11, 2)) # 第...
# -*- coding: utf-8 -*- ''' Created on 2018年1月18日 @author: Jeff Yang ''' players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) # 切片,切除索引从0开始,到2为止的元素 print(players[:4]) # 默认从索引0开始,到索引为3的元素 print(players[2:]) # 从索引2开始,到列表最后 print(players[-3:]) # 从倒数第三个元素开始,到末尾 print("\nHer...
# -*- coding: utf-8 -*- ''' Created on 2018年1月19日 @author: Jeff Yang ''' # python2中用raw_input(),它接收输入转换成string返回,输入数字也会当成string # python2中input()原理上是raw_input()调用eval()函数,输入字符串要用引号引起 # python3中raw_input()和input()进行了整合,仅保留了input()函数,其接收任意输入并返回字符串类型。 # eval():把字符串当成有效的python表达式求值并计算结果 # repr():把变量和表达式转换成字符串表...
from multiprocessing import Pool with open("./input.txt", "r") as f: lines = f.readlines() superline = lines[0].strip("\n") uniq_letters = set([x.lower() for x in superline]) print(uniq_letters) def calc_behaviour(line_uniq): line, uniq = line_uniq[0], line_uniq[1] done = False while True: ...
n = int(input("Enter the length of the sequence: ")) # Do not change this line for i in range(1, n+1): if i == 1: new_number = num_1 = i elif i == 2: new_number = num_2 = i elif i == 3: new_number = num_3 = i else: new_number = num_1 + num_2 + num_3 num_1, num_2...
import re from dataclasses import dataclass # Fermat's little theorem gives a simple inv: # Meaning (a * inv(a, n)) % n = 1 def inv(a, n): return pow(a, n - 2, n) assert (5 * inv(5, 7))%7 == 1 print([inv(i, 11) for i in range(11)]) @dataclass class Shuffle: a: int b: int def forward(self, idx, size): ...
def fahrenheit_convert(C): fahrenheit = int(C) * 9/5 + 32 return str(fahrenheit) + 'F' print(fahrenheit_convert(30)) def trapezoid_area(base_up, base_down, height): return 1/2 * (base_down + base_up) * height print(trapezoid_area(1,2,3)) print(trapezoid_area(height=3,base_up=1,base_down=2))
import pandas as pd # Read the csv df = pd.read_csv('auto-mpg.txt', delim_whitespace=True, header=None) columns = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin', 'car name'] df.columns = columns def normalise(val): f_val = float(val) return 1/f...
class Bot: def __init__(self, pieces, colour): self.colour = colour self.pieces = pieces def calculate_trade(self, mypiece, otherpiece): return otherpiece.value - mypiece.value # sort_list_of_pieces sorts list of potential pieces can be captured def sort_list_of_pieces(self, ...
import pygame import random pygame.init() # Colors white = (255, 255, 255); red = (255, 0, 0); black = (0, 0, 0); green=(123,43,43); Font=pygame.font.SysFont('Purisa', 30, bold=True, italic=False) Font1=pygame.font.SysFont('DejaVu Sans', 40, bold=True, italic=False) #text display # def screen_text(text,color,x,y): ...
#!/usr/bin/python #CS 68, Bioinformatics: Lab 4 #By Elana Bogdan and Emily Dolson import pygraphviz as pgv import sys, os, copy def main(): #Make sure command-line arguments are valid if len(sys.argv) < 2: print "Usage: NJTree.py distances" exit() if not os.path.exists(sys.argv[1]): ...
#!/usr/bin/env python ''' Davis-Putnam-LL SAT solver in plain format as specified by the assignment. For a version with metrics/logging, check SAT_for_analysis.py. Implemented by Kim de Bie ''' import sys import random from collections import Counter from itertools import chain import csv heuristic = sys...
#!/usr/bin/python3 import sys def nextFootprint(footprints, step): # Our current location is the last entry in the list of footprints. here = footprints[-1].split(',') # print('Next step: ' + str(step) + ' from ' + str(here)) # Split here into x and y coordinates x = int(here[0]) y = int(here[1]) # Split step...
#02-011.py def power(base, n): return (base) ** n def power_base(base): def power_without_name(n): return power(base, n) return power_without_name power_2 = power_base(2) power_3 = power_base(3) print(type(power_2), type(power_3)) print(id(power_2), id(power_3)) #print(id(power_2), ...
#04-002.py a = (1, 2, 'go', 4, 5, 6, 7, 8, 9, 10) print(type(a), a) print(type(a[0]), a[0]) print(type(a[2]), a[2]) b = a[2:5] print(type(b), b) print(a[3:]) print(a[:5]) print(a[::3]) print(a[1:-2]) print(a[-4:-1]) a = [1, 2, 'go', 4, 5, 6, 7, 8, 9, 10] b = a[2:5] b[1] = 'go' print(type(b), b) pr...
#03-012.py for i in range(10): if not (i % 3) or not (i % 2) : continue for j in range(10): if i == j : break print(i, j) def func() : for i in range(10): for j in range(10): if (i+2) == j : return print(i, j) print('---------------') func() ...
#02-022.py value = 3 def add_num(value, num=1): value += num print(value) return value value = add_num(value) print(value) a = [1, 2, 3, 4] print(a)
#04-039.py a = [x*2 for x in range(1, 6)] #iterable g = (x*2 for x in range(1, 6)) #iterator print(a) print(g) for i in range(5) : print(a[i], end=' ') for i in range(5) : print(g[i], end=' ') print() print (next(a)) print (next(g)) c = iter(a) print (next(c))
#06-002.py import re def check(pw): if len(pw) < 8: return False bs = ( r'[0-9]+', r'[A-Z]+', r'[~!@#$%^&*]+') for x in bs: if re.search(x, pw) == None : return "NO" return "YES" print(check(input()))
class WhatClass(object): def __new__(cls, **pVK): if len(pVK) > 3 : return None for x in pVK: if x not in ('a', 'b', 'c') : return None return super().__new__(cls) def __init__(self, a=None, b=None, c=None): self.a = a self.b = b self....
from node import Node # print ('hello world') storedWords= open('words.txt','r') # print(storedWords) storedWords = storedWords.read().splitlines() storedWords = [item.lower() for item in storedWords] # print(storedWords) print (ord(storedWords[0])%26) root = Node(None) node = Node(1) node.children[5] = Node(5) print('...
import random userGuess = 0 counter = 0 a = random.randint(1, 9) while userGuess != a: userGuess = input("What's your guess: ") if userGuess == "exit": break userGuess = int(userGuess) counter = counter + 1 if userGuess < a: print("Too low") elif userGuess > a: print...
game = True while game: player = input("Write rock, paper, scissors: ") player2 = "rock" tie = False if player == player2: print("Tie") tie = True elif player == "rock" or player == "Rock": if player2 == "paper" or player2 == "Paper": print("You lose") e...
'''#1 def del_list(list): del list[0] letter = ['a', 'b', 'c'] print 'before_list' print letter del_list(letter) print letter #2 def dict_loop(dict): for name in dict: print name, dict[name] sunghwan_info = {'name':'sunghwan', 'age':20} dict_loop(sunghwan_info) ''' #exercise 1 data = {'minsu':43, 'jisu':33, ...
__author__ = '3tral' def reverorder(): st = raw_input("please input a string you want to reverse:\n") result = st.split() ab = st.split()[::-1] return ab print reverorder() #but my result is a list format, not a string format. it's not big deal, but i care. #so it can be change like the answer: # return ' '.join(ab...
__author__ = '3tral' import random l1 = random.sample(range(1,1000), random.randint(10,20)) print(l1) l2 = [1,2,3,4,5,6,7] i = input("input a number:\n") print('ha') if i not in l1: print('bingo') else: print('cao') if i in l2: print('ainiyo') else: print('qunima')
__author__ = '3tral' with open('file_to_write.txt', 'w') as open_file: open_file.write('A string is your mom') open_file.write("\nhow's your single day?") open_file = open('s2ndfile.txt','w') open_file.write('laozi shi dier pa') open_file.close() #reading file official web https://docs.python.org/3.3/tutorial/input...
# Mikael Hinton # Project 7 # iRand from Project 5 # InsertionSort from Project 6 https://www.geeksforgeeks.org/insertion-sort/ # BinarySearch https://stackoverflow.com/questions/38346013/binary-search-in-a-python-list # irand is a function given to the students that generates a list of length # is the random selectio...
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.card_game = CardGame() card_1 = Card("clubs", 2) card_2 = Card("diamonds", 1) card_3 = Card("spades", 5) card_4 = Card("hearts", 8) ...
# Import the OS module: This allows us to create file paths across operating systems import os # Module for opening & reading CSV files import csv #Determine working directory csvpath=os.path.join(r"C:\Users\eliza\Desktop\Data Analytics\Git Hub Repositories\03-Python-Challenge\PyPoll\Resources\election_data.csv") wi...
#declare and initiate variables import csv import os #declare totals variables tot = 0 totMnth = 0 totMnthAvgDenom = 0 #declare profit and loss variables and get avg change curPL = 0 prevPL = 0 curChange = 0 #used for the currect total change prevChange = 0 #used to hold the previous total change totChange = 0 #used...
import random output = None def loadMenu(): print("1. Roll Die") print("2. Roll Dice") print("3. Settings") menuSelection = int(input("Enter menu selection: ")) if (menuSelection == 1): rollDie() elif (menuSelection == 2): numOfDies = int(input("How many dice would you like to roll: ")) x = 0 while x < ...
import math, abs class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __iadd__(self, other): self.x += other.x self.y += other.y return self def __sub__(self, other): return Poi...
name1 = str(input("First name ")) day1 = int(input("First day ")) month1 = int(input("First month ")) year1 = int(input("First year ")) name2 = str(input("Second name ")) day2 = int(input("Second day ")) month2 = int(input("Second month ")) year2 = int(input("Second year ")) name3 = str(input("Third name ")) d...
from http.server import BaseHTTPRequestHandler, HTTPServer import json #What is BaseHTTPRequestHandler --> Handle HTTP reqs that arrive at server. Must be subclassed to handle each request. Important instance var of this class is server and client-address which is a tuples of the form (host, port), rfile and wfile(IO s...
import math def part_one(): masses = [] with open("input.txt") as f: for line in f: masses.append(int(line)) return [math.floor(m / 3) - 2 for m in masses] def part_two(fuels): recursive_fuel_req = [recursive_mass(fuel_mass) for fuel_mass in fuels] return sum(recursive_fuel_...
# This class SHOULD NEVER be instantiated # BUT logic common to both types of nodes can be placed here e.g. distance class Node(object): def __init__(self): self.id = '' self.x = 0.0 self.y = 0.0 self.demand = 0.0 self.serviceTime = 0.0 self.windowStart = 0.0 ...
numero = int(input("Digite o numero da tabuada: ")) for count in range(1, 11): multiplica = numero * count print("{} x {} = {}".format(numero, count, multiplica))
frase = str(input("Digite a sua frase: ")).strip().upper() palavra = frase.split() junto = ''.join(palavra) inverso = '' '''inverso = junto[::-1] - Está linha faz a mesma função do FOR abaixo''' for letra in range(len(junto) - 1, -1, -1): inverso += junto[letra] print(junto, inverso) if inverso == junto: p...
n1 = int(input("Primeiro valor: ")) n2 = int(input("Segundo valor: ")) opcao = 0 while opcao != 5: print(''' [1] Somar [2] Multiplicar [3] Maior [4] Novos Números [5] Sair''') opcao = int(input("Qual é a sua opção: ")) if opcao == 1: soma = n1 + n2 print("A soma de {} e...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 13 11:52:15 2019 In this function a neural network is created to determine if the masses of gives usefull values of the minimums to find. @author: ug """ import tensorflow as tf import numpy as np import pandas as pd data_input_T = np.load('dataPyth...
from random import randrange from sys import exit import sqlite3 connection = sqlite3.connect('card.s3db') cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS card (id INTEGER PRIMARY KEY, number TEXT, pin TEXT, balance INTEGER DEFAULT 0);') connection.commit() login_account_number = 0 class Cust...
# get training data, validation data, test data, layer neuron numbers, learning rate, mini-batch size, number of training epochs # function for mini-batch stochastic gradient descent # function for updating each mini batch # function for backpropagation # function for sigmoid computation # function for sigmoid derivati...
#!/usr/bin/env python3 """ Name: player_wolfe.py Desc: Mr. Wolfe's player AI, uses minimax and AB pruning Author: Alex Wolfe """ from copy import deepcopy from constants import * class Player(): def __init__(self, color): self.name = "WolfeBot" self.type = "AI" self.color = col...
#!/usr/bin/env python # coding: utf-8 # In[2]: # ============================================================= # Copyright © 2020 Intel Corporation # # SPDX-License-Identifier: MIT # ============================================================= # # XGBoost Getting Started Example on Linear Regression # ## Importi...
from collections import deque class node: def __init__(self,val): self.l = None self.r = None self.v = val self.color = 0 self.d = 0 class tree: def __init__(self): self.root = None self.l = None self.r = None self.h = 0 def fromlist(self, alist...
from abc import ABC, abstractmethod from tkinter import * from tkinter import filedialog """ The App class defines the behaviour of a GUI application to select the file paths. """ class App: shape_path = "" image_path = "" def __init__(self, delegate): # Sets the delegate object self.del...
#importamos biblioteca y declaramos variable import random caracteres = ['!','#','$','%','&','?','¿','¡','*','+','"'] frase = (input('Ingrese su contraseña: ')) #primera condicion hacer fuincion while (4 > (len(frase.split())) or 10 < (len(frase.split()))): frase = input ("Ingrese una contraseña que este en el ra...
import pygame # Inicializando o pygame e criando a janela pygame.init() display = pygame.display.set_mode([840, 480]) pygame.display.set_caption("Palavras Cruzadas") drawGroup = pygame.sprite.Group() guy = pygame.sprite.Sprite(drawGroup) guy.image = pygame.image.load("Data/pixil-frame-0.png") guy.image = pygame.tran...
# Swap with and without temp a=4 b=7 temp=a a=b b=temp print("Swapped with temp :") print("a=",a," b=",b) a=a+b b=a-b a=a-b print("Swapped without temp :") print("a=",a," b=",b)
string=input("Enter a string:") rev='' for i in string: rev = i + rev print(rev,"is the reverse of",string)
string1=input("Enter main string: ") string2=input("Enter the string to be added: ") stringf="" for i in range(0,int(len(string1)/2)): stringf = stringf + string1[i] stringf=stringf + string2 for i in range(int(len(string1)/2),len(string1)): stringf = stringf + string1[i] print(stringf)
print("Enter Tuple of Numbers. Any character to end.") try: my_tup=() while True: m except: print("List of Numbers:",my_tup)
num1 = 6 num2 = 10 if num1 < num2: print("less than") elif num1 == num2: print("elual to") else: print("greater than") progName = "Python" answer = "I love {}!".format(progName) print(answer) myList = ('Pink', 'Black', 'Green', 'Teal', 'Red', 'Blue') for color in myList: if color == 'Blue': ...
##Creating a class that will be encapsulated class protected: def __init__(self,number): #Creating a nurmal attribute self.a = 10 #Creating a protected attribute self._b = 20 #creating a private attribute self.__c = 30 protected = protected('number') print(protect...
from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style import random style.use('fivethirtyeight') xs=np.array([1,2,3,4,5,6], dtype=np.float64) ys=np.array([5,4,6,5,6,7], dtype=np.float64) def best_fit_slope_and_intercept(xs,ys): print(xs,ys) m=(mean(xs)*mea...
#!/usr/bin/env python2.7 """ Columbia W4111 Intro to databases Example webserver To run locally python server.py Go to http://localhost:8111 in your browser A debugger such as "pdb" may be helpful for debugging. Read about it online. """ import os from sqlalchemy.exc import IntegrityError, DataError from sql...
# Level 1 # 음양 더하기 # https://programmers.co.kr/learn/courses/30/lessons/76501 def solution(absolutes, signs): sum = 0 for i in range(len(absolutes)): if signs[i]: sum += absolutes[i] else: sum -= absolutes[i] return sum
# Binary Search # 고정점 찾기 # Amazon 인터뷰 import sys def binary_search(arr, start, end): if start > end: return None mid = (start + end) // 2 if int(arr[mid]) == mid: return mid # 중앙값보다 index가 더 작다면 elif int(arr[mid]) > mid: return binary_search(arr, start, mid - 1) # 중앙값...
# 시간초과 # def solution(s): # s_list = list(s) # i = 0 # while True: # if s_list[i] == s_list[i+1]: # s_list.pop(i) # s_list.pop(i) # i = 0 # else: # i += 1 # if i >= len(s_list)-1: # break # if len(s_list...
# Level 2 # 2021-09-15 11:50- # https://programmers.co.kr/learn/courses/30/lessons/42586 # 진도가 적힌 정수 배열 progress # 작업의 개발 속도가 적힌 정수 배열 speeds import math progress = [93, 30, 55] speeds = [1, 30, 5] day = [] answer = [] #progress = [95, 90, 99, 99, 80, 99] #speeds = [1, 1, 1, 1, 1, 1] for i in range(len(progress)):...
# Graph # 행성 터널 # https://www.acmicpc.net/problem/2887 def find_parent(parent, x): if parent[x] != x: parent[x] = find_parent(parent, parent[x]) return parent[x] def union_parent(parent, a, b): a = find_parent(parent, a) b = find_parent(parent, b) if a < b: parent[b]...
# BFS,DFS # 괄호 변환 # https://programmers.co.kr/learn/courses/30/lessons/60058 def checkBalance(word): l = 0 r = 0 for i in range(len(word)): if word[i] == '(': l += 1 else: r += 1 if l == r: return word[:i + 1], i + 1 def checkCorrect(word): s...
# Level 2 # 뉴스 클러스터링 # https://programmers.co.kr/learn/courses/30/lessons/17677 import copy def union(l1, l2): result = l1 for i in range(len(l2)): if l2[i] in result: if l2.count(l2[i]) > result.count(l2[i]): cnt = l2.count(l2[i]) - result.count(l2[i]) ...
# Binary Search # 정렬된 배열에서 특정 수의 개수 구하기 # Zoho인터뷰 import sys def binary_search(arr, target, start, end): if start > end: return None mid = (start + end) // 2 if int(arr[mid]) == target: return mid elif int(arr[mid]) > target: return binary_search(arr, target, start, mid - 1) ...
# Level 1 # 숫자 문자열과 영단어 # https://programmers.co.kr/learn/courses/30/lessons/81301 def solution(s): dic = {"zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five" : 5, "six": 6, "seven": 7, "eight": 8, "nine": 9} for key in dic.keys(): while key in s: s = s.replace(key, str(dic[key]))...
import turtle from random import randrange ## ##def tree(branch_len, t): ## if branch_len > 5: ## t.forward(branch_len) ## t.right(20) ## tree(branch_len - 15, t) ## t.left(40) ## tree(branch_len - 15, t) ## t.right(20) ## t.backward(branch_len) ## ## ##def main(): ##...
"""reduce(func,iterable)合并减少 来自functools """ from functools import reduce scores = [88,74,67,53,24,78] summ = 0 for x in scores: summ += x print(summ) def func(x,y): return x+y print(reduce(func,scores)) print(sum(scores)) print(reduce(lambda x,y:x+y,scores))
def get_available_directions(x,y) : """ In: x and y Out: available directions This function is only used by other functions to get the direction the player is allowed to move in. """ south = True north = True east = True west = True if y == 1 or (x == 3 and y == 2) : ...
""" This module provide a class to manage IO files """ import re import os import sys import subprocess class FileManager: """ This class is used to manage the files that can be read or write by the generator """ def __init__(self, filename="", path="", extension="", content="", encoding="utf-8"): ...
# -*- coding: utf-8 -*- # AUTHOR = "tylitianrui" class Solution: """ @param a: An integer @param b: An integer @return: The sum of a and b """ def aplusb(self, a, b): # write your code here carry = 1 while carry: s = a ^ b carry = 0xFFFFFFFF & (...
def is_sub_without_mistake(trie, sentence): for letter in sentence: if letter == " ": place_in_word = 0 if letter in trie.keys(): trie = trie[letter] else: return [] if "end" in trie: return trie["end"] def intersection(lst1, lst2...
# import pandas as pd """ IE Titanic utils. """ __version__ = "0.1.0" import pandas as pd def tokenize(text, lower=False, remove_stopwords=False, remove_punctuation=False): if lower: text=text.lower() if remove_stopwords: stopwords = ["a", "the", "or", "and"] words= text.split() ...
# -*- coding: utf-8 -*- """ Created on Tue Nov 5 12:56:29 2019 @author: yihua """ import numpy as np array = lambda n=100: list(np.random.randint(1,100,n)) ''' 3. 快速排序 - Quicksort 快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均 比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。 时间复杂度:O(nlogn) 空间复杂度:O(nlogn) ''' def quick...
import tempfile # Create a temporary file and write some date to it fp = tempfile.TemporaryFile() fp.write(b'Hello world') # Read data from file fp.seek(0) print(fp.read()) # Close the file, it will be removed fp.close() # Create a temporary file using a context manager with tempfile.TemporaryFile() as f_p: f_p.w...
x = int(input("Введите натуральное число: ")) n = "" while x > 0: y = str(x % 2) n = y + n x = int(x / 2) print(y, n, x) print(n)
# -*- coding: utf-8 -*- """ Created on Tue Apr 2 22:45:19 2019 @author: yangq """ #Add argument exercise import argparse parser=argparse.ArgumentParser(description="This is an exercise") parser.add_argument("integer",help="Add an integer",type=int) parser.add_argument("--verbose","-v",action="count",help=...
''' automatic operation 1.summation 2.subtraction 3.multiplication 4.Quotient 5.remainder 6.Quotient + remainder ''' x,y = input().split() a = int(x) b = int(y) k = a/b print(a + b) print(a - b) print(a * b) print(a // b) print(a % b) print('%.2f'%(k))
''' find the maximum number of swap in heap sort ''' ''' To find the maxmimum number of swap in heap the smallest integer which is 1 has to be located in the last spot and the maximum value has to be located right next one and change to parent node ''' # Size of heap n = int(input()) # Default size...
''' The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add. Two integers are less than 100,000,000. ''' # Decide how ma...
''' find hamming distance and DNA which has the smallest hamming distance ''' # two values # x is how many DNA will be typed # y is size of DNA x,y = map(int,input().split()) # Empty list dna = [] # Empty string result = '' hamming_D = 0 for i in range(x): dna.append(input()) for i in range(y): # Becuase we have ...
''' Return bigger number Q1063 ''' def biggerNum(arg1, arg2): a = int(arg1) b = int(arg2) if a > b: print(a) else: print(b) #x,y = input().split() #biggerNum(x,y) ''' Return the smallest number among three different int Q1064 ''' def smallerNum(arg1, arg2, arg3): ...
''' Cutting cable We have K cables but We want to make N cables with same length by using K cable. Find the maximum length of cable to make N cables. input example 4 11 802 743 457 539 output example ''' # import sys # sys.stdin = open('input.txt') def check(a): cnt = 0 for i in num: ...
import numpy as np from scipy import optimize #input data X = np.array(([3,5],[5,1],[10,2]), dtype = float) #output data Y = np.array(([75],[82],[93]), dtype = float) #scaling of the data X = X/(np.amax(X, axis=0)) Y = Y/100.0 class Neural_Network(object): def __init__ (self): #hyperparameters self.inputLayerS...
# return a dictionary with squares as the keys and the square value of the values as the values squares = ["one", "two", "three", "four", "five"] values = [1, 2, 3, 4, 5] def number_square(squares, values): squares1 = {} for x, y in zip(squares, values): squares1[x] = y **2 return squares1 def main...
# (Fill in the Missing Code?) Replace the ***s in the seconds_since_midnight function so that # it returns the number of seconds since midnight. The function should receive # three integers representing the current time of day. Assume that the hour is a value from # 0 (midnight) through 23 (11 PM) and that the minute a...
# 3.6 (Turing Test) The great British mathematician Alan Turing proposed a simple test # to determine whether machines could exhibit intelligent behavior. A user sits at a computer and does the same text chat with a human sitting at a computer and a computer operating by itself. The user doesn’t know if the responses a...
from Calculator import * def run_test(): """test all the functions""" assert add(2, 3) == 5, "2 + 3 is 5" assert subtract(2, 3) == -1, "2 - 3 is -1" assert multiply(2, 3) == 6, "2 * 3 is 6" assert division(6, 3) == 2, " 6 / 3 is 2" assert square_root(9) == 3, "square_root of 9 is 3" assert...
import random board = [" "]*9 winners = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7,], [2,5,8], [0,4,8], [2,4,6]] xwin = 0 owin = 0 catwin = 0 userRecord = 0 compRecord = 0 catRecord = 0 def userPick(): while True: loc = input("Pick a square (1-9): ") try: int(loc) ...
nombre = input("Ingrese un nombre :") verbo = input("Ingrese verbo :") advervio = input("Ingrese advervio :") adjetivo = input("Ingrese adjetivo :") if verbo == "matar" or "ejecutar" or "eliminar": historia2 = ("Miles de años llevan los gatos preparando la conquista del planeta.\n" "Han sido laborios...
import operator def binaryBytesToHex(byteString) -> str: return hex(int("".join([str(b) for b in byteString]), 2)) def hamming(str1, str2): assert len(str1) == len(str2) # ne = str.__ne__ ## this is surprisingly slow ne = operator.ne return sum(map(ne, str1, str2))
import csv from itertools import zip_longest #Create rows row_one = [1,2,3,4,5,6,7,8,9,10] row_two = [11,12,13,14,15,16,17,18,19,20] combined_list = [] combined_list.append(row_one) combined_list.append(row_two) print(combined_list) #zip longest is used for transpose of a column data = zip_longest(*combined_list) ...
class ListNode: def __init__(self, x): self.value = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: # 利用快慢指针确定是否存在环 # 遍历改变节点的值 slow = fast = head while fast and fast.next: fast = fast.next.next slow = slow.n...
"""" Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays """ from typing import * class Solution: def findMedianS...