text stringlengths 37 1.41M |
|---|
"""
梯度可以用来找到局部最优点
f(x)=log(x)的导数只能无限接近0
"""
import numpy as np
import matplotlib.pyplot as plt
# Define function f(x)
def f(x):
return np.log(x)
# compute f(x) for x=-10 to x=10
x = np.linspace(-10, 10, 500)
y = f(x)
# f'(x) using the rate of change
delta_x = 0.0001
y_derivative = (f(x + delta_x) - f(x)) / delt... |
# -- coding = 'utf-8' --
# Author Kylin
# Python Version 3.7.3
# OS macOS
"""
龙格库塔算法
成员变量:
x0: x的初值
xn: x的终值
y0: y的初值
h: 步长
"""
class RungeKutta(object):
x0 = 0.0
xn = 0.0
y0 = 0.0
h = 0.0
def __init__(self, x0, xn, y0, h):
self.x0 = x0... |
# -*- coding:utf-8 -*-
"""
manualGroupby 手动实现groupby的功能
:Author: kylin.smq@qq.com
:Last Modified by: kylin.smq@qq.com
"""
from operator import itemgetter
from collections import defaultdict
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'add... |
# -- coding = 'utf-8' --
# Author Kylin
# Python Version 3.7.3
# OS macOS
"""
近似计算pai与e
"""
import numpy as np
import matplotlib.pyplot as plt
def main():
# 1. 近似求解pai
n = np.sum(1 / np.arange(1, 10000) ** 2)
pai = np.sqrt(n * 6)
print("------The value of pai-------")
print("计算值 = {:.10f}, 真实值 = ... |
"""
积分是微分的逆过程~
"""
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return 2 * x
# Set up x from -10 to 10 with small steps
delta_x = 0.1
x = np.arange(-10, 10, delta_x)
# Find f(x) * delta_x
fx = f(x) * delta_x
# Compute the running sum
y = fx.cumsum()
# Plot
plt.plot(x, y)
plt.xlabel("x")
plt.yl... |
# Finds the sum of all the numbers less than 10**6 which are palindroes
# in both base 10 and base 2
# Checks if an integer is a palindrome
def isPalindrome(int_to_check):
if len(int_to_check) <= 1:
return(True)
elif int_to_check[0] == int_to_check[-1]:
return(isPalindrome(int_to_check[1:-1]))
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 21:59:55 2020
@author: Sahil
"""
import turtle
tur=turtle.Turtle()
tur.color("red")
for i in range(5):
tur.forward(50)
tur.right(90)
tur1=turtle.Turtle()
tur1.color("blue")
for i in range(5):
tur1.forward(50)
tur1.right(144)
... |
import turtle
import random
X = -300
Y = -100
GOAL = 300
colors = ["cyan","coral","mediumblue","greenyellow","black","indigo","darkviolet"]
def draw_goal_line():
t = turtle.Turtle()
t.penup()
t.setposition(GOAL, 300)
t.right(90)
t.pendown()
t.forward(600)
def draw_fresh_penstroke(t):
t.pe... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es>
#
# Distributed under terms of the BSD license.
"""
"""
class Name():
def __init__(self,name=None,lastname=None):
self.firstname=name
self.lastname=lastname
class B... |
#"inheriting from Queue"
#self.item is the thing of items
#self.items is the list itself
import Queue
class Deque(Queue.Queue):
def __init__(self):
super().__init__()#invokes the parent method
def addRear(self, item):
super().enqueue(item)
def removeFront(self):
r... |
from turtle import Turtle
from scoreboard import Scoreboard
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 2
MOVE_INCREMENT = .1
class CarManager(Turtle):
def __init__(self):
self.all_cars = []
super().__init__()
self.ht()
se... |
#!/usr/bin/env python
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
def pow_helper(x,n):
if n==1:
return x
else:
temp = pow_helper(x,n/2)
... |
# 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 generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if... |
# REVERSEDNS.PY checks if the MX records behind the domain has PTR.
# If PTR is missing, the domain's SMTP connection might be rejected due to Reverse DNS test.
# IP TEST
# Modules
import dns.resolver
# Init
mxRecord = None
aRecord = None
ptrRecord = None
maxScore = 0
totalScore = 0
# user input: Domain name
domain... |
def postfix(s):
stack = []
s = s.split()
for i in s:
if i.isdigit():
stack.append(int(i))
elif i == "+":
old = stack.pop()
stack.append(stack.pop() + old)
elif i == "-":
old = stack.pop()
stack.append(stack.pop() - old)
elif i == "*":
old = stack.pop()
stack.append(stack.pop() * old)
e... |
'''
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = 1
if x... |
#LAB 14
#Due Date: 04/05/2019, 11:59PM
########################################
#
# Name: Hojin Ryoo
# Collaboration Statement:
#
########################################
def bubbleSort(numList):
'''
Takes a list and returns 2 values
... |
#Lab #5
#Due Date: 02/08/2019, 11:59PM
########################################
#
# Name: Hojin Ryoo
# Collaboration Statement: I did not work with anyone!
#
########################################
import math
class SodaMachine:
'''
>>> m = Sod... |
from Interop import classes
class MyClass(object):
x = 5
def method(self):
"""effects only the instance of the class"""
return 'instance method called', self
@classmethod
def classmethod(cls):
"""effects the class and instances of that class"""
cls.x = 10
retur... |
"""Creating a class with property decorator"""
class MyProperty(object):
def __init__(self):
self.value = 5
pass
@property
def value_a(self):
return self.value
@value_a.setter
def value_a(self, value):
self.value = value
@value_a.deleter
def value_a(self)... |
def swap(A, i, j):
"""Helper function to swap elements i and j of list A."""
if i != j:
A[i], A[j] = A[j], A[i]
def bubblesort(A):
"""In-place bubble sort."""
if len(A) == 1:
return
swapped = True
for i in range(len(A) - 1):
if not swapped:
break
... |
#programma funzionante
def calcolatrice_di_margini():
a = 0
while a == 0:
print(
'--------------------------------------------------------------------------------------------------------------')
int = input("Cosa voui fare? Se vuoi calcolare i margini premi [m] + invio, se vuoi... |
import os
import re
def camel_case_to_snake(text):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def camel_case_to_hyphenated(text):
""""
CamelCase -> camel-case
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', text)
return re.sub('... |
import math
print("Ievadi skaitli:")
x = int(input())
a = x ** 2 + (x / 2) * 2
print("Atbilde:",int(a)) |
import math
from time import sleep
class Circle:
def __init__(self, x0, y0, x1, y1, R, r,):
self.x0 = x0
self.y0 = y0
self.x1 = x1
self.y1 = y1
self.R = R
self.r = r
if self.x0 > 0 and self.y0 > 0 and self.x1 > 0 and self.y1 > 0 and self.x0 is None:
... |
def longest(word):
stac = []
result = []
length = len(word)
i = 0
while i < length:
current = word[i]
if i == 0:
stac.append(current)
result.append(1)
i+=1
continue
if current not in stac:
if len(stac) and ord(curren... |
# CONSTRUCTOR
# -->A constructor is a special kind of method that Python calls when it instantiates an object using the definitions found in your class
# illustration of Constructor
class Student:
id = 0
name = "Default name"
email = "sample@sample.sample"
schoolName = "Default school name"
no_of_l... |
#!/usr/bin/env python3
class Shape(object):
LIZT = []
def __init__(self):
Shape.LIZT.append(self)
def __str__(self):
return('SHAPE:from __str__: {}'.format(Shape.LIZT))
def __repr__(self):
return('SHAPE: from __repr__: {} {}'.format(self,Shape.LIZT))
class Circle(Shape):
... |
#!/usr/bin/env python3
class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, delta_x, delta_y):
self.x = self.x + delta_x
self.y = self.y + delta_y
class Square(Shape):
def __init__(self, side=1, x=0, y=0):
super().__init__(x,y)
self.__... |
"""cs module: class scope demonstration module."""
mv ="module variable: mv"
def mf():
return "module function (can be used like a class method in " \
"other languages): MF()"
class SC:
scv = "superclass class variable: self.scv"
__pscv = "private superclass class variable: no access"
def __i... |
class Student:
def __init__(self,name):
self.name = name
self.exp = 0
self.lesson = 0
self.AddEXP(10)
def Hello(self):
print('สวัสดีจ้าาา ผมชื่อ{}'.format(self.name))
def Coding(self):
print('{} กำลังเขียนโปรแกรม'.format(self.name))
self.exp += 5
self.lesson += 1
def ShowEXP(self):... |
import socket
print("For client side")
HOST=socket.gethostname()
PORT=12345
s=socket.socket()
s.connect((HOST,PORT))
while True:
def menu():
value = input(
'1. Find customer \n2. Add customer \n3. Delete customer \n4. Update customer age \n5. Update customer address \n6. Update customer phone\n... |
gameResult = input('Please enter game results: ').lower()
def count(coin):
H = coin.count('h')
T = coin.count('t')
if H > T:
return 'H wins!'
elif H < T:
return 'T wins'
else:
return 'Draw!'
print (count(gameResult))
|
import math
array = [0, 3, 4, 5, 6, 15, 18, 22, 25, 27, 31, 33, 34, 35, 37, 42, 53, 60]
def binarySearch(array, number):
middleIndexOfArray = int(math.floor(len(array) / 2))
if middleIndexOfArray == 0:
return False
if array[middleIndexOfArray] == number:
return True
elif array[middleIndexOfArray] > number:
... |
file = open("01.txt")
seen = set()
requiredSumEntry = 2020
for line in file:
entry = int(line)
for seenEntry in seen:
supplement = requiredSumEntry - entry - seenEntry
if supplement in seen:
print("{} {} {} {}".format(entry, seenEntry, supplement, entry*seenEntry*supplement))
... |
file = open("02.txt")
numValid = 0
for line in file:
tokens = line.split(":")
policy = tokens[0].split(" ")
policyMinMax = policy[0].split("-")
policyMin = int(policyMinMax[0])
policyMax = int(policyMinMax[1])
policyLetter = policy[1]
password = tokens[1].strip()
count = { policyLetter: ... |
file = open("01.txt")
freqs = [int(line) for line in file]
#freqs = [+3, +3, +4, -2, -4]
#print(freqs)
seen = set()
done = False
sumFreq = 0
numCycle = 0
seen.add(sumFreq)
while not done:
for freq in freqs:
sumFreq += freq
if sumFreq in seen:
print(sumFreq)
done = True
... |
def trimPems(pem):
lines = pem.splitlines()
concatenated = ''
for x in range(1, len(lines) - 1):
concatenated += lines[x]
return concatenated
def isNumber(input):
try:
# Convert it into integer
val = int(input)
return True
except ValueError:
try:
... |
# -*- coding: utf-8 -*-
"""
@author: Jung Soo
"""
monthInt = int(input("Enter an integer.\n"))
"""print(monthNumb)"""
if (monthInt == 1):
print("January")
elif (monthInt == 2):
print("February")
elif (monthInt == 3):
print("March")
elif (monthInt == 4):
print("April")
elif (monthInt == 5)... |
my_set = ['chair', 'table', 'wardrobe', 'sofa', 'bed']
for furniture in my_set:
print(furniture)
print('############################')
for furniture in my_set:
if furniture != 'sofa':
print(furniture)
my_list = my_set + ['door', 'mirror']
print(my_set)
for furniture in my_set:
if furniture ==... |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
#import excel files and construct numpy array
s1 = pd.read_excel (r'C:\Users\lenovo\OneDrive\桌面\Physics\Pioneer Academics\Independent Project\Data\sasph008.xlsx') #place "r" b... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#UNAM-CERT
"""
Manejo de tuplas y conjuntos
"""
from random import choice
list1=[]
list2=[]
note_bec = {}
con=set()
notes = (0,1,2,3,4,5,6,7,8,9,10)
becarios = ['Alonso',
'Eduardo',
'Gerardo',
'Rafael',
'Antonio',
... |
# making custom exceptions
class UppercaseException(Exception):
pass
words = ['eenie', 'meenie', 'MINY', 'MO']
for word in words:
if word.isupper():
try:
raise UppercaseException(word)
except UppercaseException as e:
print(e.message)
continue
|
# create a generator function to generate 1000 even numbers
def gen_Even_numbers(first=0, last=1000, step=1):
n = first
while n < last:
if n%2 == 0:
yield n
n += step
print 'Type of gen_Even_numbers = ', type(gen_Even_numbers)
# set a new variable object generator
ge = gen_Even_nu... |
# list comprehensions
# zero based list
a = [num for num in range(11)]
print(a)
# n-based list
a = [num for num in range(1, 11)]
print(a)
# todo: write a function to generate n random words
# given limit of m letters in each word
|
from collections import namedtuple
d = namedtuple('Address','street city zipcode')
a1 = d('Street Address Whatever', 'Fayetteville', '72703')
print(a1)
print a1.street, a1.city , a1.zipcode
a2 = a1
print(a2)
a3 = a2._replace(city='Bentonville')
a2 = None
print a1, a2, a3
|
# -*- coding: utf-8 -*-
#
#To run this spider, from command line type 'scrapy crawl AlexaSpider -o <output_file_name>.json'
#
#This spider uses the scrapy framework to crawl sites
import scrapy
from alexa1m.items import Alexa1MItem
#Below methods used to put Alexa 1M in format that can be used by scrapy
from StringIO... |
def exponent (base, count):
if count == 1:
return base
else:
return base * factorial(base, count-1)
print(exponent(2, 4)) #expect
|
# a, b = 0, 1
# for i in range(1, 10):
# print(a)
# a, b = b, a + b
# x = [1, [1, ['a', 'b']]]
# print(x)
# def search_list(list_of_tuples, value):
# for comb in list_of_tuples:
# for x in comb:
# if x == value:
# print(x)
# return comb
# else:
# ... |
class A:
def __init__(self):
super().__init__()
print("A")
class B:
def __init__(self):
super().__init__()
print("B")
class C(A, B):
def __init__(self):
super().__init__()
c = C()
|
class Prop(property):
def __init__(self, attr_name):
hide_attr_name = "_" + attr_name
def getter(inst):
return getattr(inst, hide_attr_name)
def setter(inst, value):
print(inst, value)
setattr(inst, hide_attr_name, value)
super().__init__(getter, setter)
def __get__(self, instance, owner):
print... |
# Look_and_say_problem
'''
the look an say sequence starts with 1. Subsequent numbers are derived by describing the previous
number in terms of consecutive digits. Specifically, to generate an entry of the subsequence from
the previous entry,read off the digits of the previous entry, counting the number of digits in g... |
# Search_cyclically_sorted_array
'''
an array is said to be cyclically sorted if it is possible to cyclically shift its entries so that
it becomes sorted. e.g. [6,7,8,9,1,2,3,4,5] if you cyclically left shift for 4 times then it leads
to sorted array.
Design O(log n) algorithm for finding the position of the smalles... |
# Simple_Queue
class Queue:
def __init__(self):
self._data = collections.deque()
def enqueue(self, x):
self._data.append(x)
def dequeue(self):
return self._data.popleft()
def max(self):
return max(self._data)
# time complexity of enqueue, dequeue = O(1)
# time complexity of finding the maximum is O(n),... |
# Test_if_binary_tree_is_height_balanced
'''
a binary tree is said tobe height balanced if for each node in the tree, the difference in the height
of its left and right subtree is at most one. A perfect binary is height-balanced,as is a complete
binary tree. However, a height balanced binary tree does not have to be p... |
# Enumerate_all_primes_to_n
'''
write a program that takes an integer argument and returns all the primes between 1 and that integer
Hint: exclude multiples of primes.
'''
''' solution 1: brute force
iterate over all i from 2 to n.
for each i, we test if i is prime; if so we add to results.
we can use trial division... |
# Delete_duplicates_from_sorted_array
''' write a program that takes input as a sorted array and updates it so that all duplicates have
been removed and the remaining elements have been shifted left to fill the emptied indices.
Return the number of valid elements.
O(n) time and O(1) space complexities.
'''
'''
if O(... |
# Palindrome
# palindrome string is one which reads tthe same when it is reversed.
# space = O(1) time = O(n)
def is_palindromic(s):
# note that s[~i] = s[-i - 1]
return all(s[i] == s[~i] for i in range(len(s) // 2))
|
# Compute_all_valid_IP_addresses
'''
decimal string is a string consisting of digitss between 0 and 9.
write a program that determines where to add periods to a decimal string so that the resulting string
is a valid IP address. There may be more than one valid IP addresses corresponding to a string,
in which case you... |
num=int(input("Enter a number:")
factorial=1
if num=0:
print("The factorial value is 1")
else:
for i in range (1,num+1`):
factorial=factorial*i
print("Factorial value is:")
|
lower=int(input('Enter lower value")
upper=int(input("Enter upper value")
for i in range(lower,upper):
if(i%2!=0):
print(i)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 22:08:26 2018
@author: praveen
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv('C:/Users/praveen/Desktop/machine-learning udemy a-z/Machine Learning A-Z Template Folder\Part 2 - Regression/Section 4 - Simple Lin... |
a = int(input("Enter number1:: "))
b = int(input("Enter number2:: "))
c = int(input("Enter number3:: "))
if a>b and a>c:
print(a," is largest among ",a,", ",b," and ",c)
elif b>c:
print(b," is largest among ",a,", ",b," and ",c)
else:
print(c," is largest among ",a,", ",b," and ",c) |
text = input("Enter the line of text: ").split(" ")
list1 = []
for i in text:
if i not in list1:
list1.append(i)
text = " ".join(text)
for i in list1:
print("No: of occurences of ", i, " :: ", text.count(i))
|
# Nome: Felipe de Carvalho Alves
# RA: N2864F-5
import argparse
import Extensions as calc
import re
# Used to specify the .txt path that will be used
# Usado para especificar o arquivo que será usado
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--file", required=True, help="Caminho do arquivo texto")
args = ... |
"""
Revisão IF ELSE
IF - SE
ELSE - SE NÃO
ELIF - SE NÃO SE
# IF / ELIF /ELSE - Juntos formas a estrutura de condição no Python para tomada de decisão
Traduzindo a estrutura
------------
SE algo for verdadeiro, faça isso:
comandos
comandos
Se não faça aquilo:
comandos
comandos
------------
"""
# Exemp... |
"""
Funções de física versão 2
"""
def calculo_densidade():
def valor_massa():
print('Então vamos descobrir o valor da massa, para isso preciso que você: ')
v = float(input("Digite o valor do volume"))
d = float(input('Digite o valor da densidade'))
return v * d
def valor_volu... |
def leapYear(year):
if year % 4 == 0: # use == to compare values. = is to assign
if (year % 100 != 0) or (year % 400 == 0): # make sure the conditions are correct. you had 100 != instead of 100 ==
print(year, " is a leap year")
else:
print(year, 'is not a leap year... |
'''
Write a program that prompts for weight (in pounds) and height (in inches) of a person, and
prints the weight status of that person.
Body mass index (BMI) is a number calculated from a person’s weight and height using the
following formula: 𝑤𝑒𝑖𝑔ℎ𝑡/ℎ𝑒𝑖𝑔ℎ𝑡^2. Where 𝑤𝑒𝑖𝑔ℎ𝑡 is in kilograms and ℎ𝑒𝑖𝑔... |
"""Implement fig_subplot for matplotlib."""
import matplotlib.pyplot as plt
def fig_subplot(nrows=1, ncols=1, sharex=False, sharey=False,
subplot_kw=None, **fig_kw):
"""Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
... |
"""Simple vector implementation."""
class Vector(object):
#: esto es tal cosa...
comun = 1
def __init__(self, *components):
"""Initialize a vector."""
print "initializing vector"
if len(components)==1:
# If we are given a single sequence, try to make it into a tuple to
... |
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
def search(l, n):
if not l:
return False
if len(l) == 1:
return l[0] == n
while 1:
mid = len(l) / 2
mid_n = l[mid]
if mid == 0:
return mid_n == n
if mid_n > n:
l = l[:mid]
c... |
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class Solution(object):
def longestCommonPrefix(self, strs):
if not strs:
return ""
pre = None
for s in strs:
if pre is None:
pre = s
else:
j = len(pre) if len(pre) < len(s) e... |
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
ret, seq = {}, []
while head:
v = head.val
if v not in ret:
... |
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
if not root:
return True
def valid(left, right):
... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
class Solution(object):
def romanToInt(self, s):
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
rule = {'V': 'I', 'X': 'I', 'L': 'X', 'C': 'X', 'D': 'C', 'M': 'C'}
if not s:
return 0
if len(s) == 1:... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
"""
https://leetcode-cn.com/problems/add-two-numbers/
"""
def add_next(self, l):
last = l
extra = 1
while True... |
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class Solution(object):
def permute(self, nums):
if not nums:
return []
def arrange(nums0, total):
if total == 1:
return [nums0]
ret, t = [], total - 1
for i, v in enumerate(nums0):
... |
''' Schemdraw drawing segments.
Each element is made up of one or more segments.
'''
from collections import namedtuple
import numpy as np
from .transform import mirror_point, mirror_array, flip_point
BBox = namedtuple('BBox', ['xmin', 'ymin', 'xmax', 'ymax'])
def roundcorners(verts, radius=.5):
''' Round ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 17 23:04:59 2018
@author: hyq92
"""
import pandas as pd
import numpy as np
# sklearn preprocessing for dealing with categorical variables
from sklearn.preprocessing import LabelEncoder
# import lifelines
application_train = pd.read_csv("application_train.csv", header=0... |
""" Put together the "outbreak" aspect of Python """
from citiesandcolors2 import *
import sys
import time
Outbreaks = 0
from Tkinter import *
# Which city we are current updating
from citiesandcolors2 import *
from citylocs import CityLocs
from time import sleep
# A place to remember all the IDs of the canvas o... |
from stack import Stack
def DecToBin(num):
'''This function converts an integer in base 10 to an integer in base 2 or say its binary value'''
stk=Stack()
while(num!=0):
stk.push(num%2)
num=num//2
s=""
while(not stk.isEmpty()):
s+=str(stk.pop())
return s
if __name__=="__main__":
decimal_val=int(input())
... |
'''This module contains the function to reverse a string'''
def reverseString(original_string):
'''This method takes a string and reverses and returns it'''
if len(original_string)<2:
return original_string
else:
return reverseString(original_string[1:])+original_string[0]
if __name__=="__main__":
string=inpu... |
class Queue:
def __init__(self):
self.items=[]
def enqueue(self,data):
self.items.insert(0,data)
def dequeue(self):
if self.items!=[]:
return self.items.pop()
else:
return None
def size(self):
return len(self.items)
def isEmpty(self):
return self.items==[]
if __name__=="__main__":
queue=Que... |
"""This module contains the code to implement a breadth first search algorithm on a graph"""
import collections
def bfs(graph,start_vertex):
"""This function is used to run breadth first search on a graph"""
visited,queue=[start_vertex],collections.deque([start_vertex])
while queue:
current_vert... |
'''This is the implementation of LinkedList only but according to what I studied
on Runestone academy. Here the Linked List items do not follow an arrangement,hence it is
Unordered'''
class Node:
def __init__(self,data):
self.data=data
self.next=None
def getData(self):
return self.data
def setData(self,dat... |
from stack import Stack
def doMath(first,second,operator):
if operator=='+':
return first+second
elif operator=='-':
return first-second
elif operator=='*':
return first*second
elif operator=='/':
return first/second
else:
return first%second
def evaluatePostfix(postfix_string):
opstack=Stack()
print... |
class Solution:
def reverseString(self, s: list[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if s == []:
return
def helper(start,end,s):
if start > end:
return
helper(start+1,end-1,s)
... |
'''
第8节 链表指定值清除练习题
现在有一个单链表。链表中每个节点保存一个整数,再给定一个值val,把所有等于val的节点删掉。
给定一个单链表的头结点head,同时给定一个值val,请返回清除后的链表的头结点,
保证链表中有不等于该值的其它值。请保证其他元素的相对顺序。
测试样例:
{1,2,3,4,3,2,1},2
{1,3,4,3,1}
'''
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class ClearValue:
def c... |
'''
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
'''
class Solution:
def maxSubArray(self, nums: list[int]) -> int:
# 以num[i]结尾的最大子串和,一开始方法是对的,状态转移写错了
dp = nums
for i in range(1,len(nums)):
if dp[i-1]+ n... |
'''
题目描述:计算让一组区间不重叠所需要移除的区间个数。
先计算最多能组成的不重叠区间个数,然后用区间总个数减去不重叠区间的个数。
在每次选择中,区间的结尾最为重要,选择的区间结尾越小,留给后面的区间的空间越大,那么后面能够选择的区间个数也就越大。
Input: [ [1,2], [1,2], [1,2] ]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Input: [ [1,2], [2,3] ]
Output: 0
Explanation: You don't need ... |
'''
有一棵二叉树,其中所有节点的值都不一样,找到含有节点最多 的搜索二叉子树,并返回这棵子树的头节点.
给定二叉树的头结点root,请返回所求的头结点,若出现多个节点最多的子树,返回头结点权值最大的。
'''
'''
基本情况分析:
1. 以Node节点为头,整棵树是最大搜索二叉树:
左子树:以Node左孩子为头,最大搜索二叉树的最大值小于Node的节点值
右子树:以Node右孩子为头,最大搜索二叉树的最小值大于Node的节点值
2. 不满足上述: 以Node为头整体不能连成搜索二叉树,此时最大搜索二叉树 = 两侧子树的最大搜索二叉树里 节点数较多的
'''
# -*- coding:utf-8 -*-
# c... |
'''
链表的快速排序实现 ,空间复杂度是O(1)
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def quickSortList(self,head):
if head is None or head.next is None:
return head
tmpHead = ListNode(0)
tmpHead.next =head
self.qsortList... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# __all__ = ['栈(顺序表)',
# '栈(链接表)',
# '队列']
# 栈(顺序表)
class SStack:
def __init__(self):
self._elems = []
def is_empty(self):
return self._elems == []
def top(self):
if self._elems == []:
raise Excepti... |
'''
求a/b的小数表现形式。如果a可以整除b则不需要小数点。
如果是有限小数,则可以直接输出。如果是无限循环小数,则需要把小数循环的部分用"()"括起来。
两个整数a和b,其中
0 <= a <= 1000 000
1 <= b <= 10 000
'''
class Solution:
def demicalString(self):
a,b = [int(i) for i in input().split()]
if a%b==0:
print(a//b)
else:
cache=[]
de... |
'''
输出所有和为 S 的连续正数序列。
例如和为 100 的连续序列有:
[9, 10, 11, 12, 13, 14, 15, 16]
[18, 19, 20, 21, 22]。
双指针思路
//左神的思路,双指针问题
//当总和小于sum,大指针继续+
//否则小指针+
'''
class Solution1:
def FindContinuousSequence(self, tsum):
phigh ,plow =2,1
allres= []
while phigh > plow:
cur = (phigh+plow)*(phigh-p... |
class ChkLoop:
def chkLoop(self, head, adjust):
# write code here
if head is None or head.next is None:
return False
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next if fast.next else None
slow = slow.next
... |
# -*- coding:utf-8 -*-
import random;
class Random5:
@staticmethod
def randomNumber():
return random.randint(0, 1000000) % 5 + 1
class Random7:
# 随机产生[1,5]
def rand5(self):
return Random5.randomNumber()
# 请通过self.rand5()随机产生[1,7]
def randomNumber(self):
# return self... |
"""
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
"""
# -*- coding:utf-8 -*-
class Solution1:
def minNumberInRotateArray(self, rotateArray):
# write code here
if len(rotateArray)==0:
return 0
... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''
链表转二叉树
'''
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def sortedListToBST(head):
""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.