text
stringlengths
37
1.41M
""" Code Challenge Name: Digit Letter Counter Filename: digit_letter_counter.py Problem Statement: Write a Python program that accepts a string from User and calculate the number of digits and letters. Hint: Store the letters and Digits as keys in the dictionary Input: Python 3.2 O...
# -*- coding: utf-8 -*- """ Created on Sat Apr 14 15:39:01 2018 @author: Administrator """ import matplotlib.pyplot as plt x_values = list(range(1, 5000)) y_values = [x**3 for x in x_values] plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='none', s=10) plt.title('cube numbers', fontsize...
#!/usr/bin/env python3 # _*_ coding:utf-8 _*_ import random def select_sort(lis, n): count1 = 0 count2 = 0 for i in range(n): minimum = i # 遍历列表,找到最小值 for j in range(n - 1, i - 1, -1): count1 += 1 if lis[j] < lis[minimum]: minimum = j ...
# Gray Level Slicing by preserving background import numpy as np import scipy.misc as misc import matplotlib.pyplot as plt def grayslicing(image, a, b): (rows, cols) = image.shape graysliced_image = np.zeros((rows, cols)) for i in range(rows): for j in range(cols): # If the pixel valu...
# Huffman Encoding def huffman(probabilities): if(len(probabilities) == 2): return dict(zip(probabilities.keys(), ['0', '1'])) # Create a new distribution by merging lowest prob. pair p_copy = probabilities.copy() a1, a2 = lowest_prob_pair(probabilities) p1, p2 = p_copy.pop(a1), p_copy.pop...
import time def calculate_time(func): def wrapper(): x = time.time() # save first time as x, before start of function func() print(f'Total time {time.time() - x}') return wrapper """ Caculate Time Calculate the time to execute any given function Parameter -------- func Any given function Return ------- w...
#%% [markdown] # ## Decision Tree # * Decision-tree is one of supervised learning algorithms. # * It work for both classification and regression. # * It can be used to visually and explicitly represent decision. # * types of Decision tree # ** Categorical Variable Decision Tree Eg: Student will play cricket or not # **...
# Get prime factor of a number import math def is_prime(prime): for i in range(2, math.ceil(math.sqrt(prime))+1): if(prime % i == 0) and (i != prime): return False return True def find_next_prime(num,prime): prime = prime + 1 while (not is_prime(prime)): prime += 1 ret...
# -*- coding:utf-8 -*- # 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 # 考察二进制编码:原码、反码、补码 # 计算机中数据的存储形式是反码 # 位运算符: class Solution: def NumberOf1(self,n): count = 0 if n<0: n = n &0xFFFF # 限定位数 while(n): count +=1 n = (n-1)&n return count # 测试 s= Solution() ...
# -*- coding:utf-8 -*- # 请实现两个函数,分别用来序列化和反序列化二叉树 # 关键词:序列化、反序列化、二叉树 # 序列化:指遍历二叉树,输出节点数据序列 # 反序列化:由节点数据序列构建二叉树 # 思路:序列化:通过BFS遍历来存储每个节点,但未None时,该节点用'#'代替,从而构建序列 # 反序列:通过两个队列来实现,分别是数据队列和结点队列;对节点队列的每个节点, # 每次弹出数据队列两个元素来构建节点的左右子节点。 class TreeNode: def __init__(self, x): self.val = x...
# -*- coding:utf-8 -*- # 将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能, # 但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 # 数值为0或者字符串不是一个合法的数值则返回0。 # 考察综合能力:能够分析边界条件、是否熟悉ASII码 # 分析边界条件: # 数据上下 溢出 # 空字符串 # 只有正负号 # 有无正负号 # 错误标志输出 class Solution: def method1(self,s): #借助乘法来实现 n = len(s) if ...
# -*- coding:utf-8 -*- # 从上往下打印出二叉树的每个节点,同层节点从左至右打印。 # 考察二叉树的遍历:宽度优先遍历,基于队列来实现 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here f...
# -*- coding:utf-8 -*- # 写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。 # 考察位运算符 class Solution: def Add(self, num1, num2): # write code here while(num1&num2): a = num1 ^ num2 b = (num1 & num2) << 1 num1 = a num2 = b return num1 # 测试 num1 = -1 num2 ...
# Exercise 5: Take the following Python code that stores a string: # str = 'X-DSPAM-Confidence:0.8475' # Use find and string slicing to extract the portion of the string after the colon character # and then use the float function to convert the extracted string into a floating point number. str = 'X-DSPAM-Confidence:0...
# Exercise 1: Write a program which repeatedly reads numbers until the user enters “done”. # Once “done” is entered, print out the total, count, and average of the numbers. # If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number...
def mul13(): k1=int(input()) if k1%13==0: print('yes') else : print('no') try: mul13() except: print('invalid')
m=input("enter input") flag=0 for j in range(0,len(m)): if(m.count(m[j])>1): flag=flag+1 if(flag==0): print("yes") else: print("no
if int(input("Enter Number"))%7==0:print2("yes") else:print2("no")
def findArmstrong(a, b) : for i in range(low + 1, b) : x = i n = 0 while (x != 0) : x = x / 10 n = n + 1 pow_sum = 0 x = i while (x != 0) : digit = x % 10 pow_sum = pow_sum + math.pow(digit, n) ...
m=int(input("Enter the numbers:")) if m>1: for i in range(2,m): if m%i==0: print ('Yes') break else: print("no") elif m==1 or m==0: print ('neither prime nor composites')
x,y=input("Enter Two values").split(' ') x,y=y,x print(x,y)
""" Factorial Digit Sum Find the sum of the digits in the number 100! """ # Simple function to produce a factorial def factorial(n): fact = 1 for x in range (1, n): fact *= x return fact # Simple function to produce the sum of the digits in an integer. def sum_digits_int(n): sum = 0 for x i...
""" Maximum Path Sum I From a triangle of numbers, taking an adjacent route from top to bottom, find the maximum total value. """ from string import digits from Tools.common_tools import extract_q_text, create_table # Function to find the max value path of a number triangle. # var tri is a tabular representation...
""" What is the 10 001st prime number? """ from Tools.common_tools import is_prime # Function to count to the nth prime, specifying the limit as the nth prime to count to. # Does not count 1 as a prime number. def count_to_nth_prime(limit): num_primes = 0 y = 1 # ctr while num_primes < limit: y +...
# weight =0.1 # def neural_network(input, weight): # prediction = input * weight # return prediction # # number_of_toes = [8.5,9.5,10,9] # input = number_of_toes[0] # pred = neural_network(input,weight) # print(pred) # import numpy as np # def neural(a,b): # pref = a.dot(b) # return pref # a = np.array...
def remove_dollar_sign(s): ls=list(s) for i in range(len(ls)-1,-1,-1): if ls[i]=="$": del ls[i] s_new='' for i in range(len(ls)): s_new+=ls[i] return s_new s=input('Enter your string you want to remove $ sign : ') print(remove_dollar_sign(s))
# PYTHON FUNDAMENTALS # Alyssa Falshaw # August 16th, 2020 # DATA TYPES: refers to how a given value is classified # Primitive data types # Boolean Values - Assesses true value of something. True and False (uppercase T and F) is_hungry = True has_freckles = False # Numbers - Integers (whole numbers), floating p...
n = int(input()) if n is 0: print(1) else: for i in reversed(range(1, n)): n = n * i print(n)
def sumsOfNNumbers(numbers, n): result = [] for i in range(len(numbers) - n + 1): result.append(sum(numbers[i:i+n])) return result input() numbers = [int(x) for x in input().split(" ")] candidates = [] for i in range(len(numbers)): candidates.append(max(sumsOfNNumbers(numbers, i+1))) print(ma...
l = [int(x) for x in input().split(" ")] if l[0] == 1 and l[1] == 2 and l[2] == 3 and l[3] == 4 and l[4] == 5 and l[5] == 6 and l[6] == 7 and l[7] == 8: print("ascending") elif l[0] == 8 and l[1] == 7 and l[2] == 6 and l[3] == 5 and l[4] == 4 and l[5] == 3 and l[6] == 2 and l[7] == 1: print("descending") else: ...
from enum import Enum, auto class Direction(Enum): UP = auto() DOWN = auto() LEFT = auto() RIGHT = auto() def move(direction, x, y): if direction == Direction.UP: return x, y+1 if direction == Direction.DOWN: return x, y-1 if direction == Direction.LEFT: return x-1, y if direction == Dire...
name = input('what is your name?') Name = input('what is your surname?') age = input('how old are you?') print=(name,Name,age)
# http://www.geeksforgeeks.org/find-minimum-possible-size-of-array-with-given-rules-for-removal/ def min_size(A, k): B = [0] * len(A) for i in range(len(B)): if i < 2: B[i] = i + 1 else: n = B[i - 1] m = 0 while B[i - m - 1] == n and i > m: ...
"gg6549@rit.edu" "Author - Geeta Madhav Gali" import math def findAccuracy(values): """ findAccuracy will find the accuracies of the values: @param: values : contains all the attribute values including the classes """ correctClassification = 0 wrongClassification = 0 #built the model that is obtained from th...
import math class LoanCalculator: ''' Class used to calculate the loan repayment amounts for the user's requirement. ''' # total number of payments n_payment = 36 lender_list = [] selected_lender_list = [] # Input loan_amt = 0.0 # Ouput payment_combine...
# slicing_lab.py # Lisa Ferrier, Python 210: Lesson 03 Exercise def exchange_first_last(seq): '''This function exchanges the first and last items in a sequence ''' seq2 = seq[-1:]+seq[1:-1]+seq[:1] return seq2 def remove_every_other(seq): '''This function removes every other item in a sequence. ''' ...
'''Convert user URLs to items. Use Python 3. ''' import urllib.parse import argparse def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('input_file') args = arg_parser.parse_args() for line in sorted(set(open(args.input_file, 'r'))): parse_result = urllib.parse.u...
import random sviner = [ "ussel", "nederdrægtig", "kujonagtig", "bananformet", "Dummernik din" ] navne = [ "Batman", "Habakuk", "Hexia", "Gnier", "Julemanden", ] egenskaber = [ "Ærværdige", "Ildelugtende", "Kloge", "Dumme", ] def nyt_navn(): navn = ra...
#! /usr/bin/python # PE15 Starting in the top left corner of a 2x2 grid, there are 6 routes (without backtracking) to the bottom right corner. # How many routes are there through a 20x20 grid? # it turns out, that this has a mathematical solution from combinatorics of n choose k where n = 20+20 (the 2 dimensions) and...
import re lines = [] words = [] counts = {} for _ in range(int(input())): lines.append(input()) for _ in range(int(input())): word = input() words.append(word) counts[word]=0 for line in lines: for word in words: patt = r'\b{}\b'.format(word) m=re.findall(patt,line) counts[...
import Tkinter,tkFileDialog import tkMessageBox import sys import pdb def pickfile(path='.'): #add filetypes root = Tkinter.Tk() root.withdraw() f = tkFileDialog.askopenfilename(parent=root,title='Choose a file') # returned f is a tuple # The askopenfile function to creates an file dialog...
def injectArguments(inFunction): """ This function allows to reduce code for initialization of parameters of a method through the decorator(@) notation You need to call this function before the method init in this way: @injectArguments """ def outFunction(*args, **kwargs): _self = args...
text = input() word = input() def search(text, word): if word in text: return "Word found" else: return "Word not found" print(search(text, word))
def min_max(Nprompt, xprompt): while True: try: N = int(input(Nprompt)) except ValueError: print("Kérlek számot adj meg!") continue if isinstance(N, int): break min = 9999999999 max = -999999999 for i in range(N): ...
def korona_coin(fiveprompt, twoprompt, oneprompt): while True: try: five = int(input(fiveprompt)) two = int(input(twoprompt)) one = int(input(oneprompt)) except ValueError: print("Kérem számot adjon meg!") continue if isins...
def chara(widthprompt, charprompt): while True: try: width = int(input(widthprompt)) except ValueError: print("Kérlek szlmot adj meg!") continue if isinstance(width, int): break char = input(charprompt) for i in range(width)...
#기본 도형 그리는 것을 반복문을 사용해서 연습해보겠습니다. import turtle as t t.color('blue') for x in range (3) : t.fd(120) t.lt(120) #방향을 왼쪽으로 설정하면 반시계방향으로 그려짐 화살표 방향을 원래 있던대로 #사각형 t.color('red') for x in range (4) : t.fd (120) t.lt(90) #원 t.color('yellow') t.circle(120)
#!/usr/bin/env python """ Implementing same algorithms in python for prototyping and testing """ import numpy as np import random import unittest def gen_matrix(len): matrix = np.matrix([[random.random() for _ in range(len)] for _ in range(len)]) for i in range(len): matrix[i][i] += len return ma...
""" Represents the camera object, storing position/orientation information @author: Matt Brucker @Author: Adam Novotny """ from math import sin, cos, pi class Camera: def __init__(self, init_pos=[0, 0, 0], init_angle=[0, 0, 0], init_fov=.5*pi): """ Initializes a new Camera object with init_pos, i...
#!/usr/bin/env python3 def sum(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): return num1 / num2 def calculator(): operator = input("Please choose an operator. Valid operators are +, -, /, *.") ...
# -*- coding: utf-8 -*- from math import * a = float(input("Введите a: ")) x= float(input("Введите x: ")) fun = input("Введите функцию которую вы хотите вычислить(G,F,Y): ") p=int(input("Введите сколько считать:")) h=float(input("Введите шаг:")) if (fun == 'G'): for i in range(p): if (10*a*a-51*a*x+5*x*x) ...
# Author : Niroshiman # Descri : Code that generates creates a circle sprite that revolves around an origin # Instru : 1) Require pygame module import pygame from pygame.sprite import Group import sys import program_functions as pf # RGB colors BLACK = (0,0,0) WHITE = (255,255,255) RED = (255,0,0) def run_game(): ...
''' Map reduce ''' ''' map(func,list) : 将传入列表list中的每个元素作为参数传给func执行,返回func返回值构成的新列表 ''' print('===========================Test Map====================================') def f(x): return x * x r = map(str, [1,2,3,4,5]) r2 = [x * x for x in [1,2,3,4,5]] for x in r : print(x) for x in r2: print(x) ''' reduc...
#!/usr/bin/env python # -*- coding: utf-8 -*- # encuesta.py: Utilería para procesar datos de encuestas en formato CSV # Alberto Pacheco © 2016 (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ import csv import traceback class Resultados: 'Clase auxiliar para empaquetar resultados de Encuesta.f...
import random #Calcula o phi_n do numero primo n def phi_n(numero): if(primo(numero)==True): return numero-1 else: return False #Verifica se um numero eh primo def primo(num): i=1 temp=0 while(i<=num): if(num%i==0): temp=temp+1 i=i+1 if(temp==2): ...
print (' ////****** 13 Mei 2018 PT.MrvDevelopment ********\\\ ') print (' Aplikasi Math System Version 1.0 ') print (" Pilih Pelajaran Matematika Yang Anda Butuhkan" ) def menu(): print "Menu Pilihan:" print print "1.","anutias" print "2.","barisanaritmeti...
""" Program to calculate and display a user's bonus based on sales. If sales are under $1,000, the user gets a 10% bonus. If sales are $1,000 or over, the bonus is 15%. Rehashed version to support function calls """ def calculation(sales): #takes user input and applies some math to it before returning the data bac...
""" Path planning Sample Code with Randomized Rapidly-Exploring Random Trees (RRT) author: AtsushiSakai(@Atsushi_twi) """ import math import random import matplotlib.pyplot as plt import numpy as np import timeit import copy from rrt_dubins import dubins_path_planning show_animation = False class RRT: """ ...
def soma(a, b, c): res = a+b+c print(res) a = int(input('Digite um número: ')) b = int(input('Digite um número: ')) c = int(input('Digite um número: ')) #print(soma(a, b, c)) soma(a, b, c)
from calculate_estates import School, Hospital from consumers import House, FlatHouse houses = [] flat_houses = [] flat = [] school = [] hospital = [] house_piece = int(input("Házak száma: ")) flat_house_piece = int(input("lakások száma: ")) school_piece = int(input("Iskolák száma: ")) hospital_piece = int(input("Kór...
""" 区分以下类型哪些是容器序列哪些是扁平序列,哪些是可变序列哪些是不可变序列: list tuple str dict collections.deque 答: 容器序列和扁平序列的区别是容器序列可以存储多种类型的元素,扁平序列只能容纳一种基础类型(因此在内存分配上更紧凑) 容器序列有: list, tuple, dict, collections.deque 扁平序列有: str 可变/不可变序列的区分方式主要有两个: 1. 是否可以对序列进行修改 2. 看似可以修改的序列,修改后的内存地址是否改变,改变了其实是说明另起一块内存进行保存而已 可变序列有: lise, dict, collections.d...
from graph import Graph from util import Queue # def earliest_ancestor(ancestors, starting_node, has_parent=False): # for parent, child in ancestors: # if child == starting_node: # return earliest_ancestor(ancestors, parent, True) # return starting_node if has_parent == True else -1 ...
name = raw_input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) # Create empty dictionary dict = {} most_occurences = 0 name = "" list = [i.split()[1] for i in handle.readlines() if i.startswith("From") and i.find("@")>0 and len(i.split())>2] for i in list: if not dict...
import json import urllib address = raw_input('Enter location: ') if len(address) < 1 : quit() url = urllib.urlopen(address) data = url.read() comments = json.loads(str(data)) #print json.dumps(comments, indent=4) #print 'Commentor Count:', len(comments) counts = comments['comments'][1]['count'] #print counts comme...
from abc import ABC, abstractmethod import math import tensorflow as tf import pickle class NetworkHandler(ABC): ''' The NetworkHandler is an abstract class for the handling of neural networks. It defines the optimization and performs the training of a network. ''' def __init__(self): sup...
import re from graceful.errors import ValidationError __all__ = ( 'min_validator', 'max_validator', 'choices_validator', 'match_validator', ) def min_validator(min_value): """Return validator function that ensures lower bound of a number. Result validation function will validate the intern...
# ask for user input (their name) name = str(input("Please enter your name: ")) def vowel(name): # define(def) function for x in name.lower(): for letter in ['a', 'e', 'i', 'o', 'u']: if x == letter: return "Your name has a vowel" return "Your name does not have a vowel" prin...
import datetime as dt from typing import List DATE_FORMAT = '%d.%m.%Y' class Record: """Класс Record предназначен для создания записей.""" amount: int comment: str date: dt.date def __init__(self, amount: int, comment: str, date: str = None) -> None: self.amount = amount self.co...
''' Classes for storage of airport instances First class stores individual instances of classes, second stores every airport in dictionary. Second class also has load function, a get function, as well as 2 functions which allow the calculation of the distance between 2 specified airports ''' import csv from math imp...
# Implementation of the Matrix ADT class Matrix: # Creates a matrix of size numRows x numCols initialized to 0. def __init__(self, numRows, numCols): self._theGrid = [[0 for j in range(numCols)] for i in range(numRows)] # Return the number of rows in the matrix. def numRows(self): retur...
from pylistqueue import Queue class ExpressionTree: # Builds an expression tree for the expression string. def __init__(self, expr_str): self._expr_tree = None self._build_tree(expr_str) def _build_tree(self, expr_str): # Build a queue containing the tokens in the expression string...
def printRev(n): if n > 0: print n printRev(n - 1) def printInc(n): if n > 0: printInc(n - 1) print n printRev(4) printInc(4)
import keras from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import optimizers import os, sys, glob import numpy as np import cv2 def load_image(file): """ Loads an image file and prepares it fo...
import math, sys def entropy(representatives): """ Calculates the entropy of a given set @ representatives: the data set """ rPubs = 0 dCrats = 0 for r in representatives: if r.party == 'R': rPubs = rPubs + 1 else: dCrats = dCrats + 1 ...
''' Neste arquivo estão implentados os algoritmos de: * Inicializacao de grafo conforme a bibliotece networkx * Busca em largura no terminal * Busca em largura com impressao na tela ''' import networkx as nx # graph library import matplotlib.pyplot as plt # matlab plot library import numpy as n...
menu = """ Unit of Temperature : | 1 | Celcius | 2 | Fahrenheit | 3 | Kelvin """ print("Welcome to Simple Converter App".center(80, "=")) while True: print(menu) starting = int(input("Starting Unit [1/2/3] : ")) destination = int(input("Destination Unit [1/2/3] : ")) temperature = float(input...
# -*- coding: utf-8 -*- class SumLikeSchool: def adding_zeros(self, num_str, inp_len): delta = inp_len - len(num_str) zeros = '' for i in range(0, delta): zeros += '0' return zeros + num_str def replace_nth(self, inp_string, new_sym, index_of_new): if i...
""" You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls...
class ValidWordAbbr(object): # static_element = {} this is static var belongs to the class def __init__(self, dictionary): """ initialize your data structure here. :type dictionary: List[str] """ self.abbrDict = {} # this is element belongs to object self for s in...
# coding=utf-8 """ Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values. For example, Given {1,2,3,4}, reorder it to {1,4,2,3}. """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): ...
""" Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. """ class Solution(object): def minPathSum(self, grid): """ :type grid: List[L...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool ...
""" Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = "aab", Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. """ class Solution(object): def minCut...
""" Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. """ class Solution(ob...
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: List[str] """ return self.findWords(0, len(s), s, wordDict, {}) def findWords(self, start, end, s, wordDict, cache): if start in cache: ...
""" Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 ...
""" Write a function to generate the generalized abbreviations of a word. Example: Given word = "word", return the following list (order does not matter): ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4" """ class Solution(object): def generateAbbr...
# coding=utf-8 # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ...
# coding=utf-8 __author__ = 'yusizhang' """ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place, do ...
# coding=utf-8 __author__ = 'yusizhang' class Solution(object): """ Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. """ def majorityElement(self, nums): """ :type nums: List[int] ...
""" Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . You may assume that the given expression is always valid. Some examples: "1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4...
__author__ = 'yusizhang' # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): """ Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume t...
__author__ = 'yusizhang' class Solution(object): """ Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements i...
class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ # sort the citations descending order --> this is wrong since it just returns the sorted array, but not sort the original array! # sorted(citations, reverse=True) ...
""" Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) The solution set must not contain duplicate ...
def Hello(): print("hello") if __name__ == "__main__": #HangMan() pass import pygame import os import sys pygame.init() startRow = 20 startPos = 10 spacing = 20 width = 600; height = 400 charPos = startPos lineNum = startRow screen = pygame.display.set_mode((width, height)) font = pygame.font.SysFont...
# Chapter 4 ; Selfinterest excercise def rot13_5(myText): # An Easter egg in Python is "The Zen of Python" accessible by using <import this> import this if (len(myText) == 0): myText = "Shannon:\nOk, I had an error in my code but I finally figured it out.\n" myText += "This is encrypted using s...
# SAMS Python Chapter 8 Quiz and Excercise # Using Functions to Create Reusable Code, pp 81 - 94 # ------------ # History: # ------------ # 04/28/2020 - added page number reference for this excercise module # added Hisotry section. # 04/17/2020 - created and completed # ------------ # Que...
# Chapter 4 ; Selfinterest excercise def rot13_5(myText): # An Easter egg in Python is "The Zen of Python" accessible by using <import this> import this #myText="" if (len(myText) == 0): myText = "Shannon:\nOk, I had an error in my code but I finally figured it out.\n" myText += "This is e...
# ###################### #SAMS Python chapter 11: student.py # ###################### class Student(object): #Always use <self> and <attr> that you want to initialize as attributes #in the __init__(). def __init__(self, name="", school="", grade="", ...