text stringlengths 37 1.41M |
|---|
'''
Author: Bastin Robins.J
Desc: Simple Account
'''
class Account(object):
def __init__(self):
self.history = []
self.storage = {}
def create_account(self, name, accno):
self.storage[accno] = name
if(self.storage[accno]):
self.history.append("Account Created Successfully")
print "Account Created S... |
'''
MapQuest User Interaction Input
---
A module that reads the input and constructs the objects that will generate the program's output.
This is the only module that should have an if __name__ == '__main__': block to make it executable,
you would execute this module.
---
The program should not prompt the user i... |
class Locker:
#List containing the filed that are locked by the file system
locked_files = []
def __init__(self):
pass
#"Test" the lock
#i.e. check if the file has been locked
def test_lock(self, file):
if file in self.locked_files:
return True
else:
... |
# -*- coding: cp1254 -*-
#its for turkish character
#print('hi world')"
#standart veri tipleri
#Numbers
#String
#List
#Tuple
#Dictionary
#desteklenensayitiokers
#int (signed integers)
#long (long integers, they can also be represented in octal and hexadecimal)
#float (floating point real values)
#complex (comple... |
# This is a program that gives simple math quizzes.
# 07-12-2020
# CTI-110 P5HW2 - Math Quiz
# Sinclair Robinson
# Write a program that gives simple math quizzes. The program should display
# two random numbers that are to be added.
import random
randomNumber1 = random.randint( 1, 250 )
randomNumber2 = r... |
import math
from io_utils import read_input_file
def strafe_move(direction, value, position_x, position_y):
if direction == "N":
position_y += value
if direction == "S":
position_y -= value
if direction == "E":
position_x += value
if direction == "W":
position_x -= val... |
from io_utils import read_2d_array
def day3_1():
input_map = read_2d_array("day3.txt")
return get_trees_count_on_slope(input_map, right_steps=3, down_steps=1)
def get_trees_count_on_slope(input_map, right_steps, down_steps):
row, column = 0, 0
trees_counter = 0
pattern_length = len(input_map[col... |
"""
Given a string, find the length of the longest substring without repeating
characters.
Examples:
"abcabcbb" -> "abc" -> 3
"bbbbb" -> "b" -> 1
"pwwkew" -> "wke" -> 3
Problem provided by: https://leetcode.com/problems/longest-substring-without-repeating-characters/
"""
def longest_substring_without_repeats_brute_f... |
# CS2021 Homework 1
def egyptianMath(p,q):
"""reads two integers p and q from a user
and uses the greedy approach to output a
listing representing a sum of unit fractions,
with sum equal to p/q
>>> egyptianMath(7,10)
1/5 + 1/2 = 7/10
>>> egyptianMath(0,5)
The fraction is equal to 0
>... |
# Homework 14.2: Problem 1
# File: HW_14_2_wilfonjv.py
# Date: 1 Dec 2018
# By: James Wilfong
# wilfonjv
# Section: 007
# Team: 071
#
# ELECTRONIC SIGNATURE
# James Wilfong
#
# The electronic signature above indicates the script
# submitted for evaluation is my individual work, and I
# have a genera... |
names = ['Jeff', 'Gary', 'Jill', 'Samantha']
for name in names:
#print('Hello there, ' + name)
print(' '.join(['Hello there,', name]))
#print the list of the names as a string
print(', '.join(names))
import os
location_of_files = 'C:\\Code\\Python\\Sentdex_Intermediate_Tutorial'
file_name = 'testfile.txt'
... |
import urllib # for URL loading
from bs4 import BeautifulSoup # for HTML prasing
import urlparse #to get each url
# To get all the URL in the website to Perform searchText
def Load_all_URL (url) :
try:
page = urllib.urlopen( url ).read()
except:
return []
urlList = []
soup = BeautifulSo... |
"""
The mathematical function run in the "tupper_func" can
represent an arbitrary grid of 106x17 pixels - and
what is depicted depends on the height on the Y axis modulo 17.
By calculating a sepcial - hundreds of pages long - offset on the
y axis to render, any image can be displayed.
The "default" image is the formu... |
'''
Topic 1 : Print Function :
--> This will print the text given in double quotes
Syntax :
print("text to be displayed")
'''
print("Hello World") |
class Player:
"""Description of the class player"""
def __init__(self, first_name, last_name, birthday, gender, rank,
score_of_round, final_score_of_tournament):
self.first_name = first_name
self.last_name = last_name
self.birthday = birthday
self.gender = gende... |
import pymysql
def unique_items(players):
insert_set = []
name_set = set()
for item in players:
if item[0]+" "+item[1] not in name_set:
name_set.add(item[0]+" "+item[1])
insert_set.append(item)
return insert_set
file = open("player_info.txt", "r")
players = []
for line ... |
secretWord = "apple"
same = "False"
secretWordBlank = ["_","_","_","_","_"]
lettersGuessed = []
def isWordGuessed(secretWord,lettersGuessed):
x = 'a','p','l','e' in lettersGuessed
y = True in x
return y
while isWordGuessed(secretWord,lettersGuessed) == False:
answer = input("Guess a character: ... |
# Autor: Ivana Olvera Mérida, A01746744
# Descripcion: Misión 2-Ejercicio 3: Cuenta
# Escribe tu programa después de esta línea.
subtotal = int (input("Subtotal: "))
propina = (subtotal*.13)
iva= (subtotal*.16)
total= (subtotal+propina+iva)
print ("Propina: %.2f" % (propina))
print ("IVA: %.2f" %(iva))
print ("Total... |
# Лабораторная работа 5
# По двум отсортированным спискам чисел с разными размерами и элементами вернуть медиану объединения этих двух списков
import statistics
def medians(nums1, nums2):
return statistics.median(nums1+nums2)
|
import googlemaps,json,requests, urllib, urllib.request
from math import sin,cos,sqrt,atan2,radians, pi
from urllib.parse import urlencode
import math as math
#Assuming current location is Gmoney's House, and distance to run is 2 miles (This will be input by the user/phonedata)
beginningLatitude = 40.51303
beginningLo... |
'''Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
'''
class Solution(object):
# DFS recursively
def subsets1(self, num... |
'''Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimiz... |
nums1 = [1,3,5,7,9]
m = 5
nums2 = [2,4,6,8,10]
n = 5
if m == 0:
nums1 = []
if n == 0:
nums2 = []
nums1.extend(nums2)
nums1.sort()
print (nums1)
|
'''Author: Pallav'''
#Open Terminal(with "ctrl+alt+t" on linux), and write 'pip install pywhatkit'
#Next import pywhatkit as <Whatever name u want, here I have used 'pallavtexttowritting'>
import pywhatkit as pallavtexttowritting
#Input from user, by which name the file is to be saved!
nameoffile = input("By what n... |
# // 1. From an unsorted array of numbers 1 to 100 excluding one number, how
# // would you find the missing number?
# // 2. From an unsorted array, check whether there are any two numbers that
# // will sum up to any given number (example: ([1,5,7,8,4,3,9] ,6) returns
# // true & ([1,5,7,8,4,3,9] , 3) returns false)
#... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
@staticmethod
def listprint(x):
while x:
print(x.val)
x = x.next
class Solution(object):
def len_list(self, l):
count = 0
... |
# Detectar si un input es palíndromo
import sys
import string
import unicodedata
if len(sys.argv) > 1:
myinput = sys.argv[1]
myinput_lower = myinput.lower()
isTrue = True
mystring = myinput_lower.replace(" ", "")
mystring_normalized = unicodedata.normalize("NFKD", mystring).encode("as... |
# Adivinar el resultado del programa introduciendo 3, aa y 6
try:
n = int(input("numero: "))
except:
n = 3
a = 1
for i in range(n, 0, -1):
print(" "*i+"*"*a)
a += 2
print(" "*(n-1)+"*"*3)
# 3: *
# ***
# *****
# ***
# aa: *
# ***
# *****
# ***
# 6: *
# ... |
# Pide 3 números e imprime su suma. Usa dos variables
numeros = int(input("Introduce el primer número: ")), int(input("Introduce el segundo número: ")), int(input("Introduce el tercer número: "))
suma = sum(numeros)
print(suma) |
def alphabet_position(text):
solucion = []
for i in text.lower():
if i <= "z" and i >= "a":
solucion.append(ord(i)-96)
solucionFinal = " ".join(map(str, solucion))
return solucionFinal
print(alphabet_position("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU... |
# Crear un programa para jugar a adivinar un número entre 0 y 100. Debe ofrecer cinco oportunidades e indicar ante un fallo si el objetivo es menor, mayor o esta muy cerca (a 2 de distancia o menos). Se debe utilizar una función para comprobar si el número es el acertado o no y hacer las indicaciones al jugador.
imp... |
# Diseña un programa que, dados dos números enteros, muestre por pantalla uno de estos mensajes: "El segundo es el cuadrado exacto del primero.", "El segundo es menor que el cuadrado del primero." o "El segundo es mayor que el cuadrado del primero.", dependiendo de la verificación de la condición correspondiente al sig... |
#Solicitar por teclado una cantidad de dinero con decimales hasta los céntimos y calcular el cambio en billetes y monedas de curso legal.
cantidad = float(input("Introduce la cantidad total de dinero: "))
billetes = [500, 200, 100, 50, 20, 10, 5]
monedas = [2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
resto = round(c... |
# Dado un número entero positivo hallar los números perfectos menores que él. Un número es perfecto si la suma de sus divisores, excepto él mismo, es igual al propio número.
num1 = int(input("Introduce el primer número: "))
divisoresNum1 = []
sumaDivisores1 = int
while num1 >= 0:
for i in range(1, num1... |
# Create some Python code that will prompt you to enter your name. Print out Hello and then the name
name = input("¿Cómo te llamas? ")
print("Hello",name) |
# El juego del ahorcado
import random
def juego():
palabras = ["cerillas", "patrulla", "papel", "azor", "alerones", "conversar", "sollozo", "manzana"]
palabra = random.choice(palabras)
palabra_lista = list(palabra)
secreto = []
intento = 10
for i in range(len(palabra_lista)):... |
# Detectar si un input es palíndromo
import sys
import string
import unicodedata
if len(sys.argv) > 1:
myinput = sys.argv[1]
isTrue = True
mystring_normalized = unicodedata.normalize("NFKD", myinput.lower().replace(" ", "")).encode("ascii", "ignore").decode("ascii")
slicedstring = mystring... |
# Un capital de C euros a un interés del x por cien anual durante n años se convierte en C ·(1 + x/100)n euros. Diseña un programa Python que solicite la cantidad C y el interés x y calcule el capital final sólo si x es una cantidad positiva.
capitalInicial = int(input("Introduce la cantidad inicial: "))
interes = ... |
import re
class SudokuBoard():
def __init__(self, board):
"""
Initiliaze with a list of lists, where each sublist
"""
self.board = board
self.valid = self.is_board_valid()
if not self.valid:
print("!! Given board is not valid")
def __str__(se... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 09:59:04 2021
@author: tew
"""
import pandas as pd
import glob
import numpy as np
import csv
import itertools
import os
def get_file_info(filename: str):
"""
allows to extract data from csv file
Parameters
----------
filename : str
DES... |
# 1.
# Manipulate the string variable s to output the correct variations.
s = "6.00 is 6.0001 and 6.0002"
# a. Manipulate s to print out '62'
# print(s[...] + s[...])
print ( s[0] + s [24])
# b. Manipulate s to print out every other character starting in position 4
# print(s[...:...:...])
print (s[4::2])
# c. Manipula... |
### Script for turning a bunch of images in a folder to greyscale ###
## (This reduces the file size drastically, for example for raspberry pi NoIr images that are grey scale anyways)
from PIL import Image
import os, sys
def check_dir(directory):
if not os.path.exists(directory):
os.makedirs(directory)
#... |
def averager():
total = 0.0
count = 0
average = None
while True:
term = yield average
total += term
count += 1
average = total / count
from coroutil import coroutine
@coroutine
def averager_auto():
total = 0.0
count = 0
average = None
while True:
... |
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30] # ordered list
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31] # values to find
def demo(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle)
print (position)
offset = po... |
def fizz_buzz(x):
if x%3==0:
return "Fizz"
elif x%5==0:
return "Buzz"
else:
return x
Ans= fizz_buzz(int(input("input the num: ")))
print(Ans)
|
import random
def bubbleSort(array):
for i in range(len(array)-1):
for j in range(i+1, len(A))[::-1]:
if array[j] < array[j-1]:
array[j], array[j-1] = array[j-1], array[j]
A = []
s = random.randint(5, 100)
for i in range(0, s):
A.append(random.randint(0, 1000))
print(A)
... |
'''
From the command line
python -m doctest [-v] your_script.py
From inside a script
import doctest
doctest.testmod()
'''
def multiply(a, b):
"""
Arguments:
a, b : Number
Returns:
type(a) : a*b
Exemple:
>>> multiply(4, 3)
12
>>> multiply('a', 3)
'aa... |
# Trapezoidal Method
# Define function to integrate
def f(x):
return 1/(1 + x**2)
# Implementing trapezoidal method
def trapezoidal(x0,xn,n):
# calculating step size
h = (xn - x0) / n
# Finding sum
integration = f(x0) + f(xn)
for i in range(1,n):
k = x0 + i*h
integra... |
def recursive_combat(player_1, player_2, played=set()):
while player_1 and player_2:
config = (tuple(player_1), tuple(player_2))
if config in played:
return False
played.add(config)
card_p1, card_p2 = player_1.pop(0), player_2.pop(0)
if (recursive_combat(player... |
# Task List Class and Object
class TaskList():
def __init__(self, tasks):
self.tasks = tasks
def add_task(time, color):
def find_task_by_color(color):
for task in self.tasks:
if task.color
|
# import tkinter
# window = tkinter.Tk()
# button = tkinter.Button(window, text='Hello', bg='green',fg='white')
# button.pack()
# window.mainloop()
import tkinter
def change(widget, colors):
"""키가 'red', 'green', 'blue'인 딕셔너리에 저장된 RGB값으로
위젯의 전경색을 업데이트한다. 색 값이 유효한지 확인하지 않는다."""
new_val = '#'
for name i... |
__author__ = 'Oleksandr Pylkevych'
def cigar_party(cigars, is_weekend):
if is_weekend:
return cigars >= 40
else:
return 40 <= cigars <= 60
def date_fashion(you, date):
if date <= 2 or you <= 2:
return 0
elif date >= 8 or you >= 8:
return 2
else:
return 1
... |
ans = input("enter coordinates. eg 'a16' \n")
# for my numbering
while ans != '':
row = int(ans[1:])
col = int( ord(ans[0].lower()) - 96 )
num = (row * 21) + col
print(num)
ans = input("enter coordinates. eg 'a16' \n")
#for debord's numbering
# while ans != '':
# row = int(ans[1:])
# c... |
import math
import WonderPy.core.wwMain
from WonderPy.util import wwMath
"""
This example shows connecting to the robot and sending commands each time sensors are received.
Basic steps:
1. add the imports
2. create a Class (in this case named "MyClass").
3. create a method named "on_sensors" which accepts self and a ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 15:46:40 2017
@author: GB121361
"""
age = 35
name = "Megan"
if age == 35:
if name == "Megan":
print(name + " is 35")
elif name == "Steve":
print("Steve")
else:
print("Not 35")
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 15:22:15 2017
@author: GB121361
"""
from math import factorial as f
print(f(0))
print(f(1))
print(f(2))
print(f(3))
print(f(4))
print(f(5))
|
#Book Management System to store book records like ID, Book name, Author name, Cost using map
# Operations performed on record:
# insert record
# search record
# delete record
# display records
#Date: 07/06/2021
bookDict = {}
def insertBook(key1, bookName, authorName, cost):
bookDict[key1] = [bookNam... |
''' problem - https://programmers.co.kr/learn/courses/30/lessons/43165
타겟 넘버
This problem is related with DFS/BFS
'''
#problem solving#1 dfs stack
def solution(numbers, target):
''' Key point - using stack, all the case checking
Pop the value and push the all result + value and all result - va... |
''' problem - https://programmers.co.kr/learn/courses/30/lessons/42577
전화번호 목록
This problem is related with hash
'''
def solution(phone_book):
''' Key Point - pop the element from phone_book,
Check the phone_book includes pop string with 0 index
Except same stri... |
string = " Hello, World! "
print(string.upper()) # Output : HELLO, WORLD!
print(string.lower()) # Output : hello, world!
print(string.strip()) # Output : Hello, World! ตัดตัวสเปสบาร์
print(string.replace("H", "J")) # Output : Jello, World!
print(string.split(",")) # Output : [ 'Hello', 'World!' ] result เ... |
"""
Recursive feature elimination
=======================================================================
A recursive feature elimination is performed prior to SVM classification.
"""
import numpy as np
from scikits.learn.svm import SVC
from scikits.learn.cross_val import StratifiedKFold, GridSearchCV
from scikits.le... |
price_item1 = float(input('Enter price of item 1: '))
quantity_item1 = int(input("Enter quantity of item 1: "))
price_item2 = float(input('Enter price of item 2: '))
quantity_item2 = int(input("Enter quantity of item 2: "))
price_item3 = float(input('Enter price of item 3: '))
quantity_item3 = int(input("Enter quantity... |
# A Dynamic Programming based
# solution to find min cost
# to reach temple N-1
# from station 0.
INF = 2147483647 #(max value of infinity as integer)
N = 4
# This function returns the
# smallest possible cost to
# reach temple N-1 from A 0.
def minCost(cost):
# dist[i] stores minimum
# cost to reach te... |
#A python program for Calculating Income Tax
print("Tax Payer categories are:")
print("-------------------------")
print("1: Single")
print("2: Married Filing Jointly")
print("3: Married Filing Separately")
print("4: Head of the household")
category = eval(input("Please specify your category as a tax-payer: ... |
countStudents = int(input("Enter the number of students: "))
print()
scoreList = []
for i in range(countStudents):
scoreEach = eval(input("Enter the score of student {0}: ".format(i+1)))
scoreList.append(scoreEach)
scoreList.sort()
print("\nThe highest socre in the class is: ", scoreList[-1])
print(... |
weight = eval(input("Enter your weight in pounds: "))
feet = eval(input("Enter Feet: "))
inch = eval(input("Enter inch: "))
height = inch + feet*12
kiloPerPound = 0.45359
meterPerInch = 0.0254
weightInKilo = weight * kiloPerPound
heightInMeters = height * meterPerInch
bmi = weightInKilo / pow(heightInMete... |
from foodMenu import Food, buildMenu, buildLargeMenu, testMaxVal
import random
def fastMaxVal(toConsider, avail, memo=None):
"""Assumes toConsider a list of subjects, avail a weight
memo supplied by recursive calls
Returns a tuple of the total value of a solution to the
0/1 knapsack probl... |
"""
Code Challenge: Solve the Clump Finding Problem.
You will need to make sure that your algorithm is efficient enough to handle a large dataset.
Clump Finding Problem: Find patterns forming clumps in a string.
Input: A string Genome, and integers k, L, and t.
Output: All distinct k-mers forming (L, t)-clumps in Gen... |
# Interpreted language-reads & executes immediately
# Indentation is IMPORTANT - turn OFF TABS!
# use four spaces (atom automatically uses spaces on .py files)
#
# put try blocks around dangerous sections of code
smallest = None
print("Before:", smallest)
for itervar in [3, 41, 12, 9, 74, 15]:
if smallest is None... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import heapq
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
inorder = []
def dfs(root):
... |
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
def reverse(s , l , r):
while (l < r):
s[l] , s[r] = s[r] , s[l]
l += 1
r -= 1
reverse(s , 0 , ... |
import threading
from queue import Queue
data_to_read = []
global data_counter
class FirstThread(threading.Thread):
def __init__(self, thread_id, name, data_input,):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.data_input = data_input
def ... |
def get_greatest_smallest(a, low, high, target):
result = -1
while low <= high:
mid = (low + high) // 2
if a[mid] <= target:
result = mid
low = mid + 1
else:
high = mid - 1
return result
def get_count(a, target):
result = get_greatest_smalles... |
# CTI-110
# M3T1 - Areas of Rectangles
# Mitchell Locklear
# 09/13/2017
height1 = int(input("What is the HEIGHT of the FIRST rectangle: "))
width1 = int(input("What is the WIDTH of the FIRST rectangle: "))
height2 = int(input("What is the HEIGHT of the SECOND rectangle: "))
width2 = int(input("What is the WIDT... |
### Bir listeyi düzleştiren (flatten) fonksiyon yazımı ###
def flatten(liste):
output = []
for i in liste:
if type(i) is list:
output.extend(flatten(i))
else:
output.append(i)
return output
### Verilen listenin içindeki elemanları tersine döndüren bir fonksiyon yazım... |
import unittest
from point import Point
class TestPoint(unittest.TestCase):
def test_newpoint(self):
Point([3,4])
Point([0,0])
Point([1.23,-3.134])
Point([0,0,3, 1241, 235402])
def test_dist_sq(self):
p = Point([3,4])
q = Point([0,0])
self.asser... |
'''
Author: Eric P. Nichols
Date: Feb 8, 2008.
Board class.
Board data:
1=white, -1=black, 0=empty
first dim is column , 2nd is row:
pieces[1][7] is the square in column 2,
at the opposite end of the board in row 8.
Squares are stored and manipulated as (x,y) tuples.
x is the column, y is the row.
'''
cla... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# In[5]:
df=pd.read_csv('worldhapiness.csv')
print(df)
# In[6]:
# Highlighting the maximum values of each attribute of the data set.
def highlight_max(s):
is_max = s... |
# Crie um algoritmo que leia quanto deinheiro uma pessoa tem na carteira e mostre
# quantos Dólares ela pode comprar. Considerando US$1,00 = R$3,27
real = float(input('Informe quanto você tem na carteira: R$ '))
conversao = real / 3.27
print('Você pode comprar US$ {}'.format(conversao))
|
# Crie um algoritmo que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit
c = float(input('Informe a temperatura em °C:' ))
f = 9 * c / 5 + 32
print('A temperatua de {} °C corresponde a {} °F'.format(c ,f))
|
# Crie um programa que leia um numero de 0 a 9999 e mostre na tela cada um dos digitos separados.
#
# Ex:
# Digite um numero: 1834
# unidade: 4
# dezena: 3
# centena: 8
# milhar: 1
numero = int(input('Digite um numero inteiro: '))
u = numero // 1 % 10 # // = Divisão inteira no Python
d = numer... |
def max_number(list1):
counter=0
max1=list1[0]
while counter<len(list1):
if list1[counter]>max1:
max1=list1[counter]
counter=counter+1
return max1
def two_list(list1,list2):
value=list1+list2
call_function=max_number(value)
return (call_function)
def odd_even(list... |
num=int(input("enetr any number"))
a=1
i=0
b=0
while i <num:
c=a+b
a=b
b=c
i=i+1
print(a) |
import re
class 翻译:
字典 = {
r"Traceback \(most recent call last\):": r"回溯 (最近的调用在最后):",
r"AttributeError: '(.*)' object has no attribute '(.*)'": r"属性错误: '\1'个体没有'\2'属性",
r"NameError: name '(.*)' is not defined": r"命名错误: 命名'\1'未定义",
r"NameError: free variable '(.*)' referenced before... |
# coding=utf-8
# 函数compute_lcs,用于计算两个列表的Longest Common Subsequence (LCS)
def _compute_lcs(source, target):
"""Computes the Longest Common Subsequence (LCS).
Description of the dynamic programming algorithm:
https://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
source: List of source tok... |
###** August 5, 2021 - intersection of two arrays II **###
# Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
# intersectionOfArrays([1,2,2,1], [2,2]) => [2,2]
#... |
import random
import time
class Area:
def __init__(self, alignment, terrain=None, name=None):
self.alignment = alignment
self.name = name
self.terrain = terrain
self.capacity = 3
def __repr__(self):
if self.terrain == "capital":
return "*"
... |
# 双指针交换
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
p1=0
p2=len(s)-1
while p1<p2:
s[p1],s[p2]=s[p2],s[p1]
p1+=1
p2-=1
... |
class Solution(object):
'''
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for k in range(len(nums)):
if(nums[k]==target):
return k
if(nums[k]>target):
... |
class Solution(object):
# 先排序,merge
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
intervals.sort(key = lambda i : i[0])
rs = [intervals[0]]
for v in intervals[1:]:
if v[0] <= rs[-1][1]:
... |
from typing import List
class implementStrStr:
def start(self,haystack:str,needle:str)->int:
if not needle:
return 0
lh=len(haystack)
ln=len(needle)
for k in range(lh-ln+1):
if(haystack[k:k+ln]==needle):
return k
return -1
haystack=... |
from typing import List
'''
class Solution:
def fizzBuzz(self, n:int)->List[str]:
# ans list
ans = []
# Dictionary to store all fizzbuzz mappings
fizz_buzz_dict = {3 : "Fizz", 5 : "Buzz"}
for num in range(1,n+1):
num_ans_str = ""
for key in fizz_b... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
# 双指针前后 + 三指针遍历
'''
l=0
r=len(nums)-1
k=0
while k<=r:
if nums[k]==0:
... |
s=input("Enter a string ")
#Method 1 ---> Using loop
for i in range(len(s)):
if(i%2==0): #zero based indexing
print(s[i],end='')
#Method 2--> slicing
print(s[::2])
|
from math import pi
radius = input('radius = ')
print('area = ',float(radius)**2*pi)
|
def abc_generator():
yield 'a'
yield 'b'
yield 'c'
for char in abc_generator():
print(char)
print('##-----------------------##')
def num_generator(num=1):
while num:
yield num
num +=1
for num in num_generator():
if num !=5:
print(num)
if num == 10:
print('... |
import requests
import urllib
import urllib.request
from bs4 import BeautifulSoup
url = ""
request = requests.get(url)
html_content = request.text
soup = BeautifulSoup(html_content, "html.parser")
#Find the tag and its attribute
print(soup.findAll("div", class_ = "paragraph"))
#Use this model to find a particular... |
___author__ = 'Bar Adar'
import unittest
from challenge2 import *
"""
A class for testing.
"""
class TestFindingPeople(unittest.TestCase):
def test_equal_names(self):
self.assertEqual(1, countUniqueNames("Deborah", "Egli", "Deborah", "Egli", "Deborah Egli"))
def test_equal_with_whitespaces(self):
... |
# 2 numbers add program using function-- return sum-- Input from the user
def add ():
num1 = int(input('Enter a first number : '))
num2 = int(input('Enter a second number : '))
result = num1 + num2
return result
tottal_result = add()
print(tottal_result)
|
# 2 numbers add program using function-- return sum--
def add (num1, num2):
result = num1 + num2
return result
A = 50
B = 60
total_result = add(A, B)
print(total_result) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.