text
stringlengths
5
121k
def two_sum(NumList): listOfNums = NumList count = 0 target = int(input('What\'s the target')) listLength = len(listOfNums) for m in range(0, listLength): for n in range(m+1, listLength): if listOfNums[m]==listOfNums[n]: continue ...
print("Currency Converter(Only Dollars And Indian Rupees)") while True: currency = input("($)Dollars or (R)Rupees:") if currency == "$": amount = int(input('Enter the amount:')) Rupees = amount * 76.50 print(f"${amount} is equal to: ₹{Rupees}") elif currency.upper() == "R": a...
""" 题目:暂停一秒输出,并格式化当前时间。 程序分析:无。 """ import time print(time.strftime("%y-%m-%d %H:%M:%S",time.localtime(time.time()))) time.sleep(1) print(time.strftime("%y-%m-%d %H:%M:%S",time.localtime(time.time()))) myD = {1:'A',2:'B'} for key ,value in dict.items(myD): print(key,value) time.sleep(1)
def yunsuan(userA, userB, operate): '运算函数' try: A = int(userA) B = int(userB) operate_list = {'+': (A + B), '-': (A - B), '*': (A * B), '/': (A / B)} return operate_list[operate] except KeyError: return '%s 没有这个运算' % operate except ValueError: return '...
from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import datasets iris = datasets.load_iris() print("Iris Data set loaded...\n\n") x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size =0.1) print("Dataset is split into ...
months = ['january','february', 'match', 'april', 'may','june','july','august','september','october','november','december'] print(months) for month in months: print(month.title() + "\n") print("go for next month:") print("GOODBYE!!!!")
code = input("Please enter the coded text") distance = int(input("Please enter the distance value")) plainText = '' for ch in code: ordValue = ord(ch) cipherValue = ordValue - distance if(cipherValue < ord('a')): cipherValue = ord('z') - (distance - (ord('a') - ordValue + 1)) plainText += chr(ci...
from Archivo import Carga from MatrizOrtogonal import MatrizOrtogonal class Menu: def __init__(self): self.archivo = "" self.ruta = "" self.nombre_terreno = "" self.obj = "" self.obj_Lista = "" self.matriz = "" def menu(self): opcion = 0 ...
from NodoOrtogonal import Nodo class Lista_V: def __init__(self): self.primero = None self.ultimo = None self.size = 0 def vacia(self): return self.primero == None def insertar(self, dato, x, y): nodo_nuevo = Nodo(dato, x, y) if self.vacia() == True: ...
while True: prompt = "%s words: " % 3 sentence = input(prompt) sentence = sentence.strip() words = sentence.split(' ') print(sentence)
''' Using string slicing, take in the user's name and print out their name translated to pig latin. For the purpose of this program, we will say that any word or name can be translated to pig latin by moving the first letter to the end, followed by "ay". For example: ryan -> yanray, caden -> adencay ''' user_name =...
import random import math def hill_climb(domain, cost_func): sol = [random.randint(domain[idx][0], domain[idx][1]) for idx in range(len(domain))] while True: neighbors = [] for j in range( len(domain) ): if sol[j] > domain[j][0]: ...
from tkinter import * from tkinter import messagebox window = Tk() window.title("Verify Form") window.geometry("540x340") window.resizable(False, False) window.config(bg="red") user_pass = {'Ghiyaath': 'Zaeemgee', 'Jaydenmay': 'jaydenmay', 'Shuaib': 'Biggun', 'Zoe': 'Foodislife'} entry1 = Label(window,...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def ReverseList(self, pHead): if pHead == None or pHead.next == None: return pHead pre = self.ReverseList(pHead.next) pHead.next.next = pHead pHead.next = None ...
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ ep = len(nums) - 1 for i in range(len(nums)-1,-1,-1): if nums[i] + i >= ep: ep = i return ep == 0
class Types_and_Strings: def __init__(self): pass def play_with_strings(self): message = input("Enter your name: ") print("\nOriginally entered: "+ message) print('\nfirst letter:'+message[:1]) print('\nlast letter:'+message[-1:]) ...
import asyncio import platform from asyncio import sleep as asyncio_sleep from time import monotonic, perf_counter PLATFORM = platform.system() WINDOWS = PLATFORM == "Windows" if WINDOWS: time = perf_counter else: time = monotonic if WINDOWS: from ._win_sleep import sleep as win_sleep ...
class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ intervals.sort(key=lambda x: x.start) merged_intervals = [] for interval in intervals: if not merged_intervals: ...
class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ if not intervals: return [newInterval] elif newInterval.end < intervals[0].start: retu...
class Solution(object): def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ if not nums: return 0 left = right = 0 total = 0 min_len = 10 ** 8 for right in range(len(nums)): ...
class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if not root: return None if root.val == p.val: return root ...
class Solution(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if not root: return False if not root.left and not root.right: return sum == root.val ...
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ triangle = [] current_line = [] for i in range(numRows): if not current_line: current_line.append(1) triangle.ap...
class Solution(object): def wordBreak(self, s, wordDict): """ Basic dynamic programming :type s: str :type wordDict: Set[str] :rtype: List[str] """ f = [[] for i in range(len(s)+1)] for i in range(len(s)): if f[i]...
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ res = '' if not strs: return res for i in range(len(strs[0])): char = strs[0][i] flag = True for j in range(1, len(strs...
class Solution(object): def maxPathSum(self, root): """ Memorized search :type root: TreeNode :rtype: int """ if not root: return 0 self.max_num = -1000000000000 f = {} def memorized_search(root): if not roo...
class Solution(object): def get_node_num(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 return self.get_node_num(root.left) + self.get_node_num(root.right) + 1 def kthSmallest(self, root, k): """ The main id...
class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ array = sorted(citations, reverse=True) index = citation = 0 for index, citation in enumerate(array): if citation < index + 1: ret...
letras = ['D', 'N', 'A'] def lex(l, n, m = ''): print(m) if n == 1: for i in l: m += i return(m) else: for i in l: lex(l, m+i, n-1) print(lex(letras, 1))
import turtle square = turtle.Turtle() wn = turtle.Screen() def drawSquare(turtle, size, totalSquares): rotationAngle = 360/totalSquares for i in range(totalSquares): square.right(rotationAngle) for i in range(4): square.forward(size) square.right(90) drawSquare(...
import math def mySqrt(n): initialGuess = n/2 for i in range(10): newGuess = (1/2)*(initialGuess + (n/initialGuess)) initialGuess = newGuess count = i + 1 print("Guess #", count,": ", newGuess) trueSQRT = math.sqrt(n) print("True Square root value = ", trueSQRT) pr...
import random count = 1 print("2") for i in range(10): number = random.randint(25,35) print("Loop: ",count," Random Number: ", number) count += 1
import turtle import math print("Two Questions:") print("A) Write a loop that prints each of the numbers on a new line. ") print("Here is my solution.... ") for i in [12, 10, 32, 3, 66, 17, 42, 99, 20]: print("Value is ", i) print("") print("B) Write a loop that prints each number and its square on a new line. ...
""" Created by Roman Polishchenko at 12/9/18 2 course, comp math Taras Shevchenko National University of Kyiv email: roma.vinn@gmail.com """ import time def matrix_chain_dynamic(dimensions, n): """ Dynamic Programming Python implementation of Matrix Chain Multiplication - build the worst sequence of brack...
array = [5,7,9,0,3,1,6,2,4,8] def quick_sort(array, start, end): if start>=end: return pivot = start left = start+1 right = end while left<=right: while left<=end and array[left]<=array[pivot]: left+=1 while right>start and array[rig...
""" ------------------------------------------------------- Sudoku class ------------------------------------------------------- Section: CP468 ------------------------------------------------------- """ import itertools rows = characters = "ABCDEFGHI" cols = numbers = "123456789" class sudoku: def __init__(...
import random import urllib.request def download_image(url): name = random.randrange(1,100) file_name = str(name) + ".jpg" urllib.request.urlretrieve(url,file_name) print("Enter the URL:-") x = input() download_image(x) print("Image Downloaded Please Check Folder")
year = int(input("Enter Year")) if year < 1000 and year > 9999: print("Wrong Year") else: if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): print("Leap year") else: print("Not a Leap Year")
number = int(input("Enter Number")) def prime(num): count = 1 for i in range(1, num): if num % i == 0: count += 1 if count > 2: break if count == 2: return True return False def factor(x): for i in range(1, x+1): if x % i == 0 and prime(i)...
''' Given a mixed array of number and string representations of integers, add up the string integers and subtract this from the total of the non-string integers. Return as a number. ''' def div_con(x): strtot = 0 digitot = 0 for ch in x: if isinstance(ch, str)...
def main(): N = int(input()) tasks = [] for i in range(N): tasks.append(list(map(int, input().split()))) tasks.sort(key=lambda x: x[1]) t = 0 for task in tasks: t += task[0] if t > task[1]: print('No') return print('Yes') if __name__ == "__main...
S = input() if '.' in S: ans, _ = S.split('.') print(ans) else: print(S)
class union_find: def __init__(self, N): self.par = [i for i in range(N)] def root(self, i): if self.par[i] == i: return i else: self.par[i] = self.root(self.par[i]) return self.par[i] def same(self, a, b): return...
""" Question: Find the amount of coins required to give the amount of cents given The second function gets the types of coins whereas the first one only gives the total amount. """ def coin_number(cents): coinlist = [25, 10, 5, 1] coinlist.sort(reverse=True) """ list must be in descending order ...
""" Solves for pi given random numbers between 0 and 1 """ from random import random def dist_from_origin(x,y): return (x**2 + y**2)**0.5 in_circle = 0 step = 100000 for i in range(step): x = random() y = random() if dist_from_origin(x,y) <= 1: in_circle += 1 print(4 * in_circle/step)
newList = [12,35,9,56,34] def swapList(newList): size = len(newList) temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList print("list after swapping:",swapList(newList))
a,b,c,d = list(map(int, input().split())) print ("YES" if a+b+c == d or a+b+d==c or b+d+c == a or c+a+d == b or a+b == c+d or a+c == b+d or d+a == b+c else "NO" )
math = input().split('+') math.sort() for i in range(len(math)): print (math[i], end='') if i!=len(math)-1: print ('+', end='')
def getSize(size): counter = 0 while size > 1024: counter += 1 size /= 1024 size = round(size, 2) if counter == 0: size = str(size)+"bytes" elif counter == 1: size = str(size)+"KB" elif counter == 2: size = str(size)+"MB" elif counter == 3: siz...
class Solution: def divide(self, dividend: int, divisor: int) -> int: def binary2decimal(binary): i = 1 sum = 0 for bit in binary[::-1]: sum += i if bit == '1' else 0 i <<= 1 return sum def binarySub(d1, d2): ...
arr = [ 2, 4, 5, 5, 6, 7, 11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 16, 18, 19, 19, 19, 22, 22, 23, 27, 29, 29, 30, 31, 33, 37, 38, 38, 38, 39, 39, 40, 40, 41, 42, 42, 43, 43, 46, 46, 50, 50, 52, 55, 57, 57, 57, 58, 59, 59, 59, 59, 59, 60, 62, 65, 65, 65, 67, 68, 68, 68, 68, 71, 73, 73, 73, 73, 73, 73...
a0 = int(input("Input a positive int: ")) print(a0) while a0 != 1: if a0 % 2 == 0: a0 = a0/2 print(int(a0)) elif a0 % 2 != 0: a0 = 3*a0+1 print(int(a0))
def open_file(filename): '''A function which tries to open the file and return it if the file is found. Otherwise it prints out error message''' try: opened_file = open(filename,"r") return opened_file except FileNotFoundError: print("File {} not found".format(filename)) def m...
def add_word(): word = "" while word != "x": word = input("Enter word to be added to list: ") if word != "x": first_list.append(word) def word_list(): for word in first_list: if len(word) > 1: if word[0] == word[-1]: second_list.append(word) ...
def sum_number(n): '''A function which finds the sum of 1..n and returns it''' sum_of_range = 0 for num in range (1,n+1): sum_of_range += num return sum_of_range def product(n): '''A function which finds the product of 1..n and returns it''' multi = 1 for num in range(1,n+1): ...
def open_file(filename): opened_file = open(filename,"r") return opened_file def make_list(opened_file): file_list = [] for lines in opened_file: split_lines = lines.split() file_list.append(split_lines) return file_list def count_words(file_list): word_count = 0 punctua...
num = int(input("Input an int: ")) while num > 0: print(num) num -= 1
def remove_whitespaces(opened_file): for line in opened_file: print(line.strip().replace(" ", ""), end = "") return True file_name = input("Enter filename: ") opened_file = open("data.txt", "r") readfile = remove_whitespaces(opened_file) print(readfile)
def find_and_replace(string,find_string,replace_string): if find_string in string: final_string = string.replace(find_string,replace_string) return final_string else: print("Invalid input!") def remove(string,remove_string): if remove_string in string: final2_string = stri...
dog_age = int(input("Input dog's age: ")) human = 16 if 0 < dog_age < 17: human_count = dog_age * human - (dog_age*dog_age*dog_age) print("Human age:", int(human_count)) else: print("Invalid age") if 1 < dog_age < 17: human_age = human + dog_age * 4 + 1 print("Human age:", human_age) elif dog...
''' Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. Examples "()" => true ")(()))" => false "(" => false "(())((()())())" => true Con...
''' Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata. ''' def reverse_alternate(string): words = string.s...
import numpy as np import util import pdb def main(train_path, valid_path, save_path, save_img): """Problem: Logistic regression with Newton's Method. Args: train_path: Path to CSV file containing dataset for training. valid_path: Path to CSV file containing dataset for validation. sav...
""" Continued fractions. """ from decimal import Decimal from fractions import Fraction class CFraction(list): """ A continued fraction, represented as a list of integer terms. """ def __init__(self, value, maxterms=15, cutoff=1e-10): if isinstance(value, (int, float, Decimal)): ...
def quick_sort(a_list): quick_sort_helper(a_list, 0, len(a_list)-1) def quick_sort_helper(a_list, first, last): if first < last: split_point = partition(a_list, first, last) quick_sort_helper(a_list, first, split_point-1) quick_sort_helper(a_list, split_point+1, last) def partition(a...
total = 99 for number in range(1, 100): if number % 7 == 0: continue else: string = str(number) if string.endswith('7'): continue total -= 1 print("从1数到99共拍腿", total, "次.")
str = 'abc_ABC' lower = str.lower() upper = str.upper() print(str) print(lower) print(upper)
coffeename = ('蓝山', '卡布奇诺', '慢的宁') for name in coffeename: print(name, end=" ") print() tuple1 = coffeename print("原元组:", tuple1) tuple1 = tuple1 + ("哥伦比亚", "麝香猫") print("新元组:", tuple1)
dictionary = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} print(dictionary) print(dictionary['key1'])
def fun_bmi(height, weight, person='路人甲'): '''功能: 根据身高和体重计算BMI指数 person:姓名 height:身高,单位:米 weight:体重,单位:千克 ''' print(person + '的身高:' + str(height) + "米 \t 体重: " + str(weight) + "千克") bmi = weight / (height ** 2) print(person + "的BMI指数为:" + str(bmi)) if bmi < 18.5: print(...
from gpiozero import Button, LED from time import sleep from random import uniform from os import _exit led = LED(4) right_button = Button(14) left_button = Button(15) left_name = input('Left player name is: ') right_name = input('Right player name is: ') led.on() sleep(uniform(5, 10)) led.off() def pressed(button)...
from sys import maxsize def maxSequence(a,size): max_mexri_stigmhs = -maxsize - 1 max_teliko = 0 arxi = 0 telos = 0 s = 0 for i in range(0,size): max_teliko += a[i] if max_mexri_stigmhs < max_teliko: max_mexri_stigmhs = max_teliko ...
class Car: def infor(self): print("This is a car") car = Car() car.infor() isinstance(car, Car) isinstance(car, str) if 5 > 3: pass class A: def __init__(self, value1=0, value2=0): self._value1 = value1 self.__value2 = value2 def setValue(self, value1, valu...
def get_names(): with open("guest_list.txt", "a") as file_object: while True: name = input('What is your name? ("q" to quit): ') if name != "q": file_object.write(f"{name}\n") else: break get_names()
class User: def __init__(self, first_name, last_name, age): self.f_name = first_name self.l_name = last_name self.age = age self.login_attempts = 0 def describe_user(self): print(f"\nUser info:\nFirst name: {self.f_name}\n" f"Last name: {self.l_nam...
class Restaurant: def __init__(self, name, cuisine): self.name = name self.cusine = cuisine self.open = True def describe_restaurant(self): print(f"{self.name} is a {self.cusine} restaurant.") def open_restaurant(self): if self.open == True: p...
with open("learning_python.txt") as file: contents = file.read() print(contents.strip()) file = "learning_python.txt" with open("learning_python.txt") as file: for line in file: print(line.rstrip()) print("") with open("learning_python.txt") as f: for l in f: lines = f.readl...
class User: def __init__(self, first_name, last_name, age): self.f_name = first_name self.l_name = last_name self.age = age def describe_user(self): print(f"\nUser info:\nFirst name: {self.f_name}\n" f"Last name: {self.l_name}\n" f"Age: {self...
taken_poll = ["bill", "george", "john", "fred", "kieth"] favorite_numbers = {taken_poll[0]: 10, taken_poll[1]: 7, taken_poll[2]: 55, taken_poll[3]: 30, taken_poll[4]: 100} index = 0 for friend in taken_poll: print(f"{frien...
class Restaurant: def __init__(self, name, cuisine): self.name = name self.cusine = cuisine self.open = True def describe_restaurant(self): print(f"{self.name} is a {self.cusine} restaurant.") def open_restaurant(self): if self.open == True: p...
def make_shirt(size, color): print(f"Made shirt that is {color} and size {size.upper()}.") make_shirt('m', 'red') make_shirt(color='blue', size='l')
import itertools a = [int(x) for x in input().split(',')] b = [int(x) for x in input().split(',')] print(' , '.join(str(t) for t in itertools.product(a,b))) lines = int(input()) for _ in range(lines): a,b = input().split() try: print(int(a) // int(b)) except (ZeroDivisionError, ValueError) as e: print(...
def is_prime(num): for i in range(2,num): if num % i ==0: return False return True def next_prime(num): if not is_prime(num): n = num + 1 while not is_prime(n): n += 1 return n else: return num print(next_prime(6))
""" Truncates string or JSON data so that it fits a specific number of characters. """ __author__ = "Jakrin Juangbhanich" __email__ = "juangbhanich.k@gmail.com" def truncate(message: str, max_length: int=128, split_ratio: float=0.8) -> str: """ Truncates the message if it is longer than max_length. It will be ...
number_1= input ("Enter a first number") number_2= input ("Enter a second number") if float(number_1)> 10 and float(number_2)>10: print("Both numbers are greater than 10.") else: print("At least one of the numbers you entered is not greater than 10")
first_number= input("Enter a first number") second_number= input("Enter a second number") result= float(second_number)-float(first_number) if result>10: print("The result is greater than 10.") elif result>0: print("The result is greater than 0 but not than 10.") elif result==0: print("The result is zero.") ...
""" Created on Fri Dec 21 23:38:34 2018 Decimal to hexatrigesimal calculator. convert decimal number to base 36 encoding; use of letters with digits. @author: susan """ def dec_to_base36(dec): """ converts decimal dec to base36 number. returns ------- sign+result """ chars =...
''' Python imports. ''' import random import string import re from rest_framework import status def capitalize_name(input_name): """ Method to capitalize first character of name. If '.' is present in string then first character of every list element after splitting input string by '.' is capitaliz...
import matplotlib.pyplot as plt import numpy as np from scipy.stats import binom, norm, beta NUM_PTS = 20 p_grid = np.linspace(start=0, stop=1, num=NUM_PTS) prior = [1] * NUM_PTS likelihood = binom.pmf(k=6, n=9, p=p_grid) unnormalized_posterior = likelihood * prior posterior = unnormalized_posterior / sum(u...
from connector import * class LC: def __init__(self, name): self.name = name def evaluate(self): return class Not(LC): def __init__(self, name): LC.__init__(self, name) self.A = Connector(self, 'A', activates=1) self.Out = Connector(self, 'Out')...
class node(object): def __init__(self,domain,parent,row,col,value=0): self.domain=domain self.value=value self.row=row self.col=col self.unassigned=True self.parent=parent def deletFromDomain(self,item): self.domain.remove(item) def addItem(self,item): self.domain.append(item) def __str__(self): ...
def getMoneySpent(keyboards, drives, b): keyboards.sort() drives.sort() result=[] for i in range(len(keyboards)): for j in range(len(drives)): if keyboards[i]+drives[j]<=b: result.append(keyboards[i]+drives[j]) elif keyboards[i]+drives[j]>b: ...
import numpy as np import matplotlib.pyplot as plt import scipy.integrate as scig import random as rdm x_initial = 0 x_final = 1/3 num_n = 10000 monte_n = 10000 eta_iter = 4 lin_min = 100 lin_max = ...
import unittest from order import * class TestOrder(unittest.TestCase): @classmethod def setUp(self): ''' Set up class in order to test core functionality associated with orders''' self.new_order = Order( 'Test Cust_Uid', 'Test Pay_Opt_Uid', ...
import math def f(n): divisors = set({1, n}) for i in range(2, math.ceil(math.sqrt(n)) + 1): if (n % i) == 0: divisors.add(i) divisors.add(n // i) return divisors if __name__ == '__main__': print(f(4001)) print(f(2689))
""" List ~~~~~~~~~~~~~~ make a list class. (Alought python has it's built-in list, we will achieve this data structure by ourself. We will only use some basic functions of python so we can display the details of list.) :copyright: (c) 2020 by Xu Hangkun. :license: LICENSE, see LICEN...
def find_max_crossing_subarray(a,low,mid,high): leftsum = - float("inf") sum = 0 for i in range(mid,low-1,-1): sum = sum + a[i] if sum > leftsum : leftsum = sum maxleft = i rightsum = - float("inf") sum = 0 for j in range(mid+1,high+1,1): sum = sum + a[j] if sum > rightsum : rightsum = sum...
def multiply(num1, num2): product = 0 num1_size = len(num1) num2_size = len(num2) for i in range(num1_size-1,-1,-1): zeros1 = (num1_size - 1) - i value1 = int(num1[i]) * (10**zeros1) for j in range(num2_size-1,-1,-1): zeros2 = (num2_size - 1) - j value2 = ...
from tkinter import * from tkinter import messagebox from settings_menu import OthelloSettingsGUI from othello_gui_board import * import othello_game_logic WINDOW_WIDTH = 500 WINDOW_HEIGHT = 500 class OthelloGUI: """ Graphical user interface for Othello game. public attributes: playagain: bool ...
def unique(lst): return len(lst) == len(set(lst)) lst1 = [1, 2, 3, 4, 5, 6, 7] lst2 = [1, 2, 3, 4, 3, 2, 1] print(unique(lst1)) print(unique(lst2))